blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
aa894da9a10e60a2de42056c4c9be3733f1631fb
meltedfork/Python-1
/Python Assignments/dictionary_basics/dictionary_basics.py
287
4.15625
4
def my_dict(): about = { "Name": "Nick", "Age": "31", "Country of birth": "United States", "Favorite Language": "Italian" } # print about.items() for key,data in about.iteritems(): print "My", key, "is", data my_dict()
true
3bed285f835cc5e500ae14e0daaa9d738a53efcf
TamizhselvanR/TCS
/alternative_series.py
967
4.25
4
''' For Example, consider the given series: 1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17, … This series is a mixture of 2 series – all the odd terms in this series form a Fibonacci series and all the even terms are the prime numbers in ascending order. Now write a program to find the Nth term in this series. ''' def primefn(n): new_term = n // 2 count = 0 for i in range(1, 1000): flag = 1 if (i > 1): for j in range(2, i): if (i % j == 0): flag = 0 break if (flag == 1): prime = i count += 1 if (count == new_term): print(prime) break def fibbo(n): new_term = (n+1) // 2 t1 = 0 t2 = 1 for i in range(1, new_term + 1): next = t1 + t2 t1 = t2 t2 = next print(t1) n = int(input()) if(n % 2 == 0): primefn(n) else: fibbo(n)
true
7d6a397767236554fe50d29a043682d9ac471a6c
ddilarakarakas/Introduction-to-Algorithms-and-Design
/HW3/q4.py
1,373
4.21875
4
import random swap_quicksort=0 swap_insertion=0 def quick_sort(array, low, high): if low<high: pivot = rearrange(array, low, high) quick_sort(array, low, pivot - 1) quick_sort(array, pivot + 1, high) def rearrange(array,low,high): global swap_quicksort p = array[high] left = low-1 for i in range(low,high): if array[i]<p: left+=1 array[i], array[left] = array[left], array[i] swap_quicksort += 1 array[left+1], array[high] = array[high], array[left+1] swap_quicksort += 1 return left+1 def insertionSort(arr): global swap_insertion for i in range(2,len(arr)): current=arr[i] position=i-1 while position>=1 and current < arr[position]: swap_insertion+=1 arr[position+1] = arr[position] position=position-1 arr[position+1]=current if __name__ == "__main__": arr1=[] for i in range(0,1000): arr1=[] for i in range(0,1000): arr1.append(random.randint(0,10000)) arr2=arr1[:] quick_sort(arr1,0,len(arr1)-1) insertionSort(arr2) print("Average count for quicksort = " + str(swap_quicksort/1000)) print("Average count for insertionsort = " + str(swap_insertion/1000)) #It is a bit slow because it works with 1000 sizes.
true
fa6192cee5ee11b819b8037ad641333ded8f9422
Bpara001/Python_Assgn
/03 Functions/varargs_start.py
445
4.1875
4
# Demonstrate the use of variable argument lists # TODO: define a function that takes variable arguments def addition(*args): result = 0 for arg in args: result +=arg return result def main(): # TODO: pass different arguments print(addition(5,10,20,30)) print(addition(1,2,3)) # TODO: pass an existing list Mynums = [4 , 8 ,10 ,12] print (addition(*Mynums)) if __name__ == "__main__": main()
true
504e64c3d0be1d03c044c54594c9af6785539da2
samsnarrl22/Beginner-Projects
/Song Variables.py
1,116
4.28125
4
# Storing attributes about a song in Variables # First create variables for each of the characteristics that make up a song title = "Ring of Fire" artist = "Jonny Cash" # These variables are strings which can be seen due to the "" album = "The Best of Johnny Cash" genre = "Country" time_in_seconds = 163 # time_in_seconds is an integer beats_per_minute = 103.5 # beats_per_minute is a float track_number = "1" # These variables will appear like integers but are strings year_released = "1967" # Now its time to print these variables so we can see them in the console print(title) print(artist) print(album) print(genre) print(time_in_seconds) print(beats_per_minute) print(track_number) print(year_released) """This shows us the information stored in the variable. However it is just a random list at this point so it would like better if they were defined""" print("Title: ", title) print("Artist: ", artist) print("Album: ", album) print("Genre: ", genre) print("Track length (s): ", time_in_seconds) print("BPM", beats_per_minute) print("Track Number: ", track_number) print("Year Released: ", year_released)
true
88812cfba755cc4b06a8724ea3def8d51f18dd68
JinHoChoi0104/Python_Study
/Inflearn/chapter05_02.py
850
4.21875
4
# Chapter05-02 # 파이썬 사용자 입력 # Input 사용법 # 기본 타입(str) # ex1 # name = input("Enter Your Name: ") # grade = input("Enter Your Grade: ") # company = input("Enter Your Company name: ") # print(name, grade, company) # ex2 # number = input("Enter number: ") # name = input("Enter name: ") # print("type of number", type(number) * 3) # print("type of name", type(name)) # ex3 # first_number = int(input("Enter number1: ")) # second_number = int(input("Enter number2: ")) # # total = first_number + second_number # print("first_number + second_number: ", total) # ex4 # float_number = float(input("Enter a float number: ")) # print("input float: ", float_number*3) # print("input type: ",type(float_number)) # ex5 print("FirstName - {0}, LastName - {1}".format(input("Enter first name: "), input("Enter second name: ")))
true
9eb1e8456b09fc34a2d11c5c41c63d85704cc70c
JoyP7/BasicPythonProjects
/rock_paper_scissors.py
1,408
4.28125
4
from random import randint #create a list of play options t = ["Rock", "Paper", "Scissors"] #assign a random play to the computer computer = t[randint(0,2)] #set player to False player = False p_score = 0 c_score = 0 #here is the game while player == False: #case of Tie player = input("Rock, Paper, or Scissors?") if player == computer: print("That's a Tie!") elif player == "Rock": if computer == "Paper": print("You lose! You got covered by", computer) c_score += 1 else: print("You won! Your", player, "smashes", computer) p_score += 1 elif player == "Paper": if computer == "Scissors": print("You lose! You got cut by", computer) c_score += 1 else: print("You won! Your ", player, "covered", computer) p_score += 1 elif player == "Scissors": if computer == "Rock": print("You lose! You got smashed by", computer) c_score += 1 else: print("You won! Your",player, "cut", computer) p_score += 1 else: print("That's not a valid option! Please choose one three available options.") print("You:", p_score, "Computer:", c_score) #start the game over #set the player to False since it's True after a run player = False computer = t[randint(0,2)]
true
b0652b6f3148c4213d754423c27d40276ef4baab
ddtriz/Python-Classes-Tutorial
/main.py
1,223
4.375
4
#BASIC KNOWLDEGE ABOUT CLASSES #What is a class? class firstClass():#Determine a class in the code by using [class] name = "" identification = 0 print ("hello") firstClass.name = "John" firstClass.identification = 326536123 #If you print the firstClass you'll get something like <class '__main__.firstClass> #That's because you're printing the class and not any attribute of it. #You can call them by using the [.] after firstClass #if you have a print in your class and you call it #(firstClass()) #it will act like a function. (In this case it will print #hello, as I wrote print("hello") in the class.) firstClass() #OUTPUT:[ hello ] print(firstClass)#OUTPUT:[ <class '__main__.firstClass> ] #Output using Attributes! :D print(firstClass.name)#OUTPUT:[ Jhon ] print(firstClass.identification)#OUTPUT:[ 326536123 ] #You can also create objects to use better classes. #It's like importing something as something. Example: #import pyaudio as pA #pA.listen() bla bla bla #You can do the same with classes. Just assign a name to the class: fC = firstClass() fC.name = "Rose" fC.identification = 112233445566 #That's all the basics about the classes, at least I think. #hope you like it and understood it.
true
f7f462a0cc00c3d68b8d0a5bd282151eea24fb9a
ECastro10/Assignments
/rock_paper_scissors_looped.py
2,085
4.125
4
#import random and computer signs list import random signchoices = ["rock", "paper", "scissors"] player1_score = 0 comp_score = 0 game = 0 while game < 3: hand1 = input("Enter rock, paper, or scissors Player1 > ").lower() compSign = random.choice(signchoices) print("Computer chooses " + compSign) if hand1 == "": print("Nothing was entered for Player 1, invalid game") elif hand1 == compSign: print("Tie!") elif hand1 == "rock" and compSign == "paper": print("Computer wins!") comp_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) elif hand1 == "paper" and compSign == "rock": print("Player1 wins!") player1_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) elif hand1 == "paper" and compSign == "scissors": print("Computer wins!") comp_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) elif hand1 == "scissors" and compSign == "paper": print("Player1 wins!") player1_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) elif hand1 == "scissors" and compSign == "rock": comp_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) print("Computer wins!") elif hand1 == "rock" and compSign == "scissors": print("Player1 wins!") player1_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) if comp_score > player1_score: print("Computer Wins!!!") else: print("You win, it was a fluke")
true
150747e7e7b6a368e0ac7af28d4a4d10358acdbb
mohitsharma2/Python
/Book_program/max_using_if.py
413
4.59375
5
# Program to accept three integers and print the largest of the three.Make use of only if statement. x=float(input("Enter First number:")) y=float(input("Enter Second number:")) z=float(input("Enter Third number:")) max=x if y>max: max=y if z >max: max=z print("Largest number is:",max) """ output===> Enter First number:12 Enter Second number:54 Enter Third number:45 Largest number is: 54.0 """
true
d2db2c0608a6ad6ca1f9c423c55ec4aeffef3939
mohitsharma2/Python
/Book_program/divisor.py
1,068
4.28125
4
#program to find the multiles of a number(divisor) out of given five number. print("Enter the five number below") num1=float(input("Enter first number:")) num2=float(input("Enter second number:")) num3=float(input("Enter third number:")) num4=float(input("Enter fourth number:")) num5=float(input("Enter fifth number:")) divisor=float(input("Enter divisor number:")) count=0 remainder=num1 % divisor if remainder ==0: print(num1) count+=1 remainder=num2 % divisor if remainder ==0: print(num2) count+=1 remainder=num3 % divisor if remainder ==0: print(num3) count+=1 remainder=num4 % divisor if remainder ==0: print(num4) count+=1 remainder=num5 % divisor if remainder ==0: print(num5) count+=1 print(count,"multiple of ",divisor,"found") """ output===> Enter the five number below Enter first number:10 Enter second number:5 Enter third number:15 Enter fourth number:20 Enter fifth number:26 Enter divisor number:5 10.0 5.0 15.0 20.0 4 multiple of 5.0 found """
true
e8fc3a72648cfd8d9b857012a27031e7a08b8357
mohitsharma2/Python
/Blackjack.py
1,629
4.3125
4
""" Name: Blackjack Filename: Blackjack.py Problem Statement: Play a game that draws two random cards. The player then decides to draw or stick. If the score goes over 21 the player loses (goes ‘bust’). Keep drawing until the player sticks. After the player sticks draw two computer cards. If the player beats the score they win. Data: Not required Extension: Aces can be 1 or 11! The number used is whichever gets the highest score. Hint: Not Available Algorithm: Not Available Boiler Plate Code: Not Available Sample Input: Not Available Sample Output: Not Available """ import random input1='' list1=[1,2,3,4,5,6,7,8,9,10,11,12,13] while(input1==''): a=random.choice(list1) b=random.choice(list1) if (a+b)>=21: print('you bust') else: c=random.choice(list1) d=random.choice(list1) if (a+b)>(c+d): print('You win') print('you have',a+b,'computer has',c+d) else: print('You loose') print('you have',a+b,'computer has',c+d) input1=input('Press "Enter" to continue:') ''' output=========================================================== You loose you have 7 computer has 16 Press "Enter" to continue: you bust Press "Enter" to continue: You loose you have 6 computer has 16 Press "Enter" to continue: You loose you have 19 computer has 22 Press "Enter" to continue: you bust Press "Enter" to continue: You loose you have 11 computer has 13 Press "Enter" to continue: You win you have 14 computer has 9 Press "Enter" to continue:h '''
true
3817d594c6261e8d7a51bd820a4c0ed2bfe36dd0
mohitsharma2/Python
/Book_program/sqrt.py
930
4.25
4
# program to calculate and print roots of a quadratic equcation : ax^2 + bx + c=0 (a!=0) import math print("for quadratic equcation : ax^2 + bx + c=0,enter cofficient below:") a=int(input("Enter a:")) b=int(input("Enter b:")) c=int(input("Enter c:")) if a==0: print("Value of 'a' should not be zero.") print("\n Aborting !!!") else: value = b*b - 4 * a * c if value>0: root1=(-b+math.sqrt(value))/(2*a) root2=(-b-math.sqrt(value))/(2*a) print("Roots are real and unequal") print("Root1=",root1,"Root2=",root2) elif value==0: root1= -b/(2*a) print("Roots are real and Equal") print("Root1=",root1,"Root2=",root1) else: print("Roots are Complex and Imaginary") """ output===> Enter a:3 Enter b:5 Enter c:2 Roots are real and unequal Root1= -0.6666666666666666 Root2= -1.0 """
true
0f1f74514cd78b6f952e24f923975d82a18e1260
mohitsharma2/Python
/Book_program/identify_character.py
474
4.3125
4
""" program to print whether a given character is an uppercase or a lowercase character or a digit or any other special character. """ inp1=input("Enter the Character:") if inp1>='A' and inp1<="Z" : print("You entered upper case character.") elif inp1>='a' and inp1<='z' : print("You entered lower case character.") elif inp1>='0' and inp1<='9' : print("You entered numeric character.") else: print("You entered special character.") 0
true
260ea2d6275282bb8ecc34d2488bbdca52459a45
mohitsharma2/Python
/gravity_cal.py
224
4.21875
4
# Gravity Calculator Acceleration=float(input('enter the Acceleration in m/s^2')) Time=float(input('enter the time in seconds ')) distance=(Acceleration*Time*Time )/ 2 print('object after falling for 10 seconds=',distance)
true
2c894119b5321d953fa1346d722d42f190de8c38
alexdavidkim/Python3-Notes
/numeric_types/booleans.py
2,949
4.53125
5
# All objects in Python have a Truthyness or Falsyness. All objects are True except: # None # False # 0 # Empty sequences (list, tuple, string, etc) # Empty mapping types (dictionary, set, etc) # Custom classes that implement a __bool__ or __len__ that returns False or 0 # Therefore, every built-in class in Python has a __bool__ or __len__ function # if 27: # print("I'm True!") # print(bool(None)) # if 0: # print("This won't print!") # my_empty_list = [] # if my_empty_list: # print("This won't print!") # my_truthy_list = [None] # if my_truthy_list: # print("Hello from my_truthy_list!") # class A: # def __bool__(self): # return self == 0 # a = A() # print(bool(a)) # The boolean operators are: not, and, or # Operator preference (Use parentheses even when not necessary): # () # < > <= >= == != in is # not # and # or # True and False will evaluate first becoming True or False # print(True or True and False) # Circuits - booleans are circuits (See Part 1 - Functional - Section 4:55) meaning a closed circuit allows electricity to flow through the circuit (True), and an open circuit cuts the circuit (False). A short-circuit evaluation example would be with the or operator. b doesn't need to be evaluated because a is already True. # a = -1 # b = False # if a or b: # print('Open circuit!') # Inversely, a False value on the left side of the equation with the and operator will short-circuit and always evaluate False. # a = False # b = True # if a and b: # print('This won\'t print') # else: # print('This short circuited!') # Imagine we want to populate data to a view function and we want to make sure there is always something to show the user. about_table_field represents an empty field in a database, therefore the about_me variable we use to populate data to the user will have the fallback data of 'n/a' # about_table_field = '' # about_me = about_table_field or 'N/A' # Again used as a fallback to ensure that b is not None # a = None # b = a or 1 # or - X or Y: if X is truthy, returns X, otherwise evaluates Y and returns it # print('a' or [1,2]) # print('' or [1,2]) # x = '' or 'N/A' # if x: # print(x) # else: # print('Error') # and - X and Y: if X is falsy, return X, otherwise if X is True, evaluate Y and return it # print(None and 100) # print(True and 'Evaluating Y') # We want to avoid a zero division error therefore, we can write an if statement or use the and operator # a = 2 # b = 0 # if b == 0: # print(0) # else: # print(a/b) # print(b and a/b) # We want to return the first character from a string if it exists # s1 = None # s2 = '' # s3 = 'Hello World' # print((s1 and s1[0]) or '') # print((s2 and s2[0]) or '') # print((s3 and s3[0]) or '') # not operator is different than and/or. not is not part of the bool class. and/or both return one of the objects. not returns True/False print(not True)
true
629d204d76e6545d713ec221aebff2c8bd627a6a
cstarr7/daily_programmer
/hard_2.py
1,852
4.28125
4
# -*- coding: utf-8 -*- # @Author: Charles Starr # @Date: 2016-03-08 23:51:13 # @Last Modified by: Charles Starr # @Last Modified time: 2016-03-09 00:14:55 #Your mission is to create a stopwatch program. #this program should have start, stop, and lap options, #and it should write out to a file to be viewed later. import datetime as dt class Stopwatch(object): #object contains time and does simple operations def __init__(self): self.start_time = None def start(self): if self.start_time == None: self.start_time = dt.datetime.utcnow() else: print 'The watch is already running.' def lap(self): if not self.start_time == None: delta = dt.datetime.utcnow() - self.start_time print delta.total_seconds() print 'The clock is still running' else: print 'The clock is not running' def stop(self): if not self.start_time == None: delta = dt.datetime.utcnow() - self.start_time() self.start_time = None print delta.total_seconds() print 'The clock is stopped' else: print 'The clock is not running.' def reset(self): if not self.start_time == None: self.start_time = dt.datetime.utcnow() print 'The clock has restarted.' else: print 'The clock is not running.' def menu(stopwatch): #displays a menu for stopwatch operations while True: print 'Stopwatch options:' print '1. Start' print '2. Lap' print '3. Stop' print '4. Reset' print '5. Quit' user_choice = raw_input('Select an operation: ') if user_choice == '1': stopwatch.start() elif user_choice == '2': stopwatch.lap() elif user_choice == '3': stopwatch.stop() elif user_choice == '4': stopwatch.reset() elif user_choice == '5': break else: print 'Please enter a valid menu option.' def main(): #creates stopwatch and sends it to the menu stopwatch = Stopwatch() menu(stopwatch) main()
true
a388858021542a586073ae6f0cea563423bedd17
cstarr7/daily_programmer
/easy_267.py
1,223
4.28125
4
# -*- coding: utf-8 -*- # @Author: Charles Starr # @Date: 2016-07-06 23:20:28 # @Last Modified by: Charles Starr # @Last Modified time: 2016-07-06 23:53:49 #https://www.reddit.com/r/dailyprogrammer/comments/4jom3a/20160516_challenge_267_easy_all_the_places_your/ def input_place(): #ask user what place their dog got, check validity, return int while True: fail_msg = 'Enter a positive integer' try: user_input = int(raw_input('What place did your dog get?')) except: print fail_msg return user_input def not_places(place, show_size=100): #returns list of places that your dog didn't finish place_list = [] for not_place in range(1, show_size+1): if place == not_place: continue place_string = str(not_place) suffix = 'th' important_digits = place_string if len(place_string) > 1: important_digits = place_string[-2:] if important_digits[-1] == '1' and important_digits != '11': suffix = 'st' elif important_digits[-1] == '2' and important_digits != '12': suffix = 'nd' elif important_digits[-1] == '3' and important_digits != '13': suffix = 'rd' place_list.append(place_string + suffix) return place_list def main(): size = input_place() print not_places(size) main()
true
bcdf93ea36a3afa6632324742bf0b9acae82a7ef
nguyent57/Algorithms-Summer-Review
/square_root_of_int.py
1,388
4.28125
4
def square_root(x): # BASE CASE WHEN X == 0 OR X == 1, JUST RETURN X if (x == 0 or x == 1): return(x) # STARTING VALUE FROM 2 SINCE WE ALREADY CHECKED FOR BASE CASE i = 2 # PERFECT SQUARE IS THE SQUARE NUMBER ON THE RIGHT OF THE GIVEN NUMBER # SAY, WE HAVE 7 -> PERSQUARE IS 9, 3 PERSQUARE IS 4 persquare = 2 # AS LONG AS PERFECT SQUARE IS <= X -> INCREMENT ith BY ONE AND # CALCULATE THE PERFECT SQUARE, EXIT WHILE LOOP WHEN LARGER. while (persquare <= x): i += 1 persquare = i * i # CALCULATE THE ROOT OF THE PERSQUARE sqrtpersquare = (persquare/i) # DIVIDE NUMBER BY THE GIVEN NUMBER xnew = x/sqrtpersquare # THEN CALCULATE THAT NUMBER'S AVG BY ADDING THAT NUMBER WITH THE ROOT OF PERSQUARE avgxnew = (xnew + sqrtpersquare)/2 # REPEAT THE PROCESS: X/AVGNEW = AVGNEW-> (AVGXNEW + AVGNEW)/2 avgnew = x /avgxnew newavg = round((avgxnew + avgnew)/2,3) sqrt = newavg*newavg if sqrt>x: avgnew = x/newavg newavg = round((newavg + avgnew) / 2, 3) sqrt = newavg * newavg if sqrt > x: newavg = round((newavg + avgnew) / 2, 3) return (newavg) return(newavg) # Driver Code x = 4 print(square_root(x)) x = 5 print(square_root(x)) x = 7 print(square_root(x)) x = 9 print(square_root(x))
true
fd525d79b0b9b683440ef6e52a268feb1550e4e3
nguyent57/Algorithms-Summer-Review
/shortest_palindrome.py
1,682
4.21875
4
# RUN TIME # USE: TAKE THE REVERSE STRING OF THE GIVEN STRING AND BRING IT TO THE END # TO SEE WHAT IS THE SUFFIX OF THE STRING COMPARING TO THE PREFIX OF THE STRING # REMOVE THE SUFFIX --> SHORTEST PALINDROME def palindrom(str): # CREATE AN EMPTY STRING FOR PALINDROME reverse = '' # FOR EVERY ITEM IN GIVEN STR for char in str: # EMPTY STR WILL ADD THE NEXT ELEMENT TO CURRENT AVAILABLE IN w reverse = char + reverse #print(reverse) """ DAD -> DAD => IF THE REVERSE OF THE GIVEN STRING IS EXACTLY THE SAME => ALREADY PALINDROME """ if reverse == str: print(str) """ BANANA -> BANANAB => COMPARE EVERY CHAR OF REVERSE STRING EXCEPT THE LAST CHAR WITH => STARTING OF THE INDEX 1 OF ORIGINAL STRING => IF THE SAME, THEN CREATE A STRING OF ORIGINAL STRING WITH THE LAST ELEMENT OF THE REVERSE STR """ elif reverse[:-1] == str[1:]: print(reverse[:-1]) pal = str + reverse[-1] print(pal) """ ANAA -> AANAA => COMPARE EVERY CHAR OF REVERSE STRING FROM INDEX 1 WITH => EVERY CHAR OF ORIGINAL STR EXCEPT LAST CHAR => IF THE SAME, THEN CREATE A STRING OF THE FIRST CHAR OF REVERSE STR WITH ORIGINAL STR """ elif reverse[1:] == str[:-1]: pal = reverse[1] + str print(pal) """ TOM -> TOMOT => ELSE, CREATE A STRING OF ORIGINAL STR WITH REVERSE STR STARTING FROM INDEX 1 """ else: pal = str + reverse[1:] print(pal) str=input() palindrom(str)
true
7bbe8947b97d2bd27773d003f3b3eedf9eaa712a
nguyent57/Algorithms-Summer-Review
/all_unique_char.py
814
4.25
4
# METHOD 1: USING A FUNCTION # RUN TIME: O(n) # CREATE A FUNCTION THAT WOULD TAKE ANY STRING def all_unique_char(str): # CREATE A DICTIONARY TO STORE THE COUNT OF EACH CHARACTER count = {} # CREATE AN ARRAY TO STORE THE CHAR char = [] # FOR EVERY ITEM IN STRING for i in str: # IF THE COUNT EXIST -> INCREMENT BY ONE if i in count: count[i] +=1 # ELSE SET IT TO ONE AND APPEND THE CHAR INTO THE ARRAY else: count[i] = 1 char.append(i) # FOR EVERY ITEM IN CHAR ARRAY for i in char: # IF THE COUNT IS LARGER THAN 1 if count[i] > 1: # RETURN FALSE return False # OR RETURN TRUE IF EXISTS return True str = 'TOM' print(all_unique_char(str))
true
0f6633f03b958e1c606f41ec4c82e660b6dfd350
UdayQxf2/tsqa-basic
/BMI-calculator/03_BMI_calculator.py
2,937
5.125
5
""" We will use this script to learn Python to absolute beginners The script is an example of BMI_Calculator implemented in Python The BMI_Calculator: # Get the weight(Kg) of the user # Get the height(m) of the user # Caculate the BMI using the formula BMI=weight in kg/height in meters*height in meters Exercise 3: Write a program to calculate the BMI by accepting user input from the keyboard and check whether the user comes in underweight ,normal weight or obesity. Create functions for calculating BMI and check the user category. i)Get user weight in kg ii)Get user height in meter iii) Use this formula to calculate the BMI BMI = weight_of_the_user/(height_of_the_user * height_of_the_user) iv)Use this level to check user category #)Less than or equal to 18.5 is represents underweight #)Between 18.5 -24.9 indicate normal weight #)Between 25 -29.9 denotes over weight #)Greater than 30 denotes obese # Hint i)Create a function to get the input ii)Create one more function to calculate BMi iii)Create one more function for checking user category """ def get_input_to_calcluate_bmi(): "This function gets the input from the user" print("Enter the weight of the user in Kgs") # Get the weight of the user through keyboard weight_of_the_user = input() # Get the height of the user through keyboard print("Enter the height of the user in meters") height_of_the_user = input() return weight_of_the_user,height_of_the_user def calculate_bmi(weight_of_the_user,height_of_the_user): "This function calculates the BMI" # Calculate the BMI of the user according to height and weight bmi_of_the_user = weight_of_the_user/(height_of_the_user * height_of_the_user) # Return the BMI of the user to the called function return bmi_of_the_user def check_user_bmi_category(bmi): "This function checks if the user is underweight, normal, overweight or obese" if bmi <= 18.5: print("The user is considered as underweight") elif bmi > 18.5 and bmi < 24.9: print("The user is considered as normal weight") elif bmi > 25 and bmi <= 29.9: print("The user is considered as overweight") elif bmi >=30: print("The user is considered as obese") # Program starts here if __name__ == "__main__": # This calling function gets the input from the user weight_of_the_user,height_of_the_user = get_input_to_calcluate_bmi() # This calling function stores the BMI of the user bmi_value = calculate_bmi(weight_of_the_user,height_of_the_user) print("BMI of the user is :",bmi_value) # This function is used to calculate the user's criteria check_user_bmi_category(bmi_value)
true
fba5a5017e2f9b1f5b91a3f877e45a7c63f758eb
UdayQxf2/tsqa-basic
/BMI-calculator/02_BMI_calculator.py
1,797
5.09375
5
""" We will use this script to learn Python to absolute beginners The script is an example of BMI_Calculator implemented in Python The BMI_Calculator: # Get the weight(Kg) of the user # Get the height(m) of the user # Caculate the BMI using the formula BMI=weight in kg/height in meters*height in meters Exercise 2: Write a program to calculate the BMI by accepting user input from the keyboard and check whether the user comes in underweight ,normal weight overweight or obesity. i)Get user weight in kg ii)Get user height in meter iii) Use this formula to calculate the bmi BMI = weight_of_the_user/(height_of_the_user * height_of_the_user) iv)Use this level to check user category #)Less than or equal to 18.5 is represents underweight #)Between 18.5 -24.9 indicate normal weight #)Between 25 -29.9 denotes over weight #)Greater than 30 denotes obese """ print("Enter the weight of the user in Kg's") # Get the weight of the user through keyboard weight_of_the_user = input() # Get the height of the user through keyboard print("Enter the height of the user in meters") height_of_the_user = input() # Calculate the BMI of the user according to height and weight bmi = weight_of_the_user/(height_of_the_user * height_of_the_user) print("BMI of the user is :",bmi) # Check the user comes under under weight, normal or obesity if bmi <= 18.5: print("The user is considered as underweight") elif bmi > 18.5 and bmi < 24.9: print("The user is considered as normal weight") elif bmi > 25 and bmi <= 29.9: print("The user is considered as overweight") elif bmi >=30: print("The user is considered as obese")
true
bd1268244c535712fa6616edbf7b2a015867b30e
mikephys8/The_Fundamentals_pythonBasic
/week7/9-1.py
1,005
4.1875
4
__author__ = 'Administrator' tup = ('a', 3, -0.2) print(tup[0]) print(tup[1]) print(tup[2]) print(tup[-1]) print('-------------') print(tup[:2]) print(tup[1:2]) print(tup[1:3]) print(tup[2:3]) print(tup[2:]) print('-------------') # tuples arer immutable!!cannot be assigned with other # value in opposition with list # tup[0] = 'b' print('-------------') # lists have a lot of methods print(dir(list)) print('\n\n') # but tuples only have count and index print(dir(tuple)) print('-------------') for item in tup: print(item) print('\n') print('The length of tup is: ' + str(len(tup))) print('-------------') for i in range(len(tup)): print('The number of i is: ' + str(i)) print('The tuple in index ' + str(i) +' contains: ' + str(tup[i])) print('-------------') # if you want to create a tuple in repl print((1,2)) # only one element tuple(it just parenthesizes the mathematical expression print((1)) # to create on element tuple print((1,)) # empty tuple(do not require comma) print(())
true
035b6c28e1b373fef200773cdc73a940a98d8f7c
arrpitsharrma/PreCourse_1
/Exercise_4.py
1,528
4.25
4
# Time Complexity : not sure # Space Complexity : not sure # Did this code successfully run on Leetcode : yes # Any problem you faced while coding this : had a hard time dealing with tree, I get stuck when I come across trees and linked list for basic things sometimes # Python program to insert element in binary tree class newNode(): def __init__(self, data): self.key = data self.left = None self.right = None """ Inorder traversal of a binary tree""" def inorder(temp): if temp is None: return inorder(temp.left) print(temp.key, end= " ") inorder(temp.right) """function to insert element in binary tree """ def insert(temp,key): y = None x = temp node = newNode(key) while x is not None: y = x if key < x.key: x = x.left else: x = x.right if y is None: y = node elif key < y.key: y.left = node else: y.right = node return y # Driver code if __name__ == '__main__': root = newNode(10) root.left = newNode(11) root.left.left = newNode(7) root.right = newNode(9) root.right.left = newNode(15) root.right.right = newNode(8) print("Inorder traversal before insertion:", end = " ") inorder(root) key = 12 insert(root, key) print() print("Inorder traversal after insertion:", end = " ") inorder(root)
true
a662d0ba108c778eabc880a98c81767894b9e31e
jon-rutledge/Notes-For-Dummies
/Python/ListsAndStrings.py
1,198
4.1875
4
#strings and lists testList = list('Hello') print(testList) print(testList) #strings are immutable data types, they cannot be modified #if you need to modify a string value, you need to create a new string based the original #References #with one off variables you can do something like this spam = 42 cheese = spam spam = 100 print(cheese) #cheese retains the value of 42 as it is not a reference to 'spam' but #instead its own variable and value #with lists this does not work spam = [0,1,2,3,4,5] cheese = spam cheese[1] = 'TEST' print(cheese) print(spam) #spam also changes because the REFERENCES to the list is in both spam and cheese #think of you assigning an set of addresses to spam and cheese #by changing the value of something in the list, the addresses stay the same #import Copy #by using the copy module we can actually truly copy a list and act on it #without modifiying the original list import copy spam = [1,2,3,4] cheese = copy.deepcopy(spam) cheese.append('TEST') print(cheese) print(spam) #lists can also exist on multiple lines spam = [1, 2, 3] #also can conitnue on new lines by using \ print('This is line 1 and ' + \ 'this is line 2')
true
34f8a256264e0da898d07b32d613371bc0fecde5
SACHSTech/ics2o1-livehack-2-Kyle-Lue
/problem2.py
1,066
4.5
4
""" ------------------------------------------------------------------------------- Name: problem2.py Purpose: Determine the sides of the traingle and determine if it is a triangle Author: Lue.Kyle Created: 23/02/2021 ------------------------------------------------------------------------------ """ #Input the lengths of the three sides print ("Welcome to the Triangle Checker") side_1 = int(input("Enter the length of the first side: ")) side_2 = int(input("Enter the length of the second side: ")) side_3 = int(input("Enter the length of the third side: ")) #Calculate if it is a triangle depending on the sides and output the result if side_3 > side_2 + side_1: print ("The figure is not a triangle") elif side_2 > side_3 + side_1: print ("The figure is not a triangle") elif side_1 > side_2 + side_3: print ("The figure is not a triangle") elif side_1 <= side_2 + side_3: print ("The figure is a triangle") elif side_2 <= side_1 + side_3: print ("The figure is a triangle") elif side_3 <= side_1 + side_3: print ("The figure is a triangle")
true
5ba6cfe289b2cec8dd68df78d11253cbb7a5ec0c
ashutosh4336/python
/coreLanguage/ducktyping/lambda.py
1,324
4.28125
4
""" --> What is Lambda function ? Lambda function are Namesless or Anonymous functions 'lambda' is not a function it is a keywork in python --> Why they are Used. One-Time-Use ==> Throw away function as they're only used Once IO of other function ==> They're also passed as inputs or returned as outputs of other High-Order function Reduce Code Size ==> The body of Lambda function is written in a single line --> Syntax lambda arguments: expression lambda : 'Specify purpose' lambda a1: "Specify use of a1" lambda a1...n: "Specify use of a1...n" """ # x = lambda a: a * a # # def x(a): return a * a # print(x(3)) """ Anonymous function with in user defined function """ def a(x): return(lambda y: x + y) # s = a(5) # print(s(5)) # # c = a(10) # print(c(8)) ''' filter() ==> used to filter the given iterables(list, set, etc) with the help of another function passed as an argument to test all the elements to be true or false ''' ''' # lambda with filter mylist = [1,5,3,5,4,6] newlist = list(filter(lambda x: (x % 2 == 0), mylist)) # print(newlist) ''' ''' # lambda with Map() mylist = [1, 2 ,3, 4, 5, 6, 7, 8, 9] newlist = list(map(lambda x: (x / 3 != 2), mylist)) print(newlist) ''' # lambda with reduce() import functools a = functools.reduce(lambda x,y: x+y, [23, 56, 48, 91, 1]) print(a)
true
90b19ba814eb586ddae8d0b97068b71901a8627c
Satishchandra24/CTCI-Edition-6-Python3
/chapter1/oneAway.py
2,799
4.15625
4
"""There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. EXAMPLE pale, ple-> true pales, pale -> true pale,bale-> true pale,bake-> false""" def oneAway(str1,str2): #In this function based on the length of the str2 comapared to str1 one we will call delete,replace or insert len1=len(str1) len2=len(str2) if len1==len2+1: return checkDelete(str1,str2) elif len1==len2: return checkReplace(str1,str2) elif len1==len2-1: return checkInsert(str1,str2) else: return False def checkDelete(str1,str2):#This function will see if two strings are same after we delete on char a={}#define map b={} for i in range(len(str1)): a[i]=str1[i] #In this map we will have key->val pair For the first string 1->'first char in string' ... for i in range(len(str2)):#In this map we will have key->val pair for the second string if str1[i]==str2[i]:#We will add a char at pos i if the char at the position is same as in str1 b[i]=str2[i] else: b[i+1]=str2[i]#We will add the char at pos i+1 since it will be same at that pos count=0 for i in b.keys(): try: if b[i]==a[i]: count=count+1 except: return False if count==len(str2): #We will count the same vals for keys in both map and return true if the count is same return True return False def checkInsert(str1,str2): a={} b={} for i in range(len(str1)): #a[str1[i]]=i a[i]=str1[i] for i in range(len(str2)): if i==len(str2)-1: b[i]=str2[i] break if str1[i]==str2[i]: #b[str2[i]]=i b[i]=str2[i] else: #b[str2[i]]=i+1 b[i]=str2[i+1] count=0 print(a) print(b) for i in b.keys(): try: if b[i]==a[i]: count=count+1 except: pass print(count) if count==len(str2)-1: return True return False def checkReplace(str1,str2): a={} b={} for i in range(len(str1)): a[i]=str1[i] for i in range(len(str2)): if str1[i]==str2[i]: b[i]=str2[i] else: #b[str2[i]]=i+1 b[i]=str2[i] count=0 for i in b.keys(): try: if b[i]==a[i]: count=count+1 except: pass if count==len(str2)-1: return True return False str1="ppqr" str2="pppr" output=oneAway(str1,str2) if output: print("Yes they are on edit away") else: print("No, they are not one edit away")
true
bd897223c898fe68168a467fd41f7b1923bcf6ee
rwedema/master_ontwikkeling
/informatica_start/jupyter_notebooks/informatics01/WC_05/random_dna_template.py
1,231
4.21875
4
#!/usr/bin/env python3 #imports import sys import random def calc_gc(seq): #calculates the percentage of GC in the sequence #finish this function yourself pass def generate_dna(len_dna): #generates random DNA with GC percentage between 50 and 60% #some comments removed. Write your own comments! gc_perc = ? while gc_perc < ? ? gc_perc > ?: bases = ? #make an empty list (avoid string concatenation) dna = ? #start for loop to make random letter for i in range(?): #add a random letter to the list dna.append(?) #make a string from the list sequence = "".join(?) #calculate GC percentage. If this is either < 50 or > 60, the loop will start again! #if this is between 50 and 60 the loop will stop! gc_perc = ?(?) #pack both sequence and GC percentage in a tuple and return return (?, ?) def main(): #generate a dna sequence with length 20 dna = generate_dna(20) #print first element from tuple. This is the sequence. print("sequence:", dna[0]) #print second element from tuple. This is the GC percentage. print("GC percentage:", dna[1]) return main()
true
ea4d338b844b370f06bdfd9368fac0c1f154a8a7
rwedema/master_ontwikkeling
/informatica_start/jupyter_notebooks/informatics01/WC_03/03_dna_convert_functions_solution.py
1,748
4.15625
4
#!/usr/bin/env python3 #solution for DNA convert #imports import sys def is_valid_dna(seq): #checks if all letters of seq are valid bases valid_dna = "ATCG" for base in seq: if not base in valid_dna: #the break statement is not needed anymore as return automatically breaks the loop. return False #the loop is finished so we are sure no non-valid bases were encountered. #we can return True now return True def reverse_dna(seq): #reverse string rev_dna = seq[::-1] return rev_dna def complement_dna(seq): #return complement dna bases = {'A':'T', 'T':'A', 'C':'G', 'G':'C'} comp_dna_list = [] for base in seq: comp_base = bases[base] comp_dna_list.append(comp_base) comp_dna = "".join(comp_dna_list) return comp_dna def reverse_complement_dna(seq): rev_dna = (reverse_dna(seq)) rev_comp_dna = (complement_dna(seq)) return rev_comp_dna def main(): #catch command line arguments args = sys.argv #check if sequence is given if len(args) < 2: print("please provide a sequence") print("Program stopping...") sys.exit() #dna string is second argument dna = args[1] #now convert to upper: dna = dna.upper() #check if bases are valid: if not is_valid_dna(dna): print("Non-valid characters found") print("Program stopping...") sys.exit() #call functions rev_dna = reverse_dna(dna) comp_dna = complement_dna(dna) rev_comp_dna = reverse_complement_dna(dna) #print output print("original:", dna) print("reverse:", rev_dna) print("complement:", comp_dna) print("reverse complement:", rev_comp_dna) main()
true
e977567aa32b21b6b0a557963a5cd3a01982bca1
boluwaji11/Py-HW
/HW4/HW4-5_Boluwaji.py
674
4.5
4
# This program calculates the factorial of nonnegative integer numbers # Start # Get the desired number from the user # Use a repetition control to calculate the factorial # End # ============================================================== print('Welcome!') number = int(input('\nPlease enter the desired positive number: ')) # Input validation while number <= 0: print("Please ensure the number is a positive whole number") number = int(input('\nPlease enter the desired positive number: ')) factorial = 1 # The accumulator for occurance in range(1, number+1, 1): factorial *= occurance print() print('The Factorial(!) of', number, 'is', factorial)
true
adf9d5898e666f01c6fb4e8c5a7976fe0242283f
boluwaji11/Py-HW
/HW3/HW3-4_Boluwaji.py
1,191
4.4375
4
# This program converts temperature in degrees Celsius to Fahrenheit. # Start # Get the temperature in celsius from the user # Calculate the Fahrenheit equivalent of the inputted temperature # Check the result # If the result is more than 212F # Display "Temperature is above boiling water temperature" # If the result is less than 32F # Display "Temperature is below freezing temperature" # End BOILING_TEMP = 212 # A Named Constant for boiling temperature FREEZING_TEMP = 32 # A Named Constant for freezing temperature celsius_temperature = float(input("Please enter the temperature to convert (in Celsius): ")) convert_fahrenheit = (celsius_temperature * 1.8) + 32 print("\nThe Converted Temperature is ", format(convert_fahrenheit,'.2f'), "F", sep='') if convert_fahrenheit > BOILING_TEMP: print(format(convert_fahrenheit,'.2f'), "F", " is above boiling water temperature", sep='') elif convert_fahrenheit < FREEZING_TEMP: print(format(convert_fahrenheit,'.2f'), "F", " is below freezing temperature", sep='') else: print(format(convert_fahrenheit,'.2f'), "F", " is neither below freezing nor above boiling temperatre", sep='')
true
0cd27f6603efb0bea65eb78aceff2e0ccb25a884
boluwaji11/Py-HW
/HW5/HW5-3_Boluwaji.py
1,712
4.1875
4
# This program calculates dietary information # Start # Define main function # In the main function,get fat and carbohydrate information from the user # Pass fat to calories_fat and call it # Pass carbohydrate to calories_carbs and call it # Call calories_fat and calories_carbs in main # Define the calories_fat function # Calculates the calories using fat and displays the result # Define the calories_carbs function # Calculates the calories using carbohydrate and displays the result # Call the main function # End #================================================================== # The welcome message and header print('Welcome! This program calculates dietary information') print('------------------------------------------------------') print() # Define the global constants FAT_CONVERSION_FACTOR = 9.0 CARB_CONVERSION_FACTOR = 4.0 # Define the main function of the program def main(): fat = float(input('Please enter your daily fat consumption (in grams): ')) carbohydrate = float(input('Please enter your daily carbohydrate consumption (in grams): ')) print() calories_fat(fat) calories_carb(carbohydrate) # Define the calories_fat function def calories_fat(fat_amount): calories_from_fat = fat_amount * FAT_CONVERSION_FACTOR print('The Amount of Calories in', fat_amount, 'gram(s) of Fat consumed is', format(calories_from_fat, '.2f')) # Define the calories_carb function def calories_carb(carbs): calories_from_carbs = carbs * CARB_CONVERSION_FACTOR print('The Amount of Calories in', carbs, 'gram(s) of Carbohydrate consumed is', format(calories_from_carbs, '.2f')) # Call the main function main()
true
2eece337929e5f114a7a8a2e4dc0e33d4634906b
boluwaji11/Py-HW
/HW6/HW6-1-a_Boluwaji.py
1,476
4.15625
4
# This program saves different video running times for Kevin to the video_running_times.txt file. # Start # Define the main function # Ask Kevin for the number of short videos he's working with # Open a file to save the videos # Enter the different times and write it to file # Close the file # Notify Kevin of the written file # Call the main function # End # ================================================================================================== # The headers and introductory message print('Welcome, Kevin! This program saves a sequence of videos running times into file.') print('--------------------------------------------------------------------------------') print() # Define the main funtion def main(): num_videos = int(input('To begin, how many videos do you have in this project, Kevin?: ')) # Number of short videos to be saved video_file = open('video_running_times.txt', 'w') # Creates the file to save the running times # For loop to get each video's running time and write it to the video_running_times.txt file. print('Please enter the running time for each video') print() for count in range(1, num_videos + 1): run_time = float(input('Video #' + str(count) + ': ')) video_file.write(str(run_time) + '\n') # Close the file. video_file.close() print() print('The video times have been saved to video_running_times.txt') # Call the main function. main()
true
9f4e5d5c93d94f01f61e924974c34d869a5fa0b1
piyush546/Machine-Learning-Bootcamp
/Basic Python programs/listreverse.py
341
4.21875
4
# -*- coding: utf-8 -*- """ A program to demonstrate list content reversing and optimizing the reversing method of string """ # To take user name input in single command using split name = input().split() # to print the name string after reversing name = name[::-1] name = " ".join(name) print(name) # Input = piyush kumar # Output = kumar piyush
true
68742eb158b913e6e9f3f85f80d669eef018fa2d
piyush546/Machine-Learning-Bootcamp
/Basic Python programs/style.py
290
4.15625
4
# -*- coding: utf-8 -*- """ A program to use some str methods """ # variables to store strings to be styled First_string = input("Enter the string:") # To print the strings after styling print(str.upper(First_string)) print(str.lower(First_string)) print(str.capitalize(First_string))
true
34b635354da1a433f5a0ebc96a481141bf48f1be
Neeraj-Chhabra/Class_practice
/task2.py
454
4.125
4
def square_root(a): z=1 x=a/2 while(z==1): y = (x + (a/x)) / 2 if (abs(y-x) < 0.0000001): print(x) z=2 return(x) else: x=y # print("new value not final", x) # print(y) def test_square_root(a): return(math.sqrt(a)) root=int(input("enter the number for the squareroot")) import math d=square_root(root) print(type(d)) b=test_square_root(root) print(type(b)) c=abs(d-b) print(type(c)) print(root,"\t", d, "\t", b ,"\t", c)
true
30822abe9cc556240dca0da5ade9f60371c89676
RayNieva/Python
/printTable.py
2,165
4.4375
4
#!/usr/bin/env python """Project Table Printer Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this:""" import pprint def main(): tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] tableData firstColumn=tableData[0] firstColumn secondColumn=tableData[1] secondColumn thirdColumn=tableData[2] thirdColumn thirdColumn[0] len(firstColumn[0]) numOfColumnWidths1=len(firstColumn) numOfColumnWidths2=len(secondColumn) numOfColumnWidths3=len(thirdColumn) columnWidths1=[] columnWidths2=[] columnWidths3=[] #columnWidths.append(n) for i in range(numOfColumnWidths1): print(len(firstColumn[i])) n=len(firstColumn[i]) columnWidths1.append(n) print(columnWidths1) columnWidths1.sort(reverse=True) columnWidths1[0] for i in range(numOfColumnWidths2): print(len(secondColumn[i])) n=len(secondColumn[i]) columnWidths2.append(n) print(columnWidths2) columnWidths2.sort(reverse=True) print(columnWidths2[0]) for i in range(numOfColumnWidths3): print(len(thirdColumn[i])) n=len(thirdColumn[i]) columnWidths3.append(n) print(columnWidths3) columnWidths3.sort(reverse=True) print(columnWidths3[0]) # 'A String'.rjust(columnWidths[0] + 2) """ for i in range(numOfColumnWidths): print(firstColumn[i],secondColumn[i],thirdColumn[i]) """ for i in range(numOfColumnWidths1): print(firstColumn[i].rjust(columnWidths1[0] + 2),secondColumn[i].rjust(columnWidths2[0] + 2),thirdColumn[i].rjust(columnWidths3[0] + 2)) if __name__ == '__main__': main()
true
e3d1598b8864ed8a3bd40b2e9f41894b5028c326
nuneza6954/cti110
/M4T4 P4HW2_ PoundsKilos _AliNunez.py
951
4.3125
4
# Program will display a table of pounds starting from 100 through 300 # (with a step value of 10) and their equivalent kilograms. # The formula for converting pounds to kilograms is: # kg= lb/2.2046 # Program will do a loop to display the table. # 03-07-2019 # CTI-110 P4HW2 - Pounds to Kilos Table # Ali Nunez # Declare Variables pounds = 0 kilogram = 0 # Get input from user pounds = float(input("Enter weight in pounds:")) # Calculation: convert pounds to kilograms kilogram = pounds/2.2046 for pounds in range(100, 300, 10): kilogram = pounds / 2.2046 print("Pounds:", pounds, " Kilograms:" ,format(kilogram,'.2f'),sep="") # Declared my variables # pounds = 0 # kilogram = 0 # Prompt user for input to "Enter weight in pounds" # Used a calculation to pounds to kilograms # kilogram = pounds / 2.2046 # Displayed conversion for every tenth value strarting at 100 to 300 # using a for loop.
true
6c3e99015bf3c5a132b18f7d55dddf6b7e9952d5
narasimhareddyprostack/Ramesh-CloudDevOps
/Python/Fours/Set/four.py
208
4.40625
4
s = {1,2,3} s.update('hello') print(s) #The Python set update() method updates the set, adding items from other iterables. ''' adding items form other iterable objects, such as list, set, dict, string '''
true
96be9ec136c4bd58d90e56a1f1b6b7e07a08f23a
djndl1/CSNotes
/algorithm/introAlgorithm/python-implementation/bubble_sort.py
1,005
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import operator def optimized_bubble_sort(arr, comp=operator.le): if len(arr) < 2: return arr n = len(arr) while n > 1: next_n = 0 for i in range(1, n): if not comp(arr[i-1], arr[i]): # if out of order, then swap arr[i-1], arr[i] = arr[i], arr[i-1] next_n = i n = next_n # any pair between [next_n:] is in order and will remain unchanged # arr[next_n] is greater than arr[:next_n] so that swapping occurs # only in arr[:next_n] return arr def naive_bubble_sort(arr, comp=operator.le): if len(arr) < 2: return arr while True: swapped = False for j in range(1, len(arr)): if not comp(arr[j-1], arr[j]): # swap whenever out of order arr[j-1], arr[j] = arr[j], arr[j-1] swapped = True if not swapped: # until not swapped break return arr
true
99b71f3b737456b6916d801929159ba767e85a55
TBobcat/Leetcode
/CountPrimes.py
1,234
4.25
4
def countPrimes( n): """ :type n: int :rtype: int """ prime_list=is_prime(n) # print(prime_list) return len(prime_list) def is_prime(n): # based on Sieve of Eratosthenes result = [] if n <=1 : return [] # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n)] p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n , p): prime[i] = False p += 1 prime[0]= False prime[1]= False # Print all prime numbers for p in range(n): if prime[p]: result.append(p) #Use print(p) for python 3 return result if __name__ == '__main__': num1=10 num2=0 num3=1 # print(is_prime(0)) # print(is_prime(1)) # print(is_prime(2)) print(countPrimes(num1)) print(countPrimes(num2)) print(countPrimes(num3)) else: pass
true
b4ab5c05860d95676bdc24b9813226002a49fc0f
fgarcialainez/RabbitMQ-Python-Tutorial
/rabbitmq/tutorial1/receive.py
1,191
4.3125
4
#!/usr/bin/env python """ In this part of the tutorial we'll write two small programs in Python; a producer (sender) that sends a single message, and a consumer (receiver) that receives messages and prints them out. It's a "Hello World" of messaging. https://www.rabbitmq.com/tutorials/tutorial-one-python.html """ import pika def callback(ch, method, properties, body): print(" [x] Received %r" % body.decode("utf-8")) def main(): # Open a connection with RabbitMQ server connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() # Create a 'hello' queue from which the messages will be received channel.queue_declare(queue='hello') # Receive messages from 'hello' queue in the callback function channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True) # Enter a never-ending loop that waits for data and runs callbacks whenever necessary print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() # Main script if __name__ == '__main__': try: main() except KeyboardInterrupt: print('[*] Interrupted')
true
a7b0001a9a204a24607419abd86197464487e184
oskip/IB_Algorithms
/Merge.py
1,152
4.1875
4
# Given two sorted integer arrays A and B, merge B into A as one sorted array. # # Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. # TIP: C users, please malloc the result into a new array and return the result. # If the number of elements initialized in A and B are m and n respectively, the resulting size of array A after your code is executed should be m + n # # Example : # # Input : # A : [1 5 8] # B : [6 9] # # Modified A : [1 5 6 8 9] class Solution: # @param A : list of integers # @param B : list of integers # @return A modified after the merge def merge(self, A, B): if len(A) == 0: return B if len(B) == 0: return A result = [] i = 0 j = 0 while i < len(A) and j < len(B): if A[i] <= B[j]: result.append(A[i]) i += 1 else: result.append(B[j]) j += 1 for a in range(i, len(A)): result.append(A[a]) for b in range(j, len(B)): result.append(B[b]) return result
true
81afe70547b88e2216f90d93e901d89282ae7628
oskip/IB_Algorithms
/RevListSample.py
914
4.25
4
# Reverse a linked list. Do it in-place and in one-pass. # # For example: # Given 1->2->3->4->5->NULL, # # return 5->4->3->2->1->NULL. # # PROBLEM APPROACH : # # Complete solution code in the hints # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param A : head node of linked list # @return the head node in the linked list def reverseList(self, A): if A == None: return None head = A previous = A A = A.next while A != None: nextEl = A.next self.delete(A, previous) head = self.insertAtHead(A, head) A = nextEl return head def insertAtHead(self, node, head): node.next = head return node def delete(self, node, previous): previous.next = node.next node.next = None
true
9431f2f8c0c10c09878199baf743b0d1f3510781
pr1malbyt3s/Py_Projects
/Advent_of_Code/2021/1_2021.py
1,183
4.4375
4
# AOC 2021 Day 1 import sys # This function is used to read a file input from the command line. It returns the file contents as a list of lines. def read_file() -> list: if len(sys.argv) != 2: print("Specify puzzle input file") sys.exit(-1) else: # Open file at command line position 1: with open(sys.argv[1], 'r') as f: # Append each stripped line to a list: input_list = [line.strip() for line in f] return input_list # Part 1: Count the number of times a depth measurement increases from the previous measurement. def sonar_count(input_list:list) -> int: count = 0 for a, b in zip(input_list, input_list[1:]): if(b>a): count += 1 return count # Part 2: Count the number of times the sum of measurements in a three-measurement sliding window increases. def sliding_window(input_list:list) -> int: count = 0 for a, b in zip(input_list, input_list[3:]): if(b>a): count += 1 return count def main(): input_list = list(map(int, read_file())) print(sonar_count(input_list)) print(sliding_window(input_list)) if __name__ == "__main__": main()
true
abbda68a1e2777bae2bdc1ec1903232c81d7d42f
pr1malbyt3s/Py_Projects
/Runcode.ninja/Simple_Addition.py
1,116
4.1875
4
#!/usr/bin/env python3 # This script accepts an input file of mixed value pairs separated by lines. # It check that each value pair can be added and if so, prints the corresponding sum. import sys from decimal import Decimal # Create a master list of all number pairs. numList = [] # Type check function to determine if value is integer or decimal. # After determining type, value is translated and returned. def type_check(x): try: if isinstance(int(x), int) == True: return int(x) except ValueError: try: if isinstance(float(x), float) == True: return Decimal(x) except ValueError: return # Read file contents. with open(sys.argv[1], 'r') as f: for line in f: # Create a sublist of the number pair on each line. subNumList = [] # Perform type_check on each number pair. for num in line.split(): subNumList.append(type_check(num)) # Ensure appended line has two values and None is not one of them. if len(subNumList) == 2 and None not in subNumList: numList.append(subNumList) # Print the subList pairs. for subList in numList: print(subList[0] + subList[1])
true
dd49bbd3212bd1c77674f3b8f68ef134a6f7b253
pr1malbyt3s/Py_Projects
/Runcode.ninja/Simple_Cipher.py
579
4.28125
4
#!/usr/bin/env python3 # This script is used to decode a special 'cipher'. # The cipher pattern is each first word in a new sentence. import sys # Create a list to store each parsed first word from an input file. message = [] with open(sys.argv[1], 'r') as f: cipher = f.read() # While reading file, split the file by the '.' character, appending each first word (index 0) to the message list. cipherSplit = cipher.split(". ") for i in range(len(cipherSplit)): message.append(cipherSplit[i].split()[0]) # Print the message via the message list. print(*message, sep = " ")
true
ac0ef21febfd8f26eeec7ae27c2bee55b35ab46f
pr1malbyt3s/Py_Projects
/Runcode.ninja/Third_Letter_Is_A_Charm.py
946
4.21875
4
#!/usr/bin/env python3 # This script accepts an input file containing words with misplaced letters. # Conveniently, the misplaced letter is always from the third position in the word and is at the beginning. import sys # rotate function to perform letter rotation on a provided string. # It first checks to ensure the string is at least three letters long. # If not, it inserts the first letter of the provided word into the third (i[2]) spot. def rotate(s): if(len(s) < 3): return s c = s[0] #print(c) a = s[1:3] #print(a) b = s[3::] #print(b) f = a + c + b return f def main(): # Read file input. with open(sys.argv[1], 'r') as f: for line in f: # List that will be used for each line. inputList = [] # Append each word to the list, rotate it, and print all words once done. for word in line.split(): inputList.append(rotate(word)) print(*inputList) f.close() if __name__ == "__main__": main()
true
812a8a7dac1e22b1bdbd9e47f3c59113b303aa0c
seaboltthomas19/Monty-Hall-Problem
/monty-hall-sim.py
1,111
4.1875
4
import random switch_was_correct = 0 no_switch_was_correct = 0 print("====================================" + "\n" + "*** Monty Hall Problem Simulator ***" + "\n" + "====================================") print("Doors to choose from: ") doors = int(input()) print("Iterations to run: ") iterations = int(input()) for i in range(0, iterations): door_array = list(range(1, doors + 1)) # make a list of every door # select a correct door at random; this will simulate the door with a prize behind it correct_door = random.randint(1, doors) # select an initial choice at random; this will simulate the door the contestant has chosen initially initial_choice = random.randint(1, doors) if initial_choice == correct_door: no_switch_was_correct = no_switch_was_correct + 1 else: switch_was_correct = switch_was_correct + 1 print("Results: \n") print("Switching was correct " + str(switch_was_correct) + " times.\n") print("The initial choice was correct " + str(no_switch_was_correct) + " times.")
true
d61a5fe6d5b68073a738d19b93e24a35695cc1d4
luckymime28/Skyjam
/skyjam.py
1,851
4.1875
4
print("- If you need more info or you're confused type 'help'") def help(): print("\n-So basically, this is my first exploit I ever created \n-My name is luckymime28, and this is my exploit skyjam.py \n-skyjam.py is a password combination maker and list creator \n-Simply follow the instructions on screen and you should be fine \n-Any questions? Ask via instagram luckymime28, sorry if I take a while.\nAlso I am in no way, shape, or form responsible if any damages occur from\nyou using my product.\n") def more_info(): print("- Level 1 is typically for those who have easy passwords\n You might want to save this one for the older people\n Typically just combines words together and generates a bunch of numbers\n") print("- Level 2 is more complex, it will include special symbols usually\n This might include weird letters in the end, beginning, special characters\n It will also generate or replace letters as numbers\n") print("- Level 3 is used for more specifics, for example,\n You know what the wording is, however not what might be the last character \n Try it out in case you forgot your password\n") print("NOTE: For more success, make sure to find more research on your target\nDon't just use this tool and input randoms as you'll be less successful!") con = input("- Push Enter To continue to the Options\n> ") if con.lower() == 'help': help() while True: con2 = input("Which exploit would you like to navigate to?\n{a} Level 1\n{b} level 2\n{c} level 3\nIf you need more info for these types\ntype 'info'\n>> ") if con2.lower() == 'a': import skyjam4 elif con2.lower() == 'b': import skyjam3 elif con2.lower() == 'c': import skyjam2 elif con2.lower() == "info": more_info() else: print("\n INVALID TRY AGAIN \n")
true
1c2ac0372cd46f24e4a6a18d3fb7808154166a31
EthanCornish/AFPwork
/Chapter4-Functions-Tutorial#1.py
759
4.125
4
# Function Tutorial # Creating a main function # In the main function print instructions and ask for a value def main(): print('Hello') print('This program will ask you for a temperature\nin fahrenheit.') print('-----------------------------------------------------------') value = int(input('Enter a value')) # Calls the other function inside the main function print(ftoc(value)) # Create a function to convert fahrenheit to celsius # All the function does is execute a specific job def ftoc(fah): #fah = int(input('Enter a tempreature')) cel = (fah-32) * (5/9) # The :.2f is rounding it too 2dp print('{0}° Fahrenheight = {1:.2f}° Celcius'.format(fah, cel)) return cel # Runs the function main()
true
5fc5f217581a224b9f22be8c91a204a7936a8885
seanmortimer/udemy-python
/python-flask-APIs/functions.py
856
4.1875
4
def hello(name): print(f'Heeyyy {name}') hello('Sean ' * 5) # Complete the function by making sure it returns 42. . def return_42(): # Complete function here return 42 # 'pass' just means "do nothing". Make sure to delete this! # Create a function below, called my_function, that takes two arguments and returns the result of its two arguments multiplied together. def my_function(x, y): return x * y print(my_function(5, 10)) # Unpacking arguments def show(*args): print (args[1]) show(1, 2, 3) def add(x, y): return x + y nums = [3, 5] print(add(*nums)) nums_dict = {'x': 7, 'y': 9} print(add(**nums_dict)) # Unpacking keyword arguments def named(**kwargs): print(kwargs) named(name="Sean", age=36) def named2(name, age): print(name, age) details = {'name': 'Caitlin', 'age': 33} named2(**details)
true
832adbc3d78e3496afb1bb180fc1e8ed42be1b76
LiamWoodRoberts/HackerRank
/Anagrams.py
741
4.125
4
'''Solution to: https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem function finds the number of anagrams contained in a certain string''' def substrings(word): strings=[] for l in range(1,len(word)): sub = [word[i:i+l] for i in range(len(word)-l+1)] strings.append(sub) return strings def anagrams(word): count = 0 #create a list of all possible words at each length words = substrings(word) for i in range(len(words)): for j in range(len(words[i])): gram = sorted(words[i][j]) for k in range(j+1,len(words[i])): if gram == sorted(words[i][k]): count+=1 return count word = 'kkkk' anagrams(word)
true
4a0e8b5efeb37c0b538ed7b264f9a39ad9d67440
Rockwell70/GP_Python210B_Winter_2019
/examples/office_hours_code/class_inheritence.py
953
4.15625
4
class rectangle: def __init__(self, width, length): self.width = width self.length = length def area(self): return self.width * self.length def present_figure(self): return f'This figure has a width of {self.width}, a length of {self.length} and an area of {self.area()}' class square(rectangle): # pass def __init__(self, side): super().__init__(side, side) # def present_square(self): # return self.present_figure() def present_figure(self): return f'{super().present_figure()}. The figure is a square.' def main(): # first_rectangle = rectangle(10, 5) # print(first_rectangle.area()) # print(first_rectangle.present_figure()) # first_square = square(10, 10) first_square = square(10) print(first_square.area()) print(first_square.present_figure()) # print(first_square.present_square()) if __name__ == '__main__': main()
true
77b412d9121baf177d930b1072f9870b7f7f6b79
Rockwell70/GP_Python210B_Winter_2019
/examples/office_hours_code/donor_models.py
2,082
4.34375
4
#!/bin/python3 ''' Sample implementation of a donor database using classes ''' class Person: ''' Attributes common to any person ''' def __init__(self, donor_id, name, last_name): self.donor_id = donor_id self.name = name self.last_name = last_name class Donation: ''' Attributes for a donation can be easily extended to support more complex properties ''' def __init__(self, amount): self.amount = amount class Donor(Person): ''' Attributes for a person who is also a donor ''' def __init__(self, donor_id, name, last_name): self.donations = [] super().__init__(donor_id, name, last_name) class DonorDB(): ''' A collection of donors ''' def __init__(self): self.all_donors = {} def add_donor(donor_collection): ''' Creates a new donor and adds it to collection ''' donor_id = input("Enter donor ID: ") name = input("Enter donor's name: ") last_name = input("Enter donor's lastname: ") new_donor = Donor(donor_id, name, last_name) if donor_id not in donor_collection.all_donors: donor_collection.all_donors[donor_id] = new_donor else: print("ERROR: Donor ID already exists") def add_donation(donor_collection): ''' Creates a new donation and adds it to a donor ''' donor_id = input("Enter donor ID: ") if donor_id not in donor_collection.all_donors: print("ERROR: Donor ID does not exist") return donation_amount = int(input("Enter the donation amount: ")) new_donation = Donation(donation_amount) donor_collection.all_donors[donor_id].donations.append(new_donation) def print_db(donor_collection): ''' Prints all donors / donations in a collection ''' for donor_info in donor_collection.all_donors.values(): print(f"Donor ID: {donor_info.donor_id}") print(f"Donor: {donor_info.name} {donor_info.last_name}") for donation_info in donor_info.donations: print(f"Donation: {donation_info.amount}")
true
38ce46230cc6f2c490b97ef27681975750f48ed7
Rockwell70/GP_Python210B_Winter_2019
/examples/office_hours_code/sunday_puzzle.py
1,425
4.1875
4
''' From: https://www.npr.org/2019/01/20/686968039/sunday-puzzle-youre-halfway-there This week's challenge: This challenge comes from listener Steve Baggish of Arlington, Mass. Take the name of a classic song that became the signature song of the artist who performed it. It has two words; five letters in the first, three letters in the second. The letters can be rearranged to spell two new words. One is a feeling. The other is an expression of that feeling. What song is it? ''' def open_song_list(song_list_file): ''' Opens a file containing song names and returns a list ''' with open(song_list_file) as text_file: song_list = text_file.read().splitlines() return song_list def find_candidates(song_list): ''' Splits each song in the list into a list of words. Checks if the song has two words and if they are the right size. Returns a list of candidate songs ''' candidate_list = [] for song in song_list: song_words = song.split(' ') if (len(song_words) == 2)and(len(song_words[0]) == 5)and(len(song_words[1]) == 3): candidate_list.append(song) return candidate_list def main(): ''' Our main execution function ''' song_file = 'signature_song.txt' top_song_list = open_song_list(song_file) candidate_songs = find_candidates(top_song_list) print(candidate_songs) if __name__ == '__main__': main()
true
eb3057689fc57e496ee0e3f64cf50ef1ef723fe1
Cody-Hayes97/Sprint-Challenge--Algorithms
/recursive_count_th/count_th.py
706
4.25
4
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): # return zero if the ength of the word is less than 2 if len(word) < 2: return 0 # if the word begins with th, recurse and search for th given everything in the word after the second index elif word[:2] == "th": return count_th(word[2:]) + 1 # otherwise keep recursing through the word, taking off the first index each time until it matches the above case else: return count_th(word[1:])
true
0a1bf196667cd63dc6f5fe840a88b74aa9593883
RutujaWanjari/Python_Basics
/RenameFileNames/rename_filenames.py
885
4.375
4
# This program demonstrates how to access files from relative path. # Also it changes alphanumeric file names to totally alphabetic names. # To successfully run this program create a directory "AllFiles" and add multiple files with alphanumeric names. from pathlib import Path import os # Path is a class from "pathlib" package. Below we are calling init() function of Path class which initializes it and # makes some memory for our work. p = Path('../RenameFileNames/AllFiles/') def rename(): for x in p.iterdir(): if x.is_file(): print(x.name) file = x.name result = ''.join([i for i in file if not i.isdigit()]) # rename is a function from "os" package rename(os.path.join(p, x.name), os.path.join(p, result)) def print_output(): for x in p.iterdir(): print(x.name) rename() print_output()
true
6d210d6f2ab4cad68112fd06c8704b62352f5d03
DmitryVlaznev/leetcode
/296-reverse-linked-list.py
1,871
4.21875
4
# 206. Reverse Linked List # Reverse a singly linked list. # Example: # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # Follow up: # A linked list can be reversed either iteratively or recursively. Could # you implement both? # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None from typing import List class Solution: @staticmethod def fromArray(values: List) -> ListNode: l = len(values) if not l: return None head = ListNode(values[0]) cur = head for i in range(1, l): cur.next = ListNode(values[i]) cur = cur.next return head @staticmethod def toArray(head: ListNode) -> List: arr = [] cur = head while cur: arr.append(cur.val) cur = cur.next return arr def reverseList(self, head: ListNode) -> ListNode: prev = None cur = head while cur: next = cur.next cur.next = prev prev = cur cur = next return prev def reverseListRecursive(self, head: ListNode) -> ListNode: return self._reverseRecursive(None, head); def _reverseRecursive(self, parent: ListNode, node: ListNode) -> ListNode: if not node: return parent head = self._reverseRecursive(node, node.next) node.next = parent return head test = Solution() # test from-to array print("[] >> ", test.toArray(test.fromArray([]))) print("[1, 2, 3] >> ", test.toArray(test.fromArray([1, 2, 3]))) # test iterative algorithm print("[3, 2, 1] >> ", test.toArray(test.reverseList(test.fromArray([1, 2, 3])))) # test recursive algorithm print("[3, 2, 1] >> ", test.toArray(test.reverseListRecursive(test.fromArray([1, 2, 3]))))
true
020377082a10915fae20031ccf7b0dc1d6424a3b
DmitryVlaznev/leetcode
/328-odd-even-linked-list.py
2,474
4.34375
4
# 328. Odd Even Linked List # Given a singly linked list, group all odd nodes together followed by # the even nodes. Please note here we are talking about the node number # and not the value in the nodes. # You should try to do it in place. The program should run in O(1) space # complexity and O(nodes) time complexity. # Example 1: # Input: 1->2->3->4->5->NULL # Output: 1->3->5->2->4->NULL # Example 2: # Input: 2->1->3->5->6->4->7->NULL # Output: 2->3->6->7->1->5->4->NULL # Note: # * The relative order inside both the even and odd groups should remain # as it was in the input. # * The first node is considered odd, the second node even and so on ... from typing import List # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: @staticmethod def fromArray(values: List) -> ListNode: l = len(values) if not l: return None head = ListNode(values[0]) cur = head for i in range(1, l): cur.next = ListNode(values[i]) cur = cur.next return head @staticmethod def toArray(head: ListNode) -> List: arr = [] cur = head while cur: arr.append(cur.val) cur = cur.next return arr def oddEvenList(self, head: ListNode) -> ListNode: if not head: return head head_odd = head head_even = head_odd.next if not head_even or not head_even.next: return head p_odd = head_odd tail_odd = p_odd p_even = head_even while p_odd: next_odd = p_even.next if p_even else None next_even = next_odd.next if next_odd else None p_odd.next = next_odd if next_odd: tail_odd = next_odd p_odd = next_odd if p_even: p_even.next = next_even p_even = next_even tail_odd.next = head_even return head_odd test = Solution() print("[1, 3, 5, 2, 4] >> ", test.toArray(test.oddEvenList(test.fromArray([1, 2, 3, 4, 5])))) print("[1, 3, 2, 4] >> ", test.toArray(test.oddEvenList(test.fromArray([1, 2, 3, 4])))) print("[1, 2] >> ", test.toArray(test.oddEvenList(test.fromArray([1, 2])))) print("[1] >> ", test.toArray(test.oddEvenList(test.fromArray([1])))) print("[] >> ", test.toArray(test.oddEvenList(test.fromArray([]))))
true
f542f1f5c756600310e472c711f84dc787cefc2d
DmitryVlaznev/leetcode
/1329-sort-the-matrix-diagonally.py
1,513
4.21875
4
# 1329. Sort the Matrix Diagonally # Medium # A matrix diagonal is a diagonal line of cells starting from some cell # in either the topmost row or leftmost column and going in the # bottom-right direction until reaching the matrix's end. For example, # the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 # matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. # Given an m x n matrix mat of integers, sort each matrix diagonal in # ascending order and return the resulting matrix. # Example 1: # Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] # Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] # Constraints: # m == mat.length # n == mat[i].length # 1 <= m, n <= 100 # 1 <= mat[i][j] <= 100 from typing import List class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: import heapq rows, cols = len(mat), len(mat[0]) r, c = rows - 1, 0 d = [-1, 0] while c < cols: hq = [] ri, ci = r, c while ri < rows and ci < cols: heapq.heappush(hq, mat[ri][ci]) ri += 1 ci += 1 ri, ci = r, c while ri < rows and ci < cols: mat[ri][ci] = heapq.heappop(hq) ri += 1 ci += 1 r += d[0] c += d[1] if r < 0: r, c, d = 0, 1, [0, 1] return mat t = Solution() print(t.diagonalSort([[3, 3, 1, 1], [2, 2, 1, 2], [1, 1, 1, 2]]))
true
c4d5b792263bd949ebe3b6bb5186121c8832307f
DmitryVlaznev/leetcode
/246-strobogrammatic-number.py
1,077
4.15625
4
# 246. Strobogrammatic Number # Easy # Given a string num which represents an integer, return true if num is # a strobogrammatic number. # A strobogrammatic number is a number that looks the same when rotated # 180 degrees (looked at upside down). # Example 1: # Input: num = "69" # Output: true # Example 2: # Input: num = "88" # Output: true # Example 3: # Input: num = "962" # Output: false # Example 4: # Input: num = "1" # Output: true # Constraints: # 1 <= num.length <= 50 # num consists of only digits. # num does not contain any leading zeros except for zero itself. class Solution: def isStrobogrammatic(self, num: str) -> bool: complements = { "1": "1", "6": "9", "8": "8", "9": "6", "0": "0", } p, q = 0, len(num) - 1 while p <= q: if num[p] not in complements or num[q] not in complements: return False if complements[num[p]] != num[q]: return False p, q = p + 1, q - 1 return True
true
2d94fb484758fb8e9d8c079a8cfa4d94fe03ebaf
DmitryVlaznev/leetcode
/702-search-in-a-sorted-array-of-unknown-size.py
1,982
4.125
4
# 702. Search in a Sorted Array of Unknown Size # Given an integer array sorted in ascending order, write a function to # search target in nums. If target exists, then return its index, # otherwise return -1. However, the array size is unknown to you. You # may only access the array using an ArrayReader interface, where # ArrayReader.get(k) returns the element of the array at index k # (0-indexed). # You may assume all integers in the array are less than 10000, and if # you access the array out of bounds, ArrayReader.get will return # 2147483647. # Example 1: # Input: array = [-1,0,3,5,9,12], target = 9 # Output: 4 # Explanation: 9 exists in nums and its index is 4 # Example 2: # Input: array = [-1,0,3,5,9,12], target = 2 # Output: -1 # Explanation: 2 does not exist in nums so return -1 # Constraints: # You may assume that all elements in the array are unique. # The value of each element in the array will be in the range [-9999, 9999]. # The length of the array will be in the range [1, 10^4]. # """ # This is ArrayReader's API interface. # You should not implement it, or speculate about its implementation # """ class ArrayReader: def __init__(self, arr): self.arr = arr def get(self, index: int) -> int: if index >= len(self.arr): return 2147483647 return self.arr[index] from utils import checkValue class Solution: def search(self, reader, target): l, r = -1, 10 ** 4 while r - l > 1: mid = l + (r - l) // 2 if reader.get(mid) >= target: r = mid else: l = mid return r if reader.get(r) == target else -1 t = Solution() reader = ArrayReader([-1, 0, 3, 5, 9, 12]) checkValue(4, t.search(reader, 9)) reader = ArrayReader([-1, 0, 3, 5, 9, 12]) checkValue(-1, t.search(reader, 2)) reader = ArrayReader([34]) checkValue(0, t.search(reader, 34)) reader = ArrayReader([43]) checkValue(-1, t.search(reader, 34))
true
aefd7af360fdf3d158e5be8fdf16a3deb939b6b9
DmitryVlaznev/leetcode
/1423-maximum-points-you-can-obtain-from-cards.py
2,553
4.125
4
# 1423. Maximum Points You Can Obtain from Cards # Medium # There are several cards arranged in a row, and each card has an # associated number of points The points are given in the integer array # cardPoints. # In one step, you can take one card from the beginning or from the end # of the row. You have to take exactly k cards. # Your score is the sum of the points of the cards you have taken. # Given the integer array cardPoints and the integer k, return the # maximum score you can obtain. # Example 1: # Input: cardPoints = [1,2,3,4,5,6,1], k = 3 # Output: 12 # Explanation: After the first step, your score will always be 1. # However, choosing the rightmost card first will maximize your total # score. The optimal strategy is to take the three cards on the right, # giving a final score of 1 + 6 + 5 = 12. # Example 2: # Input: cardPoints = [2,2,2], k = 2 # Output: 4 # Explanation: Regardless of which two cards you take, your score will # always be 4. # Example 3: # Input: cardPoints = [9,7,7,9,7,7,9], k = 7 # Output: 55 # Explanation: You have to take all the cards. Your score is the sum of # points of all cards. # Example 4: # Input: cardPoints = [1,1000,1], k = 1 # Output: 1 # Explanation: You cannot take the card in the middle. Your best score # is 1. # Example 5: # Input: cardPoints = [1,79,80,1,1,1,200,1], k = 3 # Output: 202 # Constraints: # 1 <= cardPoints.length <= 10^5 # 1 <= cardPoints[i] <= 10^4 # 1 <= k <= cardPoints.length from typing import List class Solution: # O(k^2) def maxScore2(self, cardPoints: List[int], k: int) -> int: import functools @functools.lru_cache(maxsize=None) def getMax(start, end, k): if k == 1: return max(cardPoints[start], cardPoints[end]) return max( cardPoints[start] + getMax(start + 1, end, k - 1), cardPoints[end] + getMax(start, end - 1, k - 1), ) return getMax(0, len(cardPoints) - 1, k) # O(k) def maxScore(self, cardPoints: List[int], k: int) -> int: l = len(cardPoints) leftPrefixSum = [0] * (k + 1) rightPrefixSum = [0] * (k + 1) for i in range(1, k + 1): leftPrefixSum[i] = leftPrefixSum[i - 1] + cardPoints[i - 1] rightPrefixSum[i] = rightPrefixSum[i - 1] + cardPoints[l - i] res = 0 for i in range(0, k + 1): res = max(res, leftPrefixSum[i] + rightPrefixSum[k - i]) return res t = Solution() t.maxScore([1, 2, 3, 4, 5, 6, 1], 3)
true
284ec6e03f5edb54d8ba5903235f37a74a4d4b32
DmitryVlaznev/leetcode
/902-numbers-at-most-n-given-digit-set.py
1,719
4.21875
4
# 902. Numbers At Most N Given Digit Set # Hard # Given an array of digits, you can write numbers using each digits[i] # as many times as we want. For example, if digits = ['1','3','5'], we # may write numbers such as '13', '551', and '1351315'. # Return the number of positive integers that can be generated that are # less than or equal to a given integer n. # Example 1: # Input: digits = ["1","3","5","7"], n = 100 # Output: 20 # Explanation: # The 20 numbers that can be written are: # 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. # Example 2: # Input: digits = ["1","4","9"], n = 1000000000 # Output: 29523 # Explanation: # We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, # 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, # 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. # In total, this is 29523 integers that can be written using the digits array. # Example 3: # Input: digits = ["7"], n = 8 # Output: 1 # Constraints: # 1 <= digits.length <= 9 # digits[i].length == 1 # digits[i] is a digit from '1' to '9'. # All the values in digits are unique. # 1 <= n <= 109 class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: n_as_string = str(n) n_length = len(n_as_string) dp = [0] * n_length + [1] for i in range(n_length - 1, -1, -1): for d in digits: if d < n_as_string[i]: dp[i] += len(digits) ** (n_length - i - 1) elif d == n_as_string[i]: dp[i] += dp[i + 1] return dp[0] + sum(len(digits) ** i for i in range(1, n_length))
true
aa350a3b28ad670e494ba35e8865ad519ecb1f14
DmitryVlaznev/leetcode
/701-insert-into-a-binary-search-tree.py
2,224
4.1875
4
# Insert into a Binary Search Tree # You are given the root node of a binary search tree (BST) and a value # to insert into the tree. Return the root node of the BST after the # insertion. It is guaranteed that the new value does not exist in the # original BST. # Notice that there may exist multiple valid ways for the insertion, as # long as the tree remains a BST after insertion. You can return any of # them. # Example 1: # Input: root = [4,2,7,1,3], val = 5 # Output: [4,2,7,1,3,5] # Explanation: Another accepted tree is: # Example 2: # Input: root = [40,20,60,10,30,50,70], val = 25 # Output: [40,20,60,10,30,50,70,null,null,25] # Example 3: # Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 # Output: [4,2,7,1,3,5] # Constraints: # The number of nodes in the tree will be in the range [0, 104]. # -108 <= Node.val <= 108 # All the values Node.val are unique. # -108 <= val <= 108 # It's guaranteed that val does not exist in the original BST. from utils import TreeNode, checkList, treeFromArray, treeToArray class Solution: def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: p = root if not p: return TreeNode(val) while(True): if p.val < val: if not p.right: p.right = TreeNode(val) break else: p = p.right else: if not p.left: p.left = TreeNode(val) break else: p = p.left return root # checkList([4,2,7,1,3], treeToArray(treeFromArray([4,2,7,1,3], 0))) # checkList([40,20,60,10,30,50,70], treeToArray(treeFromArray([40,20,60,10,30,50,70], 0))) # checkList([40,20,60,10,30,50,70,None,None,25], treeToArray(treeFromArray([40,20,60,10,30,50,70,None,None,25], 0))) t = Solution() checkList([4,2,7,1,3,5], treeToArray(t.insertIntoBST(treeFromArray([4,2,7,1,3], 0), 5))) checkList([40,20,60,10,30,50,70,None,None,25], treeToArray(t.insertIntoBST(treeFromArray([40,20,60,10,30,50,70], 0), 25))) checkList([42], treeToArray(t.insertIntoBST(None, 42))) checkList([4,2,7,1,3,5], treeToArray(t.insertIntoBST(treeFromArray([4,2,7,1,3,None,None,None,None,None,None], 0), 5)))
true
665b37f3e85a2bdffac567069351cfb071b1322e
DmitryVlaznev/leetcode
/970-powerful-integers.py
1,683
4.15625
4
# 970. Powerful Integers # Medium # Given three integers x, y, and bound, return a list of all the # powerful integers that have a value less than or equal to bound. # An integer is powerful if it can be represented as x^i + y^j for some # integers i >= 0 and j >= 0. # You may return the answer in any order. In your answer, each value # should occur at most once. # Example 1: # Input: x = 2, y = 3, bound = 10 # Output: [2,3,4,5,7,9,10] # Explanation: # 2 = 2^0 + 3^0 # 3 = 2^1 + 3^0 # 4 = 2^0 + 3^1 # 5 = 2^1 + 3^1 # 7 = 2^2 + 3^1 # 9 = 2^3 + 3^0 # 10 = 2^0 + 3^2 # Example 2: # Input: x = 3, y = 5, bound = 15 # Output: [2,4,6,8,10,14] # Constraints: # 1 <= x, y <= 100 # 0 <= bound <= 10^6 from typing import List from utils import checkList class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: yy = [1] if y > 1: c = 1 while c < bound: yy.append(c) c *= y res = set() c = 1 while c < bound: p = 0 while p < len(yy) and c + yy[p] <= bound: res.add(c + yy[p]) p += 1 c *= x if x > 1 else float("inf") return list(res) t = Solution() checkList([2, 3, 4, 5, 7, 9, 10], sorted(t.powerfulIntegers(2, 3, 10))) checkList([2, 4, 6, 8, 10, 14], sorted(t.powerfulIntegers(3, 5, 15))) checkList([], sorted(t.powerfulIntegers(3, 5, 0))) checkList([], sorted(t.powerfulIntegers(3, 5, 1))) checkList([2], sorted(t.powerfulIntegers(3, 5, 2))) checkList([2], sorted(t.powerfulIntegers(3, 5, 2))) checkList([2, 3, 5, 9, 17, 33, 65], sorted(t.powerfulIntegers(1, 2, 100)))
true
6ad55eb0f4b036b0c33b0f00dc24de6cd29714cb
DmitryVlaznev/leetcode
/116-populating-next-right-pointers-in-each-node.py
2,141
4.125
4
# 116. Populating Next Right Pointers in Each Node # You are given a perfect binary tree where all leaves are on the same # level, and every parent has two children. The binary tree has the # following definition: # struct Node { # int val; # Node *left; # Node *right; # Node *next; # } # Populate each next pointer to point to its next right node. If there # is no next right node, the next pointer should be set to NULL. # Initially, all next pointers are set to NULL. # Follow up: # You may only use constant extra space. # Recursive approach is fine, you may assume implicit stack space does # not count as extra space for this problem. # Example 1: # Input: root = [1,2,3,4,5,6,7] # Output: [1,#,2,3,#,4,5,6,7,#] # Explanation: Given the above perfect binary tree (Figure A), your # function should populate each next pointer to point to its next right # node, just like in Figure B. The serialized output is in level order # as connected by the next pointers, with '#' signifying the end of each # level. # Constraints: # The number of nodes in the given tree is less than 4096. # -1000 <= node.val <= 1000 # Definition for a Node. class Node: def __init__( self, val: int = 0, left: "Node" = None, right: "Node" = None, next: "Node" = None, ): self.val = val self.left = left self.right = right self.next = next class Solution: def connect(self, root: "Node") -> "Node": if not root: return None from collections import deque dq = deque() dq.append(root) while dq: l = len(dq) last_sibling = dq.popleft() if last_sibling.left: dq.append(last_sibling.left) dq.append(last_sibling.right) l -= 1 while l: n = dq.popleft() last_sibling.next = n last_sibling = n l -= 1 if last_sibling.left: dq.append(last_sibling.left) dq.append(last_sibling.right) return root
true
e4f730d10a30032bce93d1b61c55e741cde27889
DmitryVlaznev/leetcode
/1704-determine-if-string-halves-are-alike.py
1,730
4.15625
4
# 1704. Determine if String Halves Are Alike # Easy # You are given a string s of even length. Split this string into two # halves of equal lengths, and let a be the first half and b be the # second half. # Two strings are alike if they have the same number of vowels ('a', # 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains # uppercase and lowercase letters. # Return true if a and b are alike. Otherwise, return false. # Example 1: # Input: s = "book" # Output: true # Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. # Therefore, they are alike. # Example 2: # Input: s = "textbook" # Output: false # Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. # Therefore, they are not alike. # Notice that the vowel o is counted twice. # Example 3: # Input: s = "MerryChristmas" # Output: false # Example 4: # Input: s = "AbCdEfGh" # Output: true # Constraints: # 2 <= s.length <= 1000 # s.length is even. # s consists of uppercase and lowercase letters. class Solution: def halvesAreAlike2(self, s: str) -> bool: vowels = set(["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]) mid = len(s) // 2 left = right = 0 for l in s[0:mid]: if l in vowels: left += 1 for l in s[mid:]: if l in vowels: right += 1 return left == right def halvesAreAlike(self, s: str) -> bool: vowels = set(["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]) v = 0 for i in range(len(s)): d = -1 if i >= len(s) // 2 else 1 if s[i] in vowels: v += d return v == 0 t = Solution() t.halvesAreAlike("Ieai")
true
9e0bd15c3f7a2e572618ffc85fdffde3d8579b0a
MicheSi/cs-bw-unit2
/balanced_brackets.py
2,142
4.125
4
''' Write function that take string as input. String can contain {}, [], (), || Function return boolean indicating whether or not string is balance ''' table = { ')': '(', ']':'[', '}':'{' } for _ in range(int(input())): stack = [] for x in input(): if stack and table.get(x) == stack[-1]: stack.pop() else: stack.append(x) print("NO" if stack else "YES") open_list = ["[","{","("] close_list = ["]","}",")"] # Function to check parentheses def check(myStr): stack = [] for i in myStr: if i in open_list: stack.append(i) elif i in close_list: pos = close_list.index(i) if ((len(stack) > 0) and (open_list[pos] == stack[len(stack)-1])): stack.pop() else: return "Unbalanced" if len(stack) == 0: return "Balanced" else: return "Unbalanced" def isBalanced(expr): if len(expr)%2!=0: return False opening=set('([{') match=set([ ('(',')'), ('[',']'), ('{','}') ]) stack=[] for char in expr: if char in opening: stack.append(char) else: if len(stack)==0: return False lastOpen=stack.pop() if (lastOpen, char) not in match: return False return len(stack)==0 def is_matched(expression): if len(expression) % 2 != 0: return False opening = ("(", "[", "{") closing = (")", "]", "}") mapping = {opening[0]:closing[0], opening[1]:closing[1], opening[2]:closing[2]} if expression[0] in closing: return False if expression[-1] in opening: return False closing_queue = [] for letter in expression: if letter in opening: closing_queue.append(mapping[letter]) elif letter in closing: if not closing_queue: return False if closing_queue[-1] == letter: closing_queue.pop() else: return False return True
true
c317269d86f21534edc00ce2e66e14e2e3b790bd
MicheSi/cs-bw-unit2
/search_insert_position.py
1,016
4.125
4
''' Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0 ''' class Solution: def searchInsert(self, nums: List[int], target: int) -> int: # use binary search to loop through array start = 0 end = len(nums) - 1 while start <= end: mid = (start + end) // 2 # if middle num is target, return it's index if nums[mid] == target: return mid # if middle num < target, move to 2nd half of array if nums[mid] < target: start = mid + 1 # target doesn't exit, add it to end of array else: end = mid - 1 return start
true
88cf81dc127010d9bec8fd09d916a1ddeee26a8e
akimi-yano/algorithm-practice
/tutoring/mockClassmates/officehour_mock2.py
819
4.28125
4
# Valid Palindrome Removal # Return true if the input is a palindrome, or can be a palindrome with no more than one character deletion. # Zero characters can be added. # Return false if the input is not a palindrome and removing any one character from it would not make it a palindrome. # Must be done in constant space and linear time. # Example input 1: 'bbabac' # output: true # Deleting either a letter b or the letter c would make this a palindrome if it were reordered correctly. # Example input 2: 'carracers' # output: carerac rc false def is_palin(s): memo = {} for c in s: if c not in memo: memo[c]=1 else: memo[c]+=1 odd_counter = 0 for v in memo.values(): if v%2!=0: odd_counter+=1 return odd_counter<3 print(is_palin('bbabac')) print(is_palin('carracers'))
true
2b0f70093994c026f521f5936967fcc887c74444
akimi-yano/algorithm-practice
/lc/1870.MinimumSpeedToArriveOnTime.py
2,783
4.21875
4
# 1870. Minimum Speed to Arrive on Time # Medium # 152 # 49 # Add to List # Share # You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. # Each train can only depart at an integer hour, so you may need to wait in between each train ride. # For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark. # Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. # Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point. # Example 1: # Input: dist = [1,3,2], hour = 6 # Output: 1 # Explanation: At speed 1: # - The first train ride takes 1/1 = 1 hour. # - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. # - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. # - You will arrive at exactly the 6 hour mark. # Example 2: # Input: dist = [1,3,2], hour = 2.7 # Output: 3 # Explanation: At speed 3: # - The first train ride takes 1/3 = 0.33333 hours. # - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. # - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. # - You will arrive at the 2.66667 hour mark. # Example 3: # Input: dist = [1,3,2], hour = 1.9 # Output: -1 # Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark. # Constraints: # n == dist.length # 1 <= n <= 105 # 1 <= dist[i] <= 105 # 1 <= hour <= 109 # There will be at most two digits after the decimal point in hour. # This solution works: class Solution: def minSpeedOnTime(self, dist: List[int], hour: float) -> int: def helper(speed): total = 0 for i in range(len(dist) - 1): way = dist[i] total += math.ceil(way/speed) total += dist[-1]/speed return total <= hour left = 1 right = 10**7 while left < right: mid = (left+right)//2 if helper(mid): right = mid else: left = mid+1 return left if helper(left) else -1
true
683bd029ec511e1c2868af454303d95065e93c23
akimi-yano/algorithm-practice
/lc/438.FindAllAnagramsInAString.py
1,687
4.25
4
# 438. Find All Anagrams in a String # Medium # 6188 # 235 # Add to List # Share # Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order. # An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. # Example 1: # Input: s = "cbaebabacd", p = "abc" # Output: [0,6] # Explanation: # The substring with start index = 0 is "cba", which is an anagram of "abc". # The substring with start index = 6 is "bac", which is an anagram of "abc". # Example 2: # Input: s = "abab", p = "ab" # Output: [0,1,2] # Explanation: # The substring with start index = 0 is "ab", which is an anagram of "ab". # The substring with start index = 1 is "ba", which is an anagram of "ab". # The substring with start index = 2 is "ab", which is an anagram of "ab". # Constraints: # 1 <= s.length, p.length <= 3 * 104 # s and p consist of lowercase English letters. # This soluion works: from collections import Counter class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: goal= Counter(p) cur = Counter() ans = [] count = 0 for i in range(len(s)): cur[s[i]] += 1 count += 1 if count == len(p): if goal == cur: ans.append(i+1-count) cur[s[i+1-count]] -= 1 count -=1 return ans ''' s "cbaebabacd" p "abc" goal {a:1, b:1, c:0} cur {c:1, b:1, a:1} ans [] count 0 1 2 '''
true
beda2c8b84bfa3be65e93edacf33c71c524f2718
akimi-yano/algorithm-practice
/lc/isTreeSymmetric.py
2,043
4.34375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 101. Symmetric Tree # Easy # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: class Solution: def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True return self.traverse(root.left, root.right) def traverse(self, left, right): if left is None or right is None: return left is None and right is None return left.val == right.val and self.traverse(left.left, right.right) and self.traverse(left.right, right.left) # the solution below did not work for cases where there are null and structure is not even # class Solution: # def __init__(self): # self.leftArr=[] # self.rightArr=[] # def isSymmetric(self, root: TreeNode) -> bool: # if root is None: # return True # print(self.leftInorder(root.left,self.leftArr)) # print(self.rightReverseInorder(root.right,self.rightArr)) # if len(self.leftArr)!= len(self.rightArr): # return False # for i in range(len(self.leftArr)): # if self.leftArr[i]!=self.rightArr[i]: # return False # return True # def leftInorder(self, current, arr): # if current is None: # return self.leftArr # self.leftInorder(current.left,arr) # self.leftArr.append(current.val) # self.leftInorder(current.right,arr) # return self.leftArr # def rightReverseInorder(self, current, arr): # if current is None: # return self.rightArr # self.rightReverseInorder(current.right,arr) # self.rightArr.append(current.val) # self.rightReverseInorder(current.left,arr) # return self.rightArr
true
0f4bfcbc1f59afbb95c2a2d112b72e1f34c798d0
akimi-yano/algorithm-practice
/lc/111.MinimumDepthOfBinaryTree.py
2,149
4.125
4
# 111. Minimum Depth of Binary Tree # Easy # 1823 # 759 # Add to List # Share # Given a binary tree, find its minimum depth. # The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. # Note: A leaf is a node with no children. # Example 1: # Input: root = [3,9,20,null,null,15,7] # Output: 2 # Example 2: # Input: root = [2,null,3,null,4,null,5,null,6] # Output: 5 # Constraints: # The number of nodes in the tree is in the range [0, 105]. # -1000 <= Node.val <= 1000 ''' since the definition of leef is not having left or right child, we need to find the min level in which the node does not have right node or left node I did BFS using queue to find that, keeping track of the level ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 queue = deque([(root, 1)]) while queue: node, level = queue.popleft() if not node.left and not node.right: return level if node.left: queue.append((node.left, level+1)) if node.right: queue.append((node.right, level+1)) ''' I can do this using DFS as well !!! ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDepth(self, root: TreeNode) -> int: def helper(cur): if not cur.left and not cur.right: return 1 left = right = float('inf') if cur.left: left = helper(cur.left) if cur.right: right = helper(cur.right) return min(left,right) +1 if not root: return 0 return helper(root)
true
a770ed5446cb22606122f0d55488d58aff374679
akimi-yano/algorithm-practice
/examOC/examWeek1.py
2,868
4.15625
4
# Week1 Exam # Complete the 'mergeArrays' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER_ARRAY b # merge two sorted arrays def mergeArrays(a, b): ans = [] i = 0 k = 0 while len(a)>i and len(b)>k: if a[i]>= b[k]: ans.append(b[k]) k+=1 else: ans.append(a[i]) i+=1 while len(b)>k: ans.append(b[k]) k+=1 while len(a)>i: ans.append(a[i]) i+=1 return ans # # Complete the 'dnaComplement' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # AT are complement # CG are complement # Rotate the input string and swap each element with its complement # return string def dnaComplement(s): ans="" for i in range(len(s)-1,-1,-1): if s[i] == "A": ans+="T" elif s[i] == "T": ans+="A" elif s[i] == "C": ans+="G" else: ans+="C" return ans # # Complete the 'minimumStepsToOne' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER num as parameter. # # take aways:::: output has to be a variable name that is different from the input !! # //recursion passing in count - dont do it if you want to turn it into memorization # def minimumStepsToOne(num): # def helper(n,count): # if n == 1: # return count # new_count = helper(n-1,count+1) # if n%2==0: # new_count = min(new_count,helper(n//2,count+1)) # if n%3==0: # new_count = min(new_count,helper(n//3,count+1)) # return new_count # return helper(num,0) # print(minimumStepsToOne(4)) # print(minimumStepsToOne(3)) # print(minimumStepsToOne(2)) # //memorization solution - still hit the max recursion depth # def minimumStepsToOne(num): # memo = {} # def helper(n): # if n in memo: # return memo[n] # if n == 1: # return 0 # new_count = 1 + helper(n-1) # if n%2==0: # new_count = min(new_count,1 + helper(n//2)) # if n%3==0: # new_count = min(new_count,1 + helper(n//3)) # memo[n] = new_count # return new_count # return helper(num) # print(minimumStepsToOne(4)) # print(minimumStepsToOne(3)) # print(minimumStepsToOne(2)) # print(minimumStepsToOne(5400)) # // tabulation solution def minimumStepsToOne(num): tab = {1: 0} for n in range(2,num+1): temp = tab[n-1] if n%2==0: temp = min(temp,tab[n//2]) if n%3==0: temp = min(temp,tab[n//3]) temp +=1 tab[n]=temp return tab[num] print(minimumStepsToOne(8))
true
94d942c6bc11ceb1a8919f193e31a186f1a90658
akimi-yano/algorithm-practice
/lc/154.FindMinimumInRotatedSortedAr.py
2,593
4.15625
4
# 154. Find Minimum in Rotated Sorted Array II # Hard # 2147 # 315 # Add to List # Share # Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: # [4,5,6,7,0,1,4] if it was rotated 4 times. # [0,1,4,4,5,6,7] if it was rotated 7 times. # Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. # Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array. # You must decrease the overall operation steps as much as possible. # Example 1: # Input: nums = [1,3,5] # Output: 1 # Example 2: # Input: nums = [2,2,2,0,1] # Output: 0 # Constraints: # n == nums.length # 1 <= n <= 5000 # -5000 <= nums[i] <= 5000 # nums is sorted and rotated between 1 and n times. # Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why? # This solution works: ''' The idea is to use Binary Search, but here we can have equal numbers, so sometimes we need to find our minimum not in one half, but in two halves. Let us consider several possible cases of values start, mid and end. nums[start] < nums[mid] < nums[end], for example 0, 10, 20. In this case we need to search only in left half, data is not shifted. nums[mid] < nums[end] < nums[start], for example 20, 0, 10. In this case data is shifted and we need to search in left half. nums[end] < nums[start] < nums[mid], for example 10, 20, 0. In this case data is shifted and we need to search in right half. nums[end] = nums[mid], it this case we need to check the value of nums[start], and strictly speaking we not always need to search in two halves, but I check in both for simplicity of code. Complexity: time complexity is O(log n) if there are no duplicates in nums. If there are duplicates, then complexity can be potentially O(n), for cases like 1,1,1,...,1,2,1,1,....1,1. Additional space complexity is O(1). ''' class Solution: def findMin(self, nums): def bin_dfs(start, end): if end - start <= 1: self.Min = min(nums[start], nums[end], self.Min) return mid = (start + end)//2 if nums[end] <= nums[mid]: bin_dfs(mid + 1, end) if nums[end] >= nums[mid]: bin_dfs(start, mid) self.Min = float("inf") bin_dfs(0, len(nums) - 1) return self.Min
true
448467cb0445f9e81c67e1c29ff29d4545a47b88
akimi-yano/algorithm-practice
/lc/UniquePaths.py
2,518
4.40625
4
# latice path unique path problems are different problems ! # difference : # lattice path - counting the edges # robot unique path - counting the boxes (so -1) # also for lattice path, # instead of doing this ---- # if m == 0 and n == 0: # return 1 # elif m<0 or n<0: # return 0 # you can just do this --- which is more efficient # if m == 0 or n == 0: # return 1 # 1. Lattice Paths # # Prompt: Count the number of unique paths to travel from the top left # corder to the bottom right corner of a lattice of M x N squares. # # When moving through the lattice, one can only travel to the # adjacent corner on the right or down. # # Input: m {Integer} - rows of squares # Input: n {Integer} - column of squares # Output: {Integer} # # Example: input: (2, 3) # # (2 x 3 lattice of squares) # __ __ __ # |__|__|__| # |__|__|__| # # output: 10 (number of unique paths from top left corner to bottom right) # # Resource: https://projecteuler.net/problem=15 # def latticePaths(m, n): # if m == 0 and n == 0: # return 1 # elif m<0 or n<0: # return 0 # return latticePaths(m-1, n) + latticePaths(m,n-1) # # Write your code here # print(latticePaths(2,2)) # print(latticePaths(2,3)) def latticePaths(m, n): if m == 0 or n == 0: return 1 return latticePaths(m-1, n) + latticePaths(m,n-1) # Write your code here print(latticePaths(2,2)) print(latticePaths(2,3)) # 2.Unique Paths # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach # the bottom-right corner of the grid (marked 'Finish' in the diagram below). # How many possible unique paths are there? # Above is a 7 x 3 grid. How many possible unique paths are there? # Example 1: # Input: m = 3, n = 2 # Output: 3 # Explanation: # From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: # 1. Right -> Right -> Down # 2. Right -> Down -> Right # 3. Down -> Right -> Right class Solution: def __init__(self): self.memo = {} def uniquePaths(self, m: int, n: int) -> int: if m==1 or n==1: return 1 if (m, n) not in self.memo: self.memo[(m, n)] = self.uniquePaths(m-1, n) + self.uniquePaths(m, n-1) return self.memo[(m, n)]
true
201e5eb0545be43fceece844312c43566b1e0818
akimi-yano/algorithm-practice
/oc/328_Odd_Even_Linked_List.py
2,239
4.1875
4
# 328. Odd Even Linked List ''' Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Time O(N) Space O(1) Example 1: index. 1 2. 3. 4. 5 Input: 1->2->3->4->5->NULL 1. 3. 5. 2 4 Output: 1->3->5->2->4->NULL Example 2: 1 2. 3. 4. 5 Input: 2->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL ''' # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next ''' ex1) 1 2 3 4 5 [1][2][3][4][5] odd -> even 1 3 5 2 4 none ex2) 2 1 3 5 6 4 7 [1][2][3][4][5][6][7] 2 3 6 7 1 5 4 [1][3][5][7][2][4][6] possible edge case: head node could be none 0<len<10,000 return head node Time O(N) Space O(1) 1 - check which one is odd and even - temp_odd - first node - tail temp_even - second node 2 merge the 2 temp ones and return head head ---> result_head = odd even_head = even connect temp odd tail and head of the temp even ''' # incomplete code # def oddEvenList(self, head: ListNode) -> ListNode: # if head is None: # return None # temp_odd = odd_tail = head # temp_even = even_tail = head.next # result_head = odd. ----> return # even_head = even. ---> join # runner = head.next.next # counter = 3 # while runner is not None: # if counter%2!=0: # odd_tail.next = runner # odd_tail = odd_tail.next # else: # even_tail.next = runner # even_tail = even_tail.next # runner = runner.next # solution that works ! def oddEvenList(self, head: ListNode) -> ListNode: if not head: return None odd = head even = head.next result_head = odd even_head = even while even and even.next: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = even_head return result_head # print(oddEvenList())
true
241ca9304d4b204bfa717ea366abdb73046e7547
akimi-yano/algorithm-practice
/lc/1338.ReduceArraySizeToTheHalf.py
1,686
4.15625
4
# 1338. Reduce Array Size to The Half # Medium # 767 # 64 # Add to List # Share # Given an array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. # Return the minimum size of the set so that at least half of the integers of the array are removed. # Example 1: # Input: arr = [3,3,3,3,5,5,5,2,2,7] # Output: 2 # Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array). # Possible sets of size 2 are {3,5},{3,2},{5,2}. # Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array. # Example 2: # Input: arr = [7,7,7,7,7,7] # Output: 1 # Explanation: The only possible set you can choose is {7}. This will make the new array empty. # Example 3: # Input: arr = [1,9] # Output: 1 # Example 4: # Input: arr = [1000,1000,3,7] # Output: 1 # Example 5: # Input: arr = [1,2,3,4,5,6,7,8,9,10] # Output: 5 # Constraints: # 1 <= arr.length <= 10^5 # arr.length is even. # 1 <= arr[i] <= 10^5 # This solution works: class Solution: def minSetSize(self, arr: List[int]) -> int: counts = {} for num in arr: if num not in counts: counts[num] = 0 counts[num] += 1 nums = list(counts.values()) nums.sort() cur_size = len(arr) goal_size = cur_size // 2 removed = 0 while nums and cur_size > goal_size: len_lost = nums.pop() cur_size -= len_lost removed += 1 return removed
true
323585745e2d7f83533a0c8b7273619c21b8ff2b
akimi-yano/algorithm-practice
/lc/1936.AddMinimumNumberOfRungs.py
2,606
4.28125
4
# 1936. Add Minimum Number of Rungs # Medium # 123 # 9 # Add to List # Share # You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. # You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there. # Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung. # Example 1: # Input: rungs = [1,3,5,10], dist = 2 # Output: 2 # Explanation: # You currently cannot reach the last rung. # Add rungs at heights 7 and 8 to climb this ladder. # The ladder will now have rungs at [1,3,5,7,8,10]. # Example 2: # Input: rungs = [3,6,8,10], dist = 3 # Output: 0 # Explanation: # This ladder can be climbed without adding additional rungs. # Example 3: # Input: rungs = [3,4,6,7], dist = 2 # Output: 1 # Explanation: # You currently cannot reach the first rung from the ground. # Add a rung at height 1 to climb this ladder. # The ladder will now have rungs at [1,3,4,6,7]. # Example 4: # Input: rungs = [5], dist = 10 # Output: 0 # Explanation: # This ladder can be climbed without adding additional rungs. # Constraints: # 1 <= rungs.length <= 105 # 1 <= rungs[i] <= 109 # 1 <= dist <= 109 # rungs is strictly increasing. # This solution works: class Solution: def addRungs(self, rungs: List[int], dist: int) -> int: cur = 0 ans = 0 for rung in rungs: if cur+dist<rung: ans += (rung-cur-1) // dist cur = rung return ans # This solution also works: class Solution: def addRungs(self, rungs: List[int], dist: int) -> int: ''' [1,3,5,10], dist = 2 0 1 3 5 7 9 [4,8,12,16] 3 0 3 (+1) 7 (+1) 11 (+1) 15 (+1) 0 3 (+1) ''' print("PPPP") cur = 0 ans = 0 for rung in rungs: # while cur + dist < rung: # ans += 1 # cur += dist # dist * x + cur = rung // dist # x = (-cur +rung)//dist if cur+dist<rung: ans += math.ceil((rung-cur) / dist)-1 cur = rung return ans
true
a316b2d14a524e00985fd59c54d58595f3c2c4a7
ARWA-ALraddadi/python-tutorial-for-beginners
/02-How to Use Pre-defined Functions Demos/2-random_numbers.py
1,626
4.53125
5
#--------------------------------------------------------------------- # Demonstration - Random Numbers # # The trivial demonstrations in this file show how the # functions from the "random" module may produce a different # result each time they're called # Normally when we call a function with the same parameters # it produces the same answer print('The maximum of 3 and 9 is', max(3, 9)) print('The maximum of 3 and 9 is still', max(3, 9)) print('The maximum of 3 and 9 remains', max(3, 9)) print() # The random functions are the exception because they may # produce a different result each time they're called from random import randint print('A random number between 3 and 9 is', randint(3, 9)) print('Another random number between 3 and 9 is', randint(3, 9)) print('A third random number between 3 and 9 is', randint(3, 9)) print() # As a slightly more realistic example, imagine that you # needed to schedule a meeting on a certain day. Any time # between 9am and 4pm is available except 12pm, when you # have lunch. The following code will produce a random # time for the meeting that never conflicts with your # lunch break. The outcome is printed in 24-hour time. from random import choice # Pick a time between 9am and 11am, inclusive morning_time = randint(9, 11) morning_option = str(morning_time) + 'am' # Pick a time between 1pm and 4pm, inclusive afternoon_time = randint(1, 4) afternoon_option = str(afternoon_time) + 'pm' # Choose between the morning and afternoon options final_choice = choice([morning_option, afternoon_option]) #Display the outcome print("We'll meet at", final_choice)
true
15e88757e99a4285445e4641ff9e86df0c9ff134
ARWA-ALraddadi/python-tutorial-for-beginners
/03-Workshop/Workshop-Solutions/fun_with_flags.py
1,564
4.28125
4
#-------------------------------------------------------------------- # # Fun With Flags # # In the lecture demonstration program "stars and stripes" we saw # how function definitions allowed us to reuse code that drew a # star and a rectangle (stripe) multiple times to create a copy of # the United States flag. # # As a further example of the way functions allow us to reuse code, # in this exercise we will import the flag_elements module into # this program and create a different flag. In the PDF document # accompanying this file you will find several flags which can be # constructed easily using the "star" and "stripe" functions already # defined. Choose one of these and try to draw it. # # First we import the two functions we need (make sure a copy of file # flag_elements.py is in the same folder as this one) from flag_elements import star, stripe # Import the turtle graphics functions from turtle import * # Here we draw the Panamanian flag as an illustration. # # Comment: Since this is such a small example, we've hardwired all # the numeric constants below. For non-trivial programs, however, # such "magic numbers" (i.e., unexplained numeric values) are best # avoided. Named, fixed values should be defined instead. # Set up the drawing environment setup(600, 400) bgcolor("white") title("Panama") penup() # Draw the two rectangles goto(0, 200) stripe(300, 200, "red") goto(-300, 0) stripe(300, 200, "blue") # Draw the two stars goto(-150, 140) star(80, "blue") goto(150, -60) star(80, "red") # Exit gracefully hideturtle() done()
true
de5d83e72f9e97e33665e635fd5099dcfb4bec07
ARWA-ALraddadi/python-tutorial-for-beginners
/06-How to Create User Interfaces Demos/02-frustrating_button.py
1,076
4.40625
4
#---------------------------------------------------------------- # # Frustrating button # # A very simple demonstration of a Graphical User Interface # created using Tkinter. It creates a window with a label # and a frustrating button that does nothing. # # Import the Tkinter functions from tkinter import * # Create a window the_window = Tk() # Give the window a title the_window.title('Tk demo') # Create a label widget (some fixed text) whose parent # container is the window the_label = Label(the_window, text = ' Frustration! ', font = ('Arial', 32)) # Create a button widget whose parent container is the # window (the button's text turns red when active) the_button = Button(the_window, text = ' Push me ', activeforeground = 'red', font = ('Arial', 28)) # Call the geometry manager to "pack" the widgets onto # the window (using default settings for now) the_label.pack() the_button.pack() # Start the event loop to react to user inputs (in this # case by doing nothing at all) the_window.mainloop()
true
d49423bc7fc93a65763555efc2a9e6aec0ccf1a1
ARWA-ALraddadi/python-tutorial-for-beginners
/10-How to Stop Programs Crashing Demos/0-mars_lander_V5.py
2,361
4.46875
4
#--------------------------------------------------------------------# # # Mars lander example - Exception handling # # This simple program allows us to experiment with defensive # programming, assertions and exception handling. It is based on # a real-life example in which a software failure caused # a Mars lander to crash. # # To run the program the user is meant to simulate a barometer # and enter an increasing series of air pressure readings # between 0 and 100, e.g., 1, 4, 10, 50, 80, 100. # # Retro rockets will fire while the pressure equals or # exceeds 75 and will stop when the pressure reaches 100, # which is assumed to be the air pressure at ground level. # # In this version exception handling code is added to the # main loop to catch any kind of altimeter failure and # respond with a default action. # # Import the regular expression match function from re import match # Two utility functions to tell us whether the retro rockets # are on or off def retros_on(): print("-- Retro rockets are firing --") def retros_off(): print("-- Retro rockets are off --") altitude = 1000000 # initialise with a big number pressure_at_surface = 100 # constant # Calculate altitude based on atmospheric # pressure - higher pressure means lower altitude def altimeter(barometer_reading): # Assertion to raise an exception if air pressure is negative assert barometer_reading >= 0, 'Barometer failure detected!' # Return the result (if we make it this far!) return pressure_at_surface - barometer_reading # Main program to decide when to fire the retros while altitude > 0: # The default action for any kind of altimeter failure # is to assume we are at a low altitude - it's better # to waste fuel than crash! try: # Calculate the lander's altitude, if possible altitude = altimeter(int(input('Enter barometer reading: '))) except ValueError: print('** Altimeter type error - Firing retros! **') retros_on() except AssertionError: print('** Altimeter range error - Firing retros! **') retros_on() else: # Decide whether or not the retros should be firing if altitude <= 0 or altitude > 25: retros_off() else: retros_on() # We made it! print('Houston, the Eagle has landed!')
true
15eaf7c1be83f2636e171211a049ceda21eb2fe5
ARWA-ALraddadi/python-tutorial-for-beginners
/03-Workshop/Workshop-Solutions/olympic_rings.py
2,327
4.5625
5
#------------------------------------------------------------------------- # # Olympic Rings # # In this folder you will find a file "olympic_rings.pdf" which shows # the flag used for the Olympics since 1920. Notice that this flag # consists of five rings that differ only in their position and colour. # If we want to draw it using Turtle graphics it would therefore be # a good idea to define a function that draws one ring and reuse it # five times. # # Complete the code below to produce a program that draws a reasonable # facsimile of the Olympic flag. (NB: In the real flag the rings are # interlocked. Don't try to reproduce this tricky feature, just draw # rings that overlap.) # #------------------------------------------------------------------------- # Step 1: Function definition # # Define a function called "ring" that takes three parameters, an # x-coordinate, a y-coordinate and a colour. When called this function # should draw an "olympic ring" of the given colour centred on the # given coordinates. (Note that Turtle graphic's "circle" function # draws a circle starting from the cursor's current position, not # centred on the cursor's position.) Since all the circles are the # same size you can define the radius and thickness of the circle # within the function def olympic_ring(x_coord, y_coord, colour): ring_radius, ring_width = 110, 20 # pixels penup() goto(x_coord + ring_radius, y_coord) # easternmost point setheading(90) # face north width(ring_width) color(colour) pendown() circle(ring_radius) # walk in a circle to create the ring #------------------------------------------------------------------------- # Step 2: Calling the function # # Now write code to call the function five times, each time with # different coordinates and colours, to create the flag. To get # you started we have provided some of the Turtle framework. # Import the Turtle functions from turtle import * # Create the drawing window setup(1000, 650) title('"... and it\'s gold, Gold, GOLD for Australia!"') # Draw the five rings olympic_ring(-250, 60, "blue") olympic_ring(0, 60, "black") olympic_ring(250, 60, "red") olympic_ring(-125, -60, "yellow") olympic_ring(125, -60, "green") # Shut down the drawing window hideturtle() done()
true
43aaf6575d5a423e006fbe4360972d2868e7a8ff
ARWA-ALraddadi/python-tutorial-for-beginners
/08-How to Find Things Demos/08-replacing_patterns.py
2,598
4.3125
4
## Replacing patterns ## ## The small examples in this demonstration show how regular ## expressions with backreferences can be used to perform ## automatic modifications of text. from re import sub ## This example shows how to "normalise" a data representation. ## A common problem at QUT is that student numbers are ## represented in different ways, either n7654321, N7654321, ## 07654321 or 7654321. Here we show how to change all student ## numbers in some text into a common zero-prefixed format. ## (The pattern used is not very robust; it is reliable only ## if there are no numbers other than student numbers in the ## text.) student_nos = \ '''Student 02723957 is to be commended for high quality work and similarly for student n1234234, but student 1129988 needs to try harder.''' print(sub('[nN0]?([0-9]{7})', r'0\1', student_nos)) # prints "Student 02723957 is to be commended for high quality # work and similarly for student 01234234, but student # 01129988 needs to try harder." print() ## As another example of substitution and backreferencing, we ## return to the copyeditor's problem of identifying accidently ## duplicated words in text. Not all such phrases are mistakes ## so they need to be checked manually. The following script ## identifies doubled-words as before, but now surrounds them with ## asterisks to draw them to the attention of the proofreader. ## It also allows the two words to be separated by not only ## blank spaces but newline characters because such errors ## often occur at line breaks. Notice that both ends of the ## pattern are required to contain non-alphabetic characters to ## ensure that we don't match parts of words. ## The following paragraph contains several instances of accidental ## word duplication. unedited_text = \ '''Some of the great achievements of of recording in recent years have been carried out on on old records. In the the early days of gramophones, many famous people including Florence Nightingale, Tennyson, and and Mr. Glastone made records. In most cases these records, where they could be found, were in a very bad state; not not that they had ever been very good by today's standards. By applying electrical re-recording, engineers reproduced the now now long-dead voices from the wax cylinders in to to new discs, and these famous voices which were so nearly lost forever are now permanently recorded.''' print(sub(r'([^a-z])(([a-z]+)[ \n]+\3)([^a-z])', r'\1**\2**\4', unedited_text)) # prints "Some of the great achievements **of of** recording in # recent years ..."
true
d69866a1cf193e6eed2cc8abfad5b9a5c6653777
ARWA-ALraddadi/python-tutorial-for-beginners
/01-Workshop/Workshop-Solutions/cylinder_volume.py
939
4.4375
4
# Volume of a cylinder # # THE PROBLEM # # Assume the following values have already been entered into the # Python interpreter, denoting the measurements of a cylindrical # tank: radius = 4 # metres height = 10 # metres # Also assume that we have imported the existential constant "pi" # from the "math" library module: from math import pi # Write an expression, or expressions, to calculate the volume # of the tank. Print the result in a message to the screen. # A SOLUTION # # 1. Calculate the area of the end of the cylinder # (The area of a circle of radius r is pi times r squared) area = pi * (radius ** 2) # metres squared # 2. Multiply the cylinder's area by its height volume = area * height # metres cubed # 3. Print the volume in a message to the screen print("The cylinder's volume is", round(volume, 2), "metres cubed") # about 502 # Quick quiz: Why is "volume" a floating point number instead of # an integer?
true
4a1039d67f5927daf41b2aa86fde4cf9d7ead6a8
ARWA-ALraddadi/python-tutorial-for-beginners
/10-How to Stop Programs Crashing Demos/0-mars_lander_V0.py
2,269
4.34375
4
#--------------------------------------------------------------------# # # Mars lander example - No error handling # # This simple program allows us to experiment with defensive # programming, assertions and exception handling. It is based on # a real-life example in which a software failure caused # a Mars lander to crash. # # To run the program the user is meant to simulate a barometer # and enter an increasing series of air pressure readings # between 0 and 100, e.g., 1, 4, 10, 50, 80, 100. # # Retro rockets will fire while the pressure equals or # exceeds 75 and will stop when the pressure reaches 100, # which is assumed to be the air pressure at ground level. # # Here, in the program's original form, if the barometer produces # incorrect numbers when the lander is near the ground it may # hit the surface without the retro rockets being on, destroying # the craft. # # Also, if the barometer produces non-number values the whole # program will crash and control of the retro rockets will be # entirely lost. # # Finally, there's a weakness in the way the loop is programmed # which means that if the lander doesn't stop at a height of # exactly zero (e.g., if it lands in a deep crater) the retro # rockets will fire while it's on the ground, possibly toppling # the craft over. # # Two utility functions to tell us whether the retro rockets # are on or off def retros_on(): print("-- Retro rockets are firing --") def retros_off(): print("-- Retro rockets are off --") altitude = 1000000 # initialise with a big number pressure_at_surface = 100 # constant # Calculate altitude based on atmospheric # pressure - higher pressure means lower altitude def altimeter(barometer_reading): # Return the result return pressure_at_surface - barometer_reading # Main program to decide when to fire the retros while altitude != 0: # Read from the barometer (the user in this case!) air_pressure = int(input('Enter barometer reading: ')) # Calculate the lander's altitude altitude = altimeter(air_pressure) # Decide whether or not the retros should be firing if altitude == 0 or altitude > 25: retros_off() else: retros_on() # We made it! print('Houston, the Eagle has landed!')
true
70d2912f7acbaa964fa09f0d17f11f96a5e3fb26
ARWA-ALraddadi/python-tutorial-for-beginners
/05-How to Repeat Actions demos/09-uniqueness.py
1,090
4.46875
4
#--------------------------------------------------------------------# # # Uniqueness test # # As an example of exiting a loop early, here we develop a small # program to determine whether or not all letters in some text # are unique. It does so by keeping track of each letter seen and # stopping as soon as it sees a letter it has encountered before. # # Define the text to be analysed text = 'The quick brown fox jumps over the lazy dog' # Create a list of letters already seen already_seen = [] # Examine each character for character in text: # Only consider alphabetic characters if character.isalpha(): # Make the comparison case insensitive uppercase_letter = character.upper() if uppercase_letter in already_seen: # Alert the user to the duplicate and stop print('Duplicate letter found:', uppercase_letter) break else: # Tell the user that a new letter has been found and continue print('New letter found:', uppercase_letter) already_seen.append(uppercase_letter)
true
101c4d993889264c4e592564584242cb96e85754
ARWA-ALraddadi/python-tutorial-for-beginners
/12-How to do more than one thing Demos/B_scribbly_turtles.py
1,501
4.71875
5
#--------------------------------------------------------------------# # # Scribbly turtles # # As a simple example showing that we can create two independent # Turtle objects, each with their own distinct state, here # we create two cursors (turtles) that draw squiggly lines on the # canvas separately. # # To develop this program from the beginning you can # # 1) Develop code to draw a single squiggly line using the # anonymous "default" turtle, # # 2) Modify the code to use a named Turtle object, and # # 3) Copy the code to create another named Turtle object. # from turtle import * from random import randint # Set up the drawing canvas and hide the default turtle setup() title('Two scribbly turtles') hideturtle() # Hide the default turtle since we don't use it # Create the two Turtle objects red_turtle = Turtle() blue_turtle = Turtle() # Define the characteristics of the red turtle red_turtle.color('red') red_turtle.turtlesize(2) red_turtle.width(4) red_turtle.pendown() red_turtle.speed('fast') # Define the characteristics of the blue turtle blue_turtle.color('blue') blue_turtle.turtlesize(3) blue_turtle.width(6) blue_turtle.pendown() blue_turtle.speed('fast') # Make the two turtles appear to draw at the same # time by interleaving their actions for steps in range(200): # Move the red turtle red_turtle.left(randint(-90, 90)) red_turtle.forward(15) # Move the blue turtle blue_turtle.left(randint(-45, 45)) blue_turtle.forward(5) # Exit done()
true
0598e5896c2b92261ac342485f300d5b0af7c907
ARWA-ALraddadi/python-tutorial-for-beginners
/09-Workshop/print_elements.py
2,663
4.84375
5
#--------------------------------------------------------- # # Print a table of the elements # # In this exercise you will develop a Python program that # accesses an SQLite database. We assume that you have # already created a version of the Elements database using # the a graphical user interface. You can do so by executing # the elements.sql script provided. # # Your tasks: # # 1) Browse the database's contents in an interactive interface # to ensure that you're familiar with its two tables and # their columns. # # 2) In your interactive interface, develop a SELECT query which # prints all available details of the elements in the database. # The result set should be ordered by atomic number as follows: # # No Name Symbol # 1 Hydrogen H # 2 Helium He # 3 Lithium Li # 4 Beryllium Be # 5 Boron B # 6 Carbon C # 7 Nitrogen N # 8 Oxygen O # 9 Fluorine F # 10 Neon Ne # 11 Sodium Na # 12 Magnesium Mg # 13 Aluminium Al # 14 Silicon Si # 15 Phosphorous P # 16 Sulphur S # 17 Chlorine Cl # 18 Argon Ar # 19 Potassium K # 20 Calcium Ca # [There may be more entries here if you did the # first "elements" exercise] # 121 Kryptonite Kr # 122 Dalekanium Dk # # 3) Using this SELECT query, write a Python program to print # all the element details in the database. Recall that after an # SQLite query has been executed on a database "cursor", method call # "cursor.fetchall()" will return a list of all rows in the # result set, and you can then use a FOR-EACH loop to process each # row in the list. # #--------------------------------------------------------- # Import the SQLite functions from sqlite3 import * # Connect to the elements database and print the atomic # number, name and symbol for each element. # 1. Make a connection to the elements database connection = connect(database = "elements.db") # 2. Get a cursor on the database elements = connection.cursor() # 3. Construct the SQLite query query = "SELECT atomic_number, symbols.element_name, symbol \ FROM atomic_numbers, symbols \ WHERE atomic_numbers.element_name = symbols.element_name \ ORDER BY atomic_number" # 4. Execute the query elements.execute(query) # 5. Get the result set and print it out print('No Name Symbol') rows = elements.fetchall() for no, name, symbol in rows: print(str(no).ljust(3) + ' ' + name.ljust(11) + ' ' + symbol.ljust(2)) # 6. Close the cursor and connection elements.close() connection.close()
true
189cbe4c2f6cb9b263e5c6f7fba1571040478428
ARWA-ALraddadi/python-tutorial-for-beginners
/08-How to Find Things Demos/01-wheres_Superman.py
1,804
4.65625
5
#--------------------------------------------------------------------- # # Where's Superman? # # To illustrate how we can find simple patterns in a text file using # Python's built-in "find" method, this demonstration searches for # some patterns in an HTML file. # # Read the contents of the file as a single string text_file = open('documents/Superman.html') text = text_file.read() text_file.close() # Make sure we've read the text properly print("Number of characters read:", len(text)) print() # Find the first occurrence of the word 'Superman' in the text print("Superman's name first occurs at position", text.find('Superman')) print() # Find the first occurrence of the word 'Batman' in the text print("Batman's name first occurs at position", text.find('Batman')) print() # Find all occurrences of the word 'Superman' in the text print("Superman's name appears in the following positions:") location = text.find('Superman') # Find first occurrence, if any while location != -1: print(location) location = text.find('Superman', location + 1) # Find next occurrence, if any print() # Find and display all names that have been strongly emphasised in the text, i.e., # those appearing between the HTML tags <strong> and </strong>. print("Names which are strongly emphasised in the text are:") start_tag = '<strong>' end_tag = '</strong>' start_location = text.find(start_tag) # Find first occurrence of start tag, if any while start_location != -1: end_location = text.find(end_tag, start_location) # Find matching end tag print(text[start_location + len(start_tag) : end_location]) # Print text between the tags start_location = text.find(start_tag, end_location) # Find next occurrence of start tag, if any # This last example is MUCH simpler with regular expressions!
true
5c6f7af9847b7112297337f1dd5199f9ba6bb97e
ARWA-ALraddadi/python-tutorial-for-beginners
/04-How to Make Decisions Demos/15-un-nesting.py
1,389
4.40625
4
#--------------------------------------------------------------------- # # "Un-nesting" some conditional statements # # There are usually multiple ways to express the # same thing in program code. As an instructive # exercise in using conditional statements, consider # the code below which decides whether or not # an applicant will get a mortgage based on their # income and their job status. Your challenge # is to change the code so that it does exactly the # same thing but only uses a single IF statement. # In other words, you must "un-nest" the two nested # IF statements. To do so you will not only need # to change the IF statements, you will also need # to devise new Boolean expressions involving the # AND connector. # Some test values - uncomment as necessary # An applicant who doesn't earn enough salary = 25000 years_in_job = 3 ### An applicant who doesn't have a steady job ##salary = 45000 ##years_in_job = 1 ### An applicant who qualifies for a loan ##salary = 55000 ##years_in_job = 3 # Two nested IF statements to be "flattened" into one if salary >= 30000: if years_in_job >= 2: print('You qualify for the loan') else: print('You must have worked in your', 'current job for at least two', 'years to qualify for a loan') else: print('You must earn at least $30,000', 'to qualify for a loan')
true
3a2ad3460b8151fc7df5ae3232b315b6c5dc9cab
ARWA-ALraddadi/python-tutorial-for-beginners
/03-How to Create Reusable Code Demos/07-ref_transparency.py
1,735
4.21875
4
#--------------------------------------------------------------------- # # Demonstration - Referential transparency # # The small examples in this file illustrate the meaning of # "referentially transparent" function definitions. A # function that is referentially transparent always does this # same thing when given the same arguments. In general, it is # easier to understand programs that use only referentially- # transparent functions. # # Functions that are NOT referentially transparent usually # return random values or, as in the example below, use a # global variable to "remember" their previous state. # #--------------------------------------------------------------------- # # The following function is referentially transparent because it # always gives the same answer when given the same argument: # # Returns the given number less five def take_5(minuend): subtrahend = 5 # constant to be subtracted return minuend - subtrahend # Some tests: print(take_5(10)) print(take_5(10)) print(take_5(10)) print(take_5(10)) print(take_5(10)) print() #--------------------------------------------------------------------- # # The following function is NOT referentially transparent because it # gives different answers when given the same argument: # subtrahend = 5 # global variable to remember how much to subtract # Returns the given number less five or more def take_at_least_5(minuend): global subtrahend # allow assignment to global variable subtrahend = subtrahend + 1 # increment amount to be subtracted return minuend - subtrahend # Some tests: print(take_at_least_5(10)) print(take_at_least_5(10)) print(take_at_least_5(10)) print(take_at_least_5(10)) print(take_at_least_5(10))
true
d8d0afeca8c35fdfa370f32af41f0ce66e670e58
ARWA-ALraddadi/python-tutorial-for-beginners
/01-Workshop/Workshop-Questions/01_repair_cost.py
854
4.21875
4
# Total repair cost # # THE PROBLEM # # Assume the following values have already been entered into the # Python interpreter, representing the vehicle repair costs in dollars # from several suppliers following a motor accident, and the deposit # paid for the work: panel_beating = 1500 mechanics = 895 spray_painting = 500 tyres = 560 deposit = 200 # Write an expression to calculate the total cost outstanding # after the deposit has been paid, and the repairs completed. # Then print an appropriate message to screen including the # amount owing. # Use the following problem solving strategy: # 1. Calculate the sum of all the costs costssum= panel_beating + mechanics + spray_painting +tyres # 2. Deduct the amount of the deposit already paid remaincost = costssum - deposit # 3. Display the result print("the remain cost is " + str(remaincost))
true
072d4198ea1dea7962646af90a14f36fc72bbf81
ARWA-ALraddadi/python-tutorial-for-beginners
/10-How to Stop Programs Crashing Demos/0-mars_lander_V1.py
2,045
4.65625
5
#--------------------------------------------------------------------# # # Mars lander example - Checking input validity # # This simple program allows us to experiment with defensive # programming, assertions and exception handling. It is based on # a real-life example in which a software failure caused # a Mars lander to crash. # # To run the program the user is meant to simulate a barometer # and enter an increasing series of air pressure readings # between 0 and 100, e.g., 1, 4, 10, 50, 80, 100. # # Retro rockets will fire while the pressure equals or # exceeds 75 and will stop when the pressure reaches 100, # which is assumed to be the air pressure at ground level. # # In this version the program checks to ensure that the # barometer reading received is an integer and requests # another if it isn't. # # Import the regular expression match function from re import match # Two utility functions to tell us whether the retro rockets # are on or off def retros_on(): print("-- Retro rockets are firing --") def retros_off(): print("-- Retro rockets are off --") altitude = 1000000 # initialise with a big number pressure_at_surface = 100 # constant # Calculate altitude based on atmospheric # pressure - higher pressure means lower altitude def altimeter(barometer_reading): # Return the result return pressure_at_surface - barometer_reading # Main program to decide when to fire the retros while altitude != 0: # Read a valid integer from the barometer (the user in this case!) raw_air_pressure = input('Enter barometer reading: ') while match('^-?[0-9]+$', raw_air_pressure) == None: raw_air_pressure = input('Re-enter barometer reading: ') air_pressure = int(raw_air_pressure) # Calculate the lander's altitude altitude = altimeter(air_pressure) # Decide whether or not the retros should be firing if altitude == 0 or altitude > 25: retros_off() else: retros_on() # We made it! print('Houston, the Eagle has landed!')
true