blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b5fa47092ffc8d0a9f927d9769edc5d41daa6aa4
MayowaLabinjo/Guessing-game
/Guessing game.py
421
4.1875
4
import random highest=10 answer=random.randrange(highest) guess=input("guess a number from 0 to %d: " % highest) while(int(guess)!=answer): if(int(guess)<answer): print ("answer is higher") else: print ("answer is lower") guess=input("guess a number from 0 to %d: " %highest) input('you are a winnerface')
true
a11123124c72d59f1eddcef83eaed890c8d5b9c0
jbking/pythonista-misc
/python_math/fibonacci_graph.py
542
4.15625
4
import matplotlib.pyplot as plt def draw_graph(final): if final <= 1: raise ValueError("specify number bigger than 1") fibonacci = [1, 1] for _ in range(final - 2): fibonacci.append(fibonacci[-1] + fibonacci[-2]) ys = [fibonacci[x + 1] / fibonacci[x] for x in range(len(fibonacci) - 1)] plt.plot(range(final - 1), ys) plt.xlabel("No.") plt.ylabel("Ratio") plt.title("Ratio between consecutive Fibonacci numbers") if __name__ == '__main__': draw_graph(100) plt.show()
false
e7724794b94a65e9a7f6aae136d821de1f33698a
vagmithra123/python
/Operators.py
1,353
4.15625
4
#range, only stop for num in range(10): print(num) #range , start, stop for num in range(2, 10): print(num) #range , start, stop, step for num in range(2, 10, 2): print(num) print(list(range(0, 11, 2))) #Generator is a special type of function, it will generate information instead of saving it all to memory. index_count = 0 for letter in 'abcde': print('At index {} the letter is {}'.format(index_count, letter)) index_count += 1 #enumerate as list index = 0 word = 'abcde' for letter in word: print(word[index]) index += 1 for item in enumerate(word): print(item) for index, letter in enumerate(word): print(index) print(letter) print('\n') #zipping lists using zip function mylist1 = [1,2,3] mylist2 = ['a','b','c'] for item in zip(mylist1, mylist2): print(item) print(list(zip(mylist1, mylist2))) #in keyword print('x' in [1, 2,3]) print('a' in 'a world') d = {'mykey' : 123} print(123 in d.values()) #min function mylist = [10,20,30, 40, 50] print(min(mylist)) print(max(mylist)) #random shuffle function mylist = [1,2,3,4,5,6,7,8,9] from random import shuffle random_list = shuffle(mylist) print(mylist) from random import randint print(randint(0,100)) mynum = randint(1,10) print(mynum) a = int(input('Enter a number: ')) b = int(input('Enter a number: ')) print(f'Sum of a and b is, {a+b}')
true
852c417315a6eb604da0c9f1ca1d3a016c062a81
vagmithra123/python
/FunctionsPracticeExercises.py
2,821
4.125
4
''' LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd lesser_of_two_evens(2,4) --> 2 lesser_of_two_evens(2,5) --> 5''' def lesser_of_two_evens(a, b): if a%2 == 0 and b%2 == 0: return min(a,b) elif a%2 == 0 || b%2 == 0: return max(a,b) ''' ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter animal_crackers('Levelheaded Llama') --> True animal_crackers('Crazy Kangaroo') --> False''' def animal_crackers(text): x = text.split() return x[0][0] == x[1][0]: ''' MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False makes_twenty(20,10) --> True makes_twenty(12,8) --> True makes_twenty(2,3) --> False''' def makes_twenty(a,b): return (a+b) == 20 or a == 20 or b == 20 ''' OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name old_macdonald('macdonald') --> MacDonald ''' def old_macdonald(name): if len(name) > 3: return name[:3].capitalize() + name[3:].capitalize() else: return 'Name is too short!' ''' MASTER YODA: Given a sentence, return a sentence with the words reversed master_yoda('I am home') --> 'home am I' master_yoda('We are ready') --> 'ready are We' ''' def master_yoda(text): return " ".join(reversed(text.split())) ''' ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200 almost_there(90) --> True almost_there(104) --> True almost_there(150) --> False almost_there(209) --> True ''' def almost_there(n): return ((abs(100 - n) <= 10) or (abs(200 -n) <= 10)) ''' FIND 33: Given a list of ints, return True if the array contains a 3 next to a 3 somewhere. has_33([1, 3, 3]) → True has_33([1, 3, 1, 3]) → False has_33([3, 1, 3]) → False ''' def has_33(nums): for i in range(0, len(nums) -1): if nums[i] == 3 and nums[i+1] == 3: return True return False ''' PAPER DOLL: Given a string, return a string where for every character in the original there are three characters paper_doll('Hello') --> 'HHHeeellllllooo' paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii' ''' def paper_doll(text): return (text[0: len(text)] * 3) ''' BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 and there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST' blackjack(5,6,7) --> 18 blackjack(9,9,9) --> 'BUST' blackjack(9,9,11) --> 19 ''' def blackjack(a,b,c): if sum(a,b,c) <= 21: return sum((a,,b,c)) elif sum ((a,b,c)) >= 21 and 11 in (a,b,c): return sum((a,,b,c)) - 10 else: return 'BUST'
false
1db8c24dbf53530312c12a4c105312e55853ab60
dhsabigailhsu/y1math
/t01primeshcflcm_evennumbers.py
255
4.25
4
# What are the even numbers from 1 to num? #num is 123 num = 123 #execute a loop from 1 to 123 for i in range(1, num+1): #check if the current number is divisible by 2 if i % 2 == 0: #print out the number, in the same line print(i, end=' ')
true
bc0dcb7241bbb3d6860b2cf1e71c2adcfa4c4f1a
cassiakaren/ULTIMA-LISTA
/ex2.py
716
4.375
4
#2) Refaça o exercício da questão anterior, imprimindo os retângulos sem preenchimento, #de forma que os caracteres que não estiverem na borda do retângulo sejam espaços. largura = int(input("Coloque a largura: ")) print("") altura = int(input("Coloque a altura: ")) print("") caractere = "#" def retângulo(largura, altura, caractere): linhacompleta = caractere * largura if largura > 2: linhavazia = caractere + (" " * (largura - 2)) + caractere else: linhavazia = linhacompleta if altura >= 1: print(linhacompleta) for i in range(altura - 2): print(linhavazia) if altura >= 2: print(linhacompleta) retângulo(largura, altura, caractere)
false
13c90534c5dd14fe60cfeef25d6f14dd2c3648ab
clebertonf/Python-ciencia-da-computacao
/001-bloco-33-01/003-funcoes.py
2,001
4.21875
4
# definição de funçoes # parametros posicionais def soma(a, b): return a + b print(soma(10, 50)) # parametros nomeados print(soma(b=40, a=120)) # Os parâmetros também podem ser variádicos. Ou seja, podem variar em sua quantidade. # Parâmetros posicionais variádicos são acessados como tuplas no interior de uma função # e parâmetros nomeados variádicos como dicionário. def concat(*strings): # Equivalente a um ", ".join(strings), que concatena os elementos de um iterável em uma # string utilizando um separador # Nesse caso a string resultante estaria separada por vírgula final_string = "" for string in strings: final_string += string if not string == strings[-1]: final_string += ", " return final_string # pode ser chamado com 2 parâmetros print(concat("Carlos", "João")) # saída: "Carlos, João" # pode ser chamado com um número n de parâmetros concat("Carlos", "João", "Maria") # saída: "Carlos, João, Maria" # dict é uma função que já vem embutida no python dict( nome="Felipe", sobrenome="Silva", idade=25 ) # cria um dicionário utilizando as chaves passadas dict( nome="Ana", sobrenome="Souza", idade=21, turma=1 ) # o número de parâmetros passados para a função pode variar print("Botaro", "Cássio", sep=", ") def leet(word): word = list(word.upper()) print(word) char_map = dict(zip("AEIO", "4310")) print(char_map) results = [] for letter in word: if letter in char_map: results.append(char_map[letter]) else: results.append(letter) return results print(leet("cleber")) def leet_replace(word): word = list(word.upper()) char_map = dict(zip("AEIO", "4310")) results = [] for letter in word: if letter in char_map: results.append(letter.replace(letter, char_map[letter])) else: results.append(letter) return results print(leet_replace("cleber"))
false
6967353bd2cd897f2b93df03d855c2255380a48d
LucyMbugua/python_bootcamp
/intro_to_python/strings.py
612
4.3125
4
firstName = 'Lucy' lastName = "Wanjiku" print(type(firstName)) print(type(lastName)) #string indexing = retrieve certain character from a string #positive indexing print(firstName[0]) print(firstName[3]) #negative indexing print(firstName[-4]) #string slicing institution = "Techcamp" #positive slicing print(institution[0:4]) print(institution[4:8]) #Negative slicing print(institution[-8:-4]) print(institution[-4:]) #slicing with step print(institution[::3]) #string concatention a = "tech" b = "CAMP" c = "Kenya" fullName = a+b+c print(fullName) print(a.upper()) print(b.lower()) print(a.title())
false
e188153fc3bae693a94f3d1cdb6cb5bb6683af4b
LucyMbugua/python_bootcamp
/practice_tasks/pythonbasics.py
2,170
4.25
4
#TASK 1: # Write a program which accepts a string as input to print "Yes" if the string is "yes", "YES" or "Yes", otherwise print "No". # Hint: Use input () to get the persons input string = input("Enter a string:") if string == "yes" or string == "YES" or string == "Yes": print("Yes") else: print("No") """TASK 2: Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function""" # a = [5, 10, 15, 20, 25] # mylist = [a[0],a[-1]] # #mylist.append(a[0]) # #mylist.append(a[len(a) -1]) # print (mylist) def mylist4(a): return [a[0],a[-1]] print(mylist4([5, 10, 15, 20, 25])) """TASK 3: Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: 1. If the number is a multiple of 4, print out a different message.""" # number = int(input("Enter a number:")) # if number%4==0 and number%2==0: # print(number, " is a multiple of 4") # elif number%2==1: # print(number, " is odd") # elif number%2==0: # print(number, " is even") #num = int(input("Enter a number: ")) """check = 4 if (num%2)==0: print("{0} is even".format(num)) else: print("{0} is odd".format(num)) if num % check == 0: print(num, "divides evenly by", check) else: print(num, "does not divide evenly by", check)""" """# Ask the user for any number anyNumber = input("Enter a number:") # evalute the number and print out appropriate messages. if int(anyNumber)%2 == 0: print("{} is an even number".format(anyNumber)) if int(anyNumber)%4 == 0: print("{} is a multiple of 4".format(anyNumber)) else: print("{} is an odd number".format(anyNumber))""" def odd_even(anyNumber): if int(anyNumber)%2 == 0: print("{} is an even number".format(anyNumber)) if int(anyNumber)%4 == 0: print("{} is a multiple of 4".format(anyNumber)) else: print("{} is an odd number".format(anyNumber)) odd_even(16)
true
f4ccec5460ab8e338326978451907f2fb71edf0a
ofbozlak/alistirma1
/dongu_yapilari/armstrong_sayi.py
749
4.28125
4
""" Kullanıcıdan aldığınız bir sayının "Armstrong" sayısı olup olmadığını bulmaya çalışın. Örnek olarak, Bir sayı eğer 4 basamaklı ise ve oluşturan rakamlardan herbirinin 4. kuvvetinin toplamı ( 3 basamaklı sayılar için 3.kuvveti ) o sayıya eşitse bu sayıya "Armstrong" sayısı denir. Örnek olarak : 1634 = 1^4 + 6^4 + 3^4 + 4^4 """ while True: print("Çıkmak İçin '1' Bas") sayi = input("Armstrong Saysını Bul(4 basamaklı sayı girin):") if sayi == '1': break deger = 0 for i in sayi: i = int(i) deger += i**4 deger = str(deger) if deger == sayi: print("Tebrikler Sayıyı Buldunuz....") else: print("Tekrar Deneyiniz....")
false
efb0a0ff7d4a195ced46dacb9b8cc5bef1e9391a
varghesechacko/PracticePython
/Exercise1.py
850
4.21875
4
# Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. # Extras: # Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python) # Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button) from datetime import date name = input("What is your name: ") age = input("Enter your age: ") yearsTo100 = 100 - int(age) currentYear = date.today().year def printCopies(): print(name + ", you will hundred in " + str(currentYear + yearsTo100)) numberOfCopies = input("Enter a number: ") for i in range(0, int(numberOfCopies)): printCopies()
true
a4e582bfb6d450c57afdf516e69bb0ceae45880d
jmartinknoll/PY4E
/exercise3.1.py
459
4.125
4
# calculate gross pay (user input) # find the breakdown of how much of the gross pay is regular pay and overtime pay # 1.5x pay for overtime x = input('enter hours: ') y = input('enter rate of pay: ') hours = float(x) payrate = float(y) if hours > 40 : print('overtime') regpay = hours * payrate otpay = (hours - 40) * (payrate * 0.5) print(regpay,otpay) pay = regpay + otpay else: print('regular') pay = hours * payrate print(pay)
true
edf032ebdb1ee2ba3a9403c5daabd748faf05d92
jmartinknoll/PY4E
/exercise7.2.py
873
4.375
4
# Write a program to prompt for a file name, and then read # through the file and look for lines of the form: # X-DSPAM-Confidence: 0.8475 # When you encounter a line that starts with “X-DSPAM-Confidence:” # pull apart the line to extract the floating-point number on the line. # Count these lines and then compute the total of the spam confidence # values from these lines. When you reach the end of the file, print out # the average spam confidence. fname = input('Enter a file name: ') try: fhand = open(fname) except: print('File does not exist') quit() count = 0 total = 0 for line in fhand: if line.startswith('X-DSPAM-Confidence:'): x = line.find(':') y = line[x + 1: ] z = float(y) count = count + 1 total = total + z print('Count:',count,'Total:',total,'Average spam confidence:',total/count)
true
2d56cebf279f5333ab4139fc5299ad96c2fd43cf
jmartinknoll/PY4E
/exercise10.2.py
802
4.15625
4
# This program counts the distribution of the hour of the day # for each of the messages. You can pull the hour from the “From” line # by finding the time string and then splitting that string into parts using # the colon character. Once you have accumulated the counts for each # hour, print out the counts, one per line, sorted by hour as shown below. fname = input('Enter a file name: ') try: fhand = open(fname) except: print('File does not exist') quit() di = dict() for line in fhand: words = line.split() if len(words) < 3 or words[0] != 'From': continue time = words[5] hour = time.split(':')[0] di[hour] = di.get(hour, 0) + 1 #print(di) lst = list() for k,v in list(di.items()): lst.append((k,v)) lst.sort() for k,v in lst: print(k,v)
true
bb4d1b7eb0f74274f3da3243dbab87a421041def
jmartinknoll/PY4E
/exercise9.4.py
966
4.34375
4
# Add code to the program in exercise 9.3 to figure out who has the # most messages in the file. After all the data has been read and the dictionary has been created, # look through the dictionary using a maximum loop (see Chapter 5) to find who has # the most messages and print how many messages the person has. fname = input('Enter a file name: ') try: fhand = open(fname) except: print('File does not exist') quit() value = dict() for line in fhand: words = line.split() if len(words) < 3 or words[0] != 'From': continue email = words[1] value[email] = value.get(email, 0) + 1 max_value = None max_email = None if max_value is None: max_value = value[email] max_email = email elif value[email] > max_value: max_value = value[email] max_email = email #for k,v in address.items(): # if address[email] > largest: # largest = address[email] # maxword = email print(max_email, value[email])
true
bc2ff903e559b4010ae4b52aea7afe6867a1cb3a
KiranJungGurung/tip-calculator
/main.py
1,187
4.375
4
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 # Print welcome to the tip calculator. print("Welcome to the tip calculator.") #Assign bill,tip and people as a variable name. bill = float(input("What was the total bill? $")) tip = int(input("How much tip would you like to give?10, 12, or 15?")) people = int(input("How many people to split the bill? ")) # Calculate final_amount: # Calculate tip_as_percent by dividing tip by 100. tip_as_percent = tip /100 # Multiply bill with tip_as_percent to get total_tip_amount. total_tip_amount = bill * tip_as_percent #Add bill and total_tip_amount to get total_bill. total_bill = bill + total_tip_amount #Divide total_bill by people to get bill_per_person. bill_per_person = total_bill / people # Round the final_amount to 2 decimal point. final_amount = round(bill_per_person, 2) #If the user put whole number as bill($150), to avoid the format error, use {:.2f}.format(). final_amount = "{:.2f}".format(bill_per_person) #print each person should pay using f-string. print(f"Each person should pay: $ {final_amount}")
true
211dd14fb065f37996f918e3543851ec7824d00f
Humayungithub/TextEditor
/TextEditor.py
1,317
4.15625
4
#import tkinter from tkinter import * #import filedialog from tkinter.filedialog import * filename = None def newFile(): global filename filename = "untitled" text.delete(0.0, END) def saveFile(): global filename t = text.get(0.0, END) f = open(filename, 'w') f.write(t) f.close() def saveAs(): f = asksaveasfile(mode='w', defaultextension='.txt') t = text.get(0.0, END) try: f.write(t.rstrip()) except: showerror(title="Oops!", message="unable to save file") def openFile(): f = askopenfile(mode='r') t = f.read() text.delete(0.0, END) text.insert(0.0, t) window = Tk() # to rename the title of the window window.title("Text Editor") window.minsize(width=400, height=400) window.maxsize(width=400, height=400) text = Text(window) # pack is used to show the object in the window text.pack() menubar = Menu(window) filemenu = Menu(menubar) filemenu.add_command(label="New", command=newFile) filemenu.add_command(label="Open", command=openFile) filemenu.add_command(label="Save", command=saveFile) filemenu.add_command(label="Save as...", command=saveAs) filemenu.add_separator() filemenu.add_command(label="Exit", command=window.quit) menubar.add_cascade(label="File", menu=filemenu) window.config(menu=menubar) window.mainloop()
true
56e17ec36959de88aa5eecd836a0e7fb907b2633
melvinm4697/cti110
/P4T2_BugCollector_MorinekiMelvin.py
458
4.28125
4
# This program will calculate total bugs collected over 5 days # March 31, 2020 # CTI-110 P4T2 - Bug Collector # Morineki Melvin # # Set total to 0 # Enter bugs collected each day for five days # Add the bugs collected for the five days # Display the total amount of bugs collected total = 0 for day in range(1, 6): print('Day', day, 'bugs collected: ') bugs = int(input()) total = total + bugs print('Total bugs collected: ', total)
true
66bee0c1e0f28c4d18c0afd73bd6da748657b64d
gabrielb09/Python-For-Lab
/Chp. 2 Problem 1/Problem1.py
1,007
4.25
4
#INSTRUCTIONS: run the program, it will print the information to the command line. #creates a function for calculating the Height and Velocity of the projectile def HandV (h,v,t): #calculates Height based on initial height, velocity, and time H = h + (v*t) - 4.9*(t**2) #calculates Velocity based on initial height, velocity, and time V = v -9.8*t #returns Height and Velocity return (H,V) #prints the height and speed at T=0s print("at time T=0 seconds the ball is " + str(HandV(1.2, 5.4, 0)[0]) + " meters up, and is traveling at " + str(HandV(1.2,5.4,0)[1]) + " meters per second") #prints the height and speed at T=0.5s print("at time T=0.5 seconds the ball is " + str(HandV(1.2, 5.4, 0.5)[0]) + " meters up, and is traveling at " + str(HandV(1.2,5.4,0.5)[1]) + " meters per second") #prints the height and speed at T=2s print("at time T=2 seconds the ball is " + str(HandV(1.2, 5.4, 2)[0]) + " meters up, and is traveling at " + str(HandV(1.2,5.4,2)[1]) + " meters per second")
true
93611faabdd036b15be790cf9c2f4a8690fc5ef0
ArishaGo99/Python
/LAB_3/LAB_3.py
642
4.25
4
#Развлетвляющиеся вычислительные процессы. #Задание2 from math import * flag=0 print('Введите значение R ') R=float(input('R=')) print('Введите координаты точки') x=float(input('X=')) y=float(input('Y=')) if (x>R) or (y>R) or (x < -R) or (y < -R): flag=0 elif ((y<=sqrt(R**2-x**2) and (x>=0))) or ((y>=-R) \ and (x>=-R) and (y<=x)): flag=1 else: flag=0 print("Точка X={0: 6.2F} Y={1: 6.2f}"\ .format(x,y), end=" ") if flag: print("попадает в область") else: print("не попадает в область")
false
fd1ad85c9b81fc0949ea0ceb836cbd432fbb9496
rajivmanivannan/learning-python
/src/basics/functions.py
2,579
4.6875
5
#!/usr/bin/env python3 # encoding= utf-8 """ Functions A function is a block of code that takes in some data and, either performs some kind of transformation and returns the transformed data, or performs some task on the data, or both. Functions are useful because they provide a high degree of modularity. Similar code can be easily grouped into functions and you can provide a name to the function that describes what the function is for. """ """ def name_of_the_function(arguments): ''' doctring of the function note that the function block is indented by 4 spaces ''' body of the function return the return value or expression """ def add_two_numbers(num1, num2): ''' Summary line... Extended description of function. Parameters: arg1 (int): Description of arg1 arg2 ... Returns: int: Description of return value ''' result = num1 + num2 return result result = add_two_numbers(1, 2) print(result) """ Keyword def: This is the keyword used to say that a function will be defined now, and the next word that is there, is the function name. Function name: This is the name that is used to identify the function. The function name comes after the def keyword. Function names have to be a single word. PEP8, which is a style guide for Python, recommends that in case multiple words are used, they should be in lowercase and they should be separated with an underscore. In the example above, add_two_numbers is the parameter name. Parameter list: Parameter list are place holders that define the parameters that go into the function.The parameters help to generalise the transformation/computation/task that is needed to be done. In Python, parameters are enclosed in parentheses. In the example above, the parameters are num1and num2. You can pass as many parameters as needed to a function. Function docstrings: These are optional constructs that provide a convenient way for associated documentation to the corresponding function. Docstrings are enclosed by triple quotes '''you will write the docstring here''' Function returns: Python functions returns a value. You can define what to return by the return keyword. In the example above, the function returns result. In case you do not define a return value, the function will return None. """ # Call a function that performs a task and has no return value def printing_side_effects(): '''a function with side effects''' print('this is a function with side effects and performs some task') printing_side_effects()
true
df30f6702a20868ccceac3a84b29a185c993401d
DanielDrex/Introduccion-python
/Scripts-DS/Numpy.py
715
4.1875
4
#Importamos las librerias de array y numpy import array as a import numpy as np L = list(range(10)) A = a.array('i',L) print(A) #Creacion de arreglos desde listas de python print(np.array([1,2,3,4,5],dtype='float32')) #Creacion de arreglos multidimensionales print(np.array([range(i,i+3) for i in [2,4,6]])) print(np.ones((3,5),dtype='float'),'\n') print(np.zeros((4,3),dtype='float32'),'\n') print(np.full((2,3),3.14),'\n') #Creacion de arrays con secuencia lineal #Inicia en 0 hasta 20 con paso de 2 print(np.arange(0,20,2),'\n') #Inicia en 0, termina en 1 dividido en 5 subdivisiones print(np.linspace(0,1,10),'\n') #Creacion de array 3 x 3 con valores aleatorios de 0 a 1 print(np.random.random((3,3)))
false
c7246a27cc3c9afa67b060b09de5d4267d5d8338
StevenR152/Connect4-Python
/code/main.py
2,149
4.1875
4
def print_board(board): print("Printing the board...") # write code that prints the board 2d array def get_user_input(valid_inputs, player): users_input = input("Enter the move for player " + str(player) + ":") print("User entered: " + users_input) # TODO Use valid_inputs to check the users input and ask them for a new input if its wrong. return int(users_input) def is_bottom_of_board(board, row_index): return row_index == len(board) - 1 def is_board_square_empty_at_position(board, row_index, col_index): return board[row_index][col_index] != 0 def place_piece(board, col, piece): print("Place piece: " + str(col)) row_index = 0 piece_placed = False while row_index < len(board) and not piece_placed: # This function needs to have the board coordinates # calculated correctly replace the zero's with actual positions. if is_board_square_empty_at_position(board, row_index, col): board[0][0] = piece piece_placed = True elif is_bottom_of_board(board, row_index): board[0][0] = piece piece_placed = True row_index += 1 def check_win(board): # TODO Work out if the game is over # The objective of the game is to be the first to form a horizontal, # vertical, or diagonal line of four of one's own pieces. # TODO Print the player who won and return True to end the game. return False def next_player(player): if player == 1: return 2 if player == 2: return 1 def play(board): is_game_over = False player = 1 # TODO currently the game supports any input, make the users input restricted to the following. valid_inputs = [1, 2, 3, 4, 5, 6, 7] while not is_game_over: print_board(board) col = get_user_input(valid_inputs, player) place_piece(board, col, player) is_game_over = check_win(board) player = next_player(player) game_board = [ [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0] ] play(game_board)
true
dcb88a1be04cd3f87f50c65209203ed44c8b8d1c
DanieleMagalhaes/Exercicios-Python
/Mundo1/convMedidas.py
452
4.125
4
metro = float(input('Digite uma distancia em metros: ')) km = metro / 1000 hm = metro / 100 dam = metro / 10 dm = metro * 10 cm = metro * 100 mm = metro * 1000 print('A distancia de {} metros corresponde a: '.format(metro)) print('{} Quilômetros'.format(km)) print('{} Hectômetros'.format(hm)) print('{} Decâmetros'.format(dam)) print('{:.0f} Decímetros'.format(dm)) print('{:.0f} Centímetros'.format(cm)) print('{:.0f} Milímetros'.format(mm))
false
aee1648e7f57b8951bc4475a10240d9b62661045
DanieleMagalhaes/Exercicios-Python
/Mundo1/hello.py
541
4.125
4
nome = input('Qual é o seu nome? ') print('\nOlá {}!' .format(nome) , ' Seja bem-vinda! \n') print ('Quando você nasceu?') dia = input ('DIA = ') mes = input ('MES = ') ano = input ('ANO = ') print ('Você nasceu no dia' , dia , 'de' , mes , 'de' , ano ,'. Correto?') print('\nVamos somar dois números?') num1 = int(input('PRIMEIRO NUMERO: ')) num2 = int(input('SEGUNDO NUMERO: ')) soma = num1 + (num2) #print('A soma dos numeros' , num1 , 'e' , num2 , 'é:' , soma) print ('A soma dos numeros {} e {} é {}' .format(num1, num2, soma))
false
4313e649e845d28f81c91ee484d3d844c7554faa
Prince7862/Number-Guessing-Game
/numberguessingGame.py
686
4.15625
4
import random; chances = 0 randomNum = random.randint(1,9) #print(randomNum) #a = (randomNum > number) #print(type(number)) #print(a) while(chances < 5): chances = chances + 1 number = int(input("Guess a Number from 1 to 9: ")) if(number < randomNum): print("The number you have entered is less than the Random Number please retry") elif(number > randomNum): print("The number you have entered is more than the Random Number please retry") if(chances == 5): print("YOU LOSE!!! THE RANDOM NUMBER WAS: ", randomNum) break elif(number == randomNum): print("CONGRATULATIONS YOU WIN!!!! ") break
true
9a34ae5932e673a307c07cc91f4a305c7d13c680
Tanishk-Sharma/Data-Structures-and-Algorithms
/Data Structures/Queue.py
1,238
4.375
4
class Queue: def __init__(self): #Constructor creates a list self.queue = list() def enqueue(self,data): #Adding elements to queue if data not in self.queue: #Checking to avoid duplicate entry (not mandatory) self.queue.insert(0,data) return True return False def dequeue(self): #Removing the last element from the queue if len(self.queue)>0: return self.queue.pop() return ("Queue Empty!") def size(self): #Getting the size of the queue return len(self.queue) def printQueue(self): #printing the elements of the queue return self.queue my_queue = Queue() print(my_queue.enqueue(5)) #prints True print(my_queue.enqueue(6)) #prints True print(my_queue.enqueue(9)) #prints True print(my_queue.enqueue(5)) #prints False print(my_queue.enqueue(3)) #prints True print(my_queue.size()) #prints 4 print(my_queue.dequeue()) #prints 5 print(my_queue.dequeue()) #prints 6 print(my_queue.dequeue()) #prints 9 print(my_queue.dequeue()) #prints 3 print(my_queue.size()) #prints 0 print(my_queue.dequeue()) #prints Queue Empty!
true
4c07495d4ac8161878fd8f34282e57023c59b4c1
michaelGRU/temp
/lists20.py
977
4.375
4
# data type: list (mutable) # create a list names = ["Chloe", "Victoria", "Jackson"] # find the index of an item names.index("Jackson") # loop through the list for i, name in enumerate(names): pass # print(f"{name} is in index {i}") # adding items: append, insert names.append("Michael") names.insert(0, "Jesus") # adds at a specific index # removing items: remove, pop, delete # Remove() deletes the matching element from # the list whereas the del and pop removes the element present at specified index names.remove("Michael") names.pop() # pop(index) #remove the item but extract the item # del x[index] # delete without returning the item # Extending names2 = ["cats", "dogs", "birds"] names.extend(names2) # Sorting - sort, reverse, will raise error # if mixed types exist names.sort() names.reverse() # copy names2 = names.copy() names3 = names[:][::-1] # reverse print(names3) # clear names3.clear() print(names3)
true
754d28fec133038d9e44f139c1ad1972d1d9e620
michaelGRU/temp
/dic20.py
413
4.1875
4
# dictionary # indexed by keys, can be any immutable type d = {"pet": "dog", "age": 5, "name": "kgb"} print(type(d)) d = dict(pet="dog", age=5, name="spot") print(d.items()) print(d.keys()) print(d.values()) print(d["pet"]) # add an item d["add"] = "sit" # remove an item del d["add"] # the value associate with the key is also gone for key in d.keys(): print(f"{key} = {d[key]}")
true
fa9127a292ada7a481b87cd997128e923aaf9a26
GeekGirlDee/FirstProjectWithTakenMind
/FirstProject/venv/Pandas/Pandas Statistics.py
2,036
4.4375
4
from pandas import Series, DataFrame import numpy as np from numpy.random import randn import matplotlib.pyplot as plt # 2d array # np.nan stands for non value array1 = np.array([[10, np.nan, 20], [30, 40, np.nan]]) print array1 # creating a Data Frame # this dataframe will print out the index which is the row number labled 1 2 # columns are numbered A B C df1 = DataFrame(array1, index=[1, 2], columns=list('ABC')) print df1 #Sum operarions well known as sum() in python # this will sum up each column print df1.sum() #this is to calculate each row/indexes print df1.sum(axis=1) print "-----------------------------------------------" #This will show the minimum values of the column print "Minimun" print df1.min() #This will show the maximum values of the column print "Maximum" print df1.max() #This will show the minimum and maximum values of the index # It does not show the value but shows the index/ row of the values with the min and max values print "Max of index" print df1.idxmax() print "Min of index" print df1.idxmin() # Cumilitive Sums leave the first index as it is # and adds the second index with the first indexx to get the outcome print "Cumulitive Sum" print df1.cumsum() # Describe function helps with oral sets such as: # count, mean, standard deviation, minimum, mpercentages (25%, 50%, 75%) and max print "Describe Function" print df1.describe() #this dataframe looks at random numbers with a 3*3 grid # it has an index of 123 and column ABC df2 = DataFrame(randn(9).reshape(3,3),index=[1,2,3],columns=list('ABC')) print "New DataFrame" print df2 # a graph is created to show the values of the dataframe #plt.plot(df2) #plt.legend(df2.columns, loc="lower right") #plt.savefig('dataframe.png') #plt.show() ser1 =Series(list('abccaabd')) print "abc" print ser1.unique() # show the frequency in which the number are represented in a series # it shows the each value on the list and the number which represents # the number of times it appears print "Frequency" print ser1.value_counts()
true
ca6eadf33cfef18f5767d072dbadf72980f14742
oxygenJing/Big-Data-exercise
/feature-engineering-with-pyspark/No16-Calculate-Missing-Percents.py
1,170
4.5
4
#Calculate Missing Percents ''' Automation is the future of data science. Learning to automate some of your data preparation pays dividends. In this exercise, we will automate dropping columns if they are missing data beyond a specific threshold. Instructions 100 XP Define a function column_dropper() that takes the parameters df a dataframe and threshold a float between 0 and 1. Calculate the percentage of values that are missing using where(), isNull() and count() Check to see if the percentage of missing is higher than the threshold, if so, drop the column using drop() Run column_dropper() on df with the threshold set to .6 ''' # Code def column_dropper(df, threshold): # Takes a dataframe and threshold for missing values. Returns a dataframe. total_records = df.count() for col in df.columns: # Calculate the percentage of missing values missing = df.where(df[col].isNull()).count() missing_percent = missing / total_records # Drop column if percent of missing is more than threshold if missing_percent > threshold: df = df.drop(col) return df # Drop columns that are more than 60% missing df = column_dropper(df, .6)
true
6be955db0f313c5af57520a9e3b6e9bad7f35854
oxygenJing/Big-Data-exercise
/feature-engineering-with-pyspark/No12-caling-your-scalers.py
2,292
4.40625
4
#Scaling your scalers ''' In the previous exercise, we minmax scaled a single variable. Suppose you have a LOT of variables to scale, you don't want hundreds of lines to code for each. Let's expand on the previous exercise and make it a function. Instructions 100 XP Define a function called min_max_scaler that takes parameters df a dataframe and cols_to_scale the list of columns to scale. Use a for loop to iterate through each column in the list and minmax scale them. Return the dataframe df with the new columns added. Apply the function min_max_scaler() on df and the list of columns cols_to_scale.\ ''' # Code def min_max_scaler(df, cols_to_scale): # Takes a dataframe and list of columns to minmax scale. Returns a dataframe. for col in cols_to_scale: # Define min and max values and collect them max_days = df.agg({col: 'max'}).collect()[0][0] min_days = df.agg({col: 'min'}).collect()[0][0] new_column_name = 'scaled_' + col # Create a new column based off the scaled data df = df.withColumn(new_column_name, (df[col] - min_days) / (max_days - min_days)) return df df = min_max_scaler(df, cols_to_scale) # Show that our data is now between 0 and 1 df[['DAYSONMARKET', 'scaled_DAYSONMARKET']].show() '''result <script.py> output: +------------+--------------------+ |DAYSONMARKET| scaled_DAYSONMARKET| +------------+--------------------+ | 10|0.044444444444444446| | 4|0.017777777777777778| | 28| 0.12444444444444444| | 19| 0.08444444444444445| | 21| 0.09333333333333334| | 17| 0.07555555555555556| | 32| 0.14222222222222222| | 5|0.022222222222222223| | 23| 0.10222222222222223| | 73| 0.3244444444444444| | 80| 0.35555555555555557| | 79| 0.3511111111111111| | 12| 0.05333333333333334| | 1|0.004444444444444...| | 18| 0.08| | 2|0.008888888888888889| | 12| 0.05333333333333334| | 45| 0.2| | 31| 0.13777777777777778| | 16| 0.07111111111111111| +------------+--------------------+ only showing top 20 rows '''
true
726157b25bec6fd17c28310b5e25a6e22c7e79ce
oxygenJing/Big-Data-exercise
/big-data--fundamentals-pyspark/No32-Loading-spam-and-non-spam-data.py
2,044
4.28125
4
#Loading spam and non-spam data ''' Logistic Regression is a popular method to predict a categorical response. Probably one of the most common applications of the logistic regression is the message or email spam classification. In this 3-part exercise, you'll create an email spam classifier with logistic regression using Spark MLlib. Here are the brief steps for creating a spam classifier. Create an RDD of strings representing email. Run MLlib’s feature extraction algorithms to convert text into an RDD of vectors. Call a classification algorithm on the RDD of vectors to return a model object to classify new points. Evaluate the model on a test dataset using one of MLlib’s evaluation functions. In the first part of the exercise, you'll load the 'spam' and 'ham' (non-spam) files into RDDs, split the emails into individual words and look at the first element in each of the RDD. Remember, you have a SparkContext sc available in your workspace. Also file_path_spam variable (which is the path to the 'spam' file) and file_path_ham (which is the path to the 'non-spam' file) is already available in your workspace. Instructions 100 XP Create two RDDS, one for 'spam' and one for 'non-spam (ham)'. Split each email in 'spam' and 'non-spam' RDDs into words. Print the first element in the split RDD of both 'spam' and 'non-spam'. ''' # code # Load the datasets into RDDs spam_rdd = sc.textFile(file_path_spam) non_spam_rdd = sc.textFile(file_path_non_spam) # Split the email messages into words spam_words = spam_rdd.map(lambda email: email.split(' ')) non_spam_words = non_spam_rdd.map(lambda email: email.split(' ')) # Print the first element in the split RDD print("The first element in spam_words is", spam_words.first()) print("The first element in non_spam_words is", non_spam_words.first()) ''' <script.py> output: The first element in spam_words is ['You', 'have', '1', 'new', 'message.', 'Please', 'call', '08712400200.'] The first element in non_spam_words is ['Rofl.', 'Its', 'true', 'to', 'its', 'name'] '''
true
c8a9a041e3bf8a1b22ff94f3532db84929554205
oxygenJing/Big-Data-exercise
/big-data--fundamentals-pyspark/No37-Visualizing-clusters.py
1,491
4.125
4
#Visualizing clusters ''' After KMeans model training with an optimum K value (K = 15), in this final part of the exercise, you will visualize the clusters and their cluster centers (centroids) and see if they overlap with each other. For this, you'll first convert rdd_split_int RDD into spark DataFrame and then into Pandas DataFrame for plotting. Similarly, you'll convert cluster_centers into Pandas DataFrame. Once the DataFrames are created, you'll use matplotlib library to create scatter plots. Remember, you already have a SparkContext sc, rdd_split_int and cluster_centers variables available in your workspace. Instructions 100 XP Convert rdd_split_int RDD into a Spark DataFrame. Convert Spark DataFrame into a Pandas DataFrame. Create a Pandas DataFrame from cluster_centers list. Create a scatter plot of the raw data and an overlaid scatter plot with centroids for k = 15. ''' # Code # Convert rdd_split_int RDD into Spark DataFrame rdd_split_int_df = spark.createDataFrame(rdd_split_int, schema=["col1", "col2"]) # Convert Spark DataFrame into Pandas DataFrame rdd_split_int_df_pandas = rdd_split_int_df.toPandas() # Convert cluster_centers into Panda DataFrame cluster_centers_pandas = pd.DataFrame(cluster_centers, columns=["col1", "col2"]) # Create an overlaid scatter plot plt.scatter(rdd_split_int_df_pandas["col1"], rdd_split_int_df_pandas["col2"]) plt.scatter(cluster_centers_pandas["col1"], cluster_centers_pandas["col2"], color="red", marker="x") plt.show()
true
fbbf3b764a4bcec5c900e1c9c45b70b235b2cbfd
KruZZy/magic-of-computing
/perm_backtracking.py
857
4.125
4
def backtrack(depth, max_level): global solution, appears ## in Python, global variables used inside a function definition should be mentioned beforehand. if depth <= max_level: ## if depth reaches max_level, we have generated a permutation. for i in range(1, max_level+1): if appears[i] == False: ## check for appearance in the additional vector appears[i] = True ## mark number i as used and add it to the solution solution[depth] = i backtrack(depth+1, max_level) appears[i] = False ## when coming back from recursion, unmark the number to add it later. solution[depth] = 0 else: print(solution[1:]) ## as we are using indexes 1 through N N = int(input("Give N: ")) solution = [0] * (N+1) appears = [False] * (N+1) backtrack(1, N)
true
054510812ff367b36335420214408a41f13a00a9
python-kurs-sda/python-kurs
/zadania_domowe/liczby_pierwsze.py
871
4.15625
4
""" Napisz funkcje stwierdzajaca czy podana jako argument liczba jest liczba pierwsza czy nie. Liczba jest pierwsza, kiedy dzieli sie tylko przez siebie i przez 1. Jednym z algorytmow wyszukiwania liczb pierwszych jest sprawdzenie czy zadna z liczb od 2 do LICZBA-1 (lub od 2 do pierwiastek z LICZBA) nie dzieli badanej liczby bez reszty. Uwaga: 0 i 1 nie sa zaliczane ani do liczb pierwszych, ani do zlozonych. """ def is_prime_number(number): """Sprawdza czy argument number jest liczba pierwsza. :param number: liczba typu int. :return: True jezeli liczba jest pierwsza, False jezeli jest zlozona. """ is_prime = True if number in range(0, 2): is_prime = False else: for i in range(2, number - 1): if number % i == 0: is_prime = False return is_prime
false
97621a05f4e5632190b12bd08275ad6510fa850a
BrunoVittor/pythonexercicios
/pythonexercicios/pythonexercicios/ex085.py
589
4.25
4
#Exercício Python 085: # Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. # No final, mostre os valores pares e ímpares em ordem crescente. lista = [[], []] valor = 0 for c in range(1, 8): valor = int(input(f'Digite o {c}º valor: ')) if valor % 2 == 0: lista[0].append(valor) else: lista[1].append(valor) lista[0].sort() lista[1].sort() print(f'Os valores pares digitados foram {lista[0]}') print(f'Os valosres impares digitados forma {lista[1]}')
false
b0f806ba4c57e9266dc436b4919d80dd99b55858
BrunoVittor/pythonexercicios
/pythonexercicios/pythonexercicios/ex088.py
1,304
4.15625
4
# Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA a criar palpites. # O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. from random import randint for x in range(int(input("Digite quantidade de jogos: "))): print([randint(1, 61) for i in range(6)]) '''lista = [] jogos = [] quant = int(input('Quantos jogos?: ')) tot = 1 while tot <= quant: cont = 0 while True: num = randint(1, 60) if num not in lista: lista.append(num) cont += 1 if cont >= 6: break lista.sort() jogos.append(lista[:]) lista.clear() tot += 1 print('Sorteando jogos') for i, l in enumerate(jogos): print(f'Jogo {i + 1}: {l}') ''' '''importar a biblioteca de sorteio lista principal lista temporária dentro o loop executar as tarefas abaixo perguntar qual o máximo de jogos serão sorteados sortear no máximo 6 jogos sortear números de 1 á 60 adicionar os números em uma lista temporária criar uma cópia da lista temporária em uma lista pricipal excluir as informações da lista temporária cada vez que o loop rodar na quantidade determinada mostar a quantidade de jogos com os números sorteados'''
false
845dfa9e7e10caba0ea4862866f7138b0f3a3542
poojitha2803/lab-programs
/lab exp-4.4.py
760
4.40625
4
4.4) In algebraic expressions, the symbol for multiplication is often left out, as in 3x+4y or 3(x+5). Computers prefer those expressions to include the multiplication symbol, like 3*x+4*y or 3*(x+5). Write a program that asks the user for an algebraic expression and then inserts multiplication symbols where appropriate. Program: exp = input("Enter algebric expression: ") cexp = '' for ch in exp: if ch>='0' and ch<='9': cexp = cexp + ch elif ch=='(': cexp = cexp + '*' + ch elif ch>='a' and ch<='z' and cexp[-1]!='(': cexp = cexp + '*' + ch else: cexp = cexp + ch print("Converted expression is :",cexp) Output: Enter algebric expression: 3x+4y Converted expression is : 3*x+4*y
true
672843b94c411d5121eeccf9637ca26e68895620
ectom/Coding-Dojo-Python-Stack
/1 - python_fundamentals/dictionary.py
250
4.125
4
def dictionary(): dict = { 'name' : 'Ethan Tom', 'age' : '20', 'country of birth' : 'The United States', 'favorite language' : 'python' } for i in dict: print "My " + i + " is " + dict[i] dictionary()
false
bb2d174195cab59c27f2006540c6389f5934bc60
TLyons830/The-Tech-Academy-Basic-Python-Projects
/Python_if.py
278
4.21875
4
num1 = 10 key = False if num1 == 12: if key: print('num1 is EQUAL to 12 and they have the key') else: print('num1 is EQUAL to 12 and they DO NOT have the key') elif num1 < 12: print('num1 is LESS than 12') else: print('num1 is GREATER than 12')
true
92e7aefdb2813c3da5c2d27bd398aaf1f5ece125
IliaIliev94/cs50-psets
/pset6/mario.py
833
4.46875
4
from cs50 import get_int # Main function which calls the get input function and prints the piramid def main(): height = get_user_input() # Prints the piramid on the basis of the number of rows the user has given as input in the height variable for i in range(height): for j in range(i + 1, height): print(" ", end="") for k in range(i + 1): print("#", end="") for l in range(2): print(" ", end="") for m in range(i + 1): print("#", end="") print() # Promts the user for input until he gives a number between 1 and 8 and return that number def get_user_input(): while True: i = get_int("Height: ") if i >= 1 and i <= 8: return i # Calls the main function if __name__ == "__main__": main()
true
6da71344509a6de17ab0334682d7938a1bb5d9b6
niniyao/PythonCrashCourse
/Chapter 4/TryitYourself_4_13 copy.py
315
4.1875
4
my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') print("my favoriate foods are:") for my_food in my_foods: print(my_food) print("\nmy friend's favoriate foods are:") for friend_food in friend_foods: print(friend_food)
false
1c00dfda6bbdbcb31d471be6dfa3a9ad0fdcfcd5
ZhangzhiS/study_note
/Algorithm/binary_search_tree.py
2,232
4.34375
4
""" 二叉查找树(英语:Binary Search Tree),也称为二叉搜索树、有序二叉树(ordered binary tree)或排序二叉树(sorted binary tree),是指一棵空树或者具有下列性质的二叉树: 1. 若任意节点的左子树不空,则左子树上所有节点的值都小于他的根节点的值。 2. 若任意节点的右子树不空,则右子树上所有节点的值都大于他的根节点的值。 3. 任意节点的左右子树也分别为二叉查找树。 4. 没有键值相等的节点 二叉查找树于其他数据结构的优势在于查找、插入的时间复杂度较低。为O(log n)。 来源于:https://zh.wikipedia.org/wiki/%E4%BA%8C%E5%85%83%E6%90%9C%E5%B0%8B%E6%A8%B9 """ class Node(object): """ 节点类 """ def __init__(self, data=None): self.data = data self.l_child = None self.r_child = None class BinarySearchTree(object): """ 二叉搜索树 """ def __init__(self, li=None): self.root = None # if li: # self.root = self.insert(self.root, li[0]) # for value in li[1:]: # self.insert(self.root, value) def insert(self, root, value): """数据的插入""" # print(root, value) if root is None: # 如果根节点为None,则初始化根节点 root = Node(value) elif value < root.data: # 如果要插入的值小于根节点的值,则插入左子树中 root.l_child = self.insert(root.l_child, value) else: # 如果要插入的值大于根节点的值,则插入右子树中 root.r_child = self.insert(root.r_child, value) return root def in_order(self, root): if root: self.in_order(root.l_child) print(root.data, end=", ") self.in_order(root.r_child) if __name__ == '__main__': lis = [62, 58, 88, 47, 73, 99, 35, 51, 93, 29, 37, 49, 56, 36, 48, 50] btree = BinarySearchTree() for i in lis: if btree.root is None: btree.root = Node(lis[0]) else: btree.insert(btree.root, i) btree.in_order(btree.root)
false
fdd668a446e26600bc06b2d3a6c648a63271b270
chen808/python_fundemental_assignments
/assignment_10_Regular_Expression_findword.py
816
4.1875
4
# importing 're' to use Regular expression import re str = 'an example word:cat!!' match = re.search(r'word:\w\w\w', str) # If-statement after search() tests if it succeeded if match: print 'found', match.group() ## 'found word:cat' else: print 'did not find' # searches to see if word 'Bat' is found whatever = 'I am Batman, king of Gotham!' match = re.search(r'Bat', whatever) if match: print 'found', match.group() else: print 'did not find' # finds the three letters after 'Bat' whatever = 'I am Batman, king of Gotham!' match = re.search(r'Bat\w\w\w', whatever) if match: print 'found', match.group() else: print 'did not find' # finds the email str = 'purple alice-b@google.com monkey dishwasher' match = re.search(r'[\w.-]+@[\w.-]+', str) if match: print match.group() ## 'alice-b@google.com'
true
9a07f9201feedb1002445d2a7cc44cebe85cbd3c
mskenderovicGH/Data-Structures-Implementation-Python
/HeapValidation.py
407
4.125
4
# this function will check if heap is as it should be def heap_check(heap): i=0 while (2 * i + 1) < len(heap): if heap[i] < heap[2*i+1] and heap[i] < heap[2*i+1]: print('ok') else: print('bad') return False i = i + 1 return True if __name__ == '__main__': heap = [1,2,3,9,5,6,7,8] print(heap_check(heap))
false
bf5d3eb1e0644ff2c6e1e756f0874778f4022df0
monica-cornescu/learn_python_hackerrank-30-days
/hackerrank_day7.py
484
4.15625
4
#Given an array, , of integers, print 's elements in reverse order as a single line of space-separated numbers. import math import os import random import re import sys if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) reverseArr = arr[::-1] for elem in reverseArr: print(elem, "", end ="") ''' or the for could be written as: for i in range(len(reverseArr): print(reverseArr[i], "", end = "") '''
true
73a0b4c8c0c52a314801f74957c52f34069d8d4b
Katiedaisey/Projects
/Solutions/factorial_finder.py
643
4.3125
4
# **Factorial Finder** - # The Factorial of a positive integer, n, is defined as # the product of the sequence n, n-1, n-2, ...1 and the # factorial of zero, 0, is defined as being 1. # Solve this using both loops and recursion. def factorial(num): if num < 2: fact = 1 else: fact = num * factorial(num - 1) return fact; num = int(raw_input('Enter a number: ')) typ = raw_input('loops or recursion (l/r)? ') fact = 1 if typ == 'l': if num < 2: fact = 1 else: n = 1 while n < num: n = n + 1 fact = fact * n print fact elif typ == 'r': if num < 2: fact = 1 else: fact = factorial(num) print fact
true
b2f4654953d024fe23e34af66d4f6922e29b9970
ScottLoPinto/ToyProblems
/src/2021/june/2/switch_sort.py
1,835
4.40625
4
# Have the function SwitchSort(arr) take arr which will be an an array consisting of integers # 1...size(arr) and determine what the fewest number of steps is in order to sort the array # from least to greatest using the following technique: Each element E in the array can swap # places with another element that is arr[E] spaces to the left or right of the chosen element. # You can loop from one end of the array to the other. For example: if arr is the array [1, 3, 4, 2] # then you can choose the second element which is the number 3, and if you count 3 places to the left you'll # loop around the array and end up at the number 4. Then you swap these elements and arr is then [1, 4, 3, 2]. # From here only one more step is required, you choose the last element which is the number 2, count 2 places # to the left and you'll reach the number 4, then you swap these elements and you end up with a sorted array # [1, 2, 3, 4]. Your program should return an integer that specifies the least amount of steps needed in order # to sort the array using the following switch sort technique. # The array arr will at most contain five elements and will contain at least two elements. def switch_sort(arr): # if ( index_current +- num ) % arr.len == desired_index, then swap and ++ swaps # if new_arr == sorted_arr, return swaps swaps = 0 sorted_arr = sorted(arr) while(arr != sorted_arr): for i in range(len(arr)): idx_right = (i + arr[i]) % len(arr) idx_left = (i - arr[i]) % len(arr) idx_desired = arr[i]-1 if(arr[i] == sorted_arr[i]): continue elif(idx_right == idx_desired): temp = arr[i] arr[i] = arr[idx_right] arr[idx_right] = temp swaps+=1 elif(idx_left == idx_desired): temp = arr[i] arr[i] = arr[idx_left] arr[idx_left] = temp swaps+=1 return swaps
true
81600d0a5d82922f89ff10b94157f24de6752067
psnehas/PreCourse-2
/Exercise_3.py
1,226
4.25
4
# Time complexity:O(n) # Space complexxity: O(1) # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): newNode = Node(new_data) if self.head == None: self.head = newNode else: cur = self.head while cur.next: cur = cur.next cur.next = newNode # Function to get the middle of # the linked list def printMiddle(self): # use two pointer technique and advance the fast pointer two nodes at a time while slow pointer moves one node at a time. This way when fast pointer reaches the end of the list, slow pointer will point to the middle of the list. if self.head == None: raise Exception("LinkedList is empty!") slow, fast = self.head, self.head while fast and fast.next: slow = slow.next fast = fast.next.next print(slow.data) # Driver code list1 = LinkedList() list1.push(5) list1.push(4) list1.push(2) list1.push(3) list1.push(1) list1.printMiddle()
true
34bea9ae596a785783149b1c97ad0339d63079f8
davidknoppers/interview_practice
/codewars/triplet_sums.py
1,609
4.34375
4
#!/usr/bin/python3 #we import random to generate random arrays to test the algo import random """ triplet_sums finds all groups in an array that add up to the target sum The array and target are both supplied by the user """ def triplet_sums(arr, target): #sort the array to make subsequent subroutines much faster #we could also call set here if we don't want repeat terms in the array arr = sorted(arr) i = 0 #result will hold our triplets result = [] while i < len(arr) - 2: #one pointer starts at the beginning of the subarray, the other at the end start = i + 1 end = len(arr) - 1 #arr[i] is the starting point at each iteration in the loop. We sum arr[i] # with the elements at start and end and check what we get while start < end: _sum = arr[i] + arr[start] + arr[end] #if sum is too big, we decrement end if _sum > target: end -= 1 #if sum is too small, we increment start elif _sum < target: start += 1 #if the sum is a match, we try to put it in result(checking for dups first) #and then decrement end if _sum == target: if [arr[i], arr[start], arr[end]] not in result: result.append([arr[i], arr[start], arr[end]]) end -= 1 i += 1 return result arr = [] for i in range(15): arr.append(random.randint(1, 15)) print("test array: {}".format(arr)) print("test array, sorted: {}".format(sorted(arr))) print(triplet_sums(arr, 20))
true
e36fc7cb4cd92bbb359491a3e477e059b6379b74
GururajM/SimpleCalculation
/simple_calculation/simple_calculation/logic/calculator.py
2,334
4.40625
4
class Calculator: """ A class used to represent a basic calculator that performs an arithmetic operation on two operands ... Attributes ---------- operand_1 : int An interger value that represents the first operand operand_2 : int An interger value that represents the first operand operation : str The string value representing arithmetic operation to be performed on the operands Methods ------- calculate_result (operand_1, operand_2, operation) Performs the specified operation on the operans and return the result of the operation """ def __init__(self, operand_1, operand_2, operation): """ Parameters ---------- operand_1 : int An interger value that represents the first operand operand_2 : int An interger value that represents the first operand operation : str The string value representing arithmetic operation to be performed on the operands """ self.operand_1 = operand_1 self.operand_2 = operand_2 self.operation = operation def calculate_result(self): """ Performs the specified operation on the operans and return the result of the operation If the argument `operand_2` is 0 and `operation` is `%`, then infinity is returned. Parameters ---------- operand_1 : int An interger value that represents the first operand operand_2 : int An interger value that represents the first operand operation : str The string value representing arithmetic operation to be performed on the operands """ # If parameter 'operation' is '+' then add the operands if self.operation == '+': return self.operand_1 + self.operand_2 # If parameter 'operation' is '-' then sibtract the operands elif self.operation == '-': return self.operand_1 - self.operand_2 # If parameter 'operation' is '*' then multiply the operands elif self.operation == '*': return self.operand_1 * self.operand_2 # Finally when parameter 'operation' is '%' then divide the operands else: # Check if the parameter 'operand_2' is 0, if not return result of division, else return infinity try: self.operand_1 / self.operand_2 return self.operand_1 / self.operand_2 except ZeroDivisionError: return float('Inf')
true
7c122b2ceeb257b19178075d1b7accb63ed7b5c9
anujvyas/Data-Structures-and-Algorithms
/Data Structures/3. Linked List/node_swap_sll.py
1,193
4.125
4
# Swap two nodes in a given linkedlist without swapping data from singly_linked_list import Node, LinkedList def swap_node(head, x, y): # If both values are same if x == y: return head # Find x prevX = None currX = head while currX != None and currX.data != x: prevX = currX currX = currX.next # Find y prevY = None currY = head while currY != None and currY.data != y: prevY = currY currY = currY.next # If any of the value is not present in the linkedlist if currX == None or currY == None: print('Cannot swap nodes as one or more nodes not present in linkedlist!') return head # If x is head // make y as the new head if prevX == None: head = currY else: prevX.next = currY # If y is head // make x as the new head if prevY == None: head = currX else: prevY.next = currX # Swap next pointers temp = currX.next currX.next = currY.next currY.next = temp return head if __name__ == '__main__': l = LinkedList() l.append_node("A") l.append_node("B") l.append_node("C") l.append_node("D") l.traverse() l.head = swap_node(l.head, 'A', 'C') l.traverse()
true
f98705a18fb7e34b4e4a3ba8292aa01d05409e77
honghaoz/DataStructure-Algorithm
/Python/Cracking the Coding Interview/Chapter 5_Bit Manipulation/5.6.py
746
4.21875
4
from Bit import * from operator import xor # Write a program to swap odd and even bits in an integer with as few instructions as possible # (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on) # Suppose 32-bit integer def swapOddWithEven(num): oddMask = bitToInt("01010101010101010101010101010101") evenMask = bitToInt("10101010101010101010101010101010") oddNumbers = num & oddMask evenNumbers = num & evenMask oddNumbers = oddNumbers << 1 evenNumbers = evenNumbers >> 1 num = oddNumbers | evenNumbers return num def test(): print "Passed" if swapOddWithEven(bitToInt("0101")) == bitToInt("1010") else "Failed" print "Passed" if swapOddWithEven(bitToInt("100101")) == bitToInt("011010") else "Failed" test()
true
a40e3892dd553267873b17ec1ebecbbadd9e8415
honghaoz/DataStructure-Algorithm
/Python/LeetCode/ZigZag Conversion.py
1,616
4.21875
4
# ZigZag Conversion # The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) # P A H N # A P L S I I G # Y I R # And then read line by line: "PAHNAPLSIIGYIR" # Write the code that will take a string and make this conversion given a number of rows: # string convert(string text, int nRows); # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". class Solution: # @return a string def convert(self, s, nRows): if nRows == 1: return s res = "" length = len(s) for row in xrange(nRows): section = 0 while section < length / (2 * nRows - 2) + 1: if row == 0: index = (2 * nRows - 2) * section if index < length: res += s[index] elif row == nRows - 1: index = (2 * nRows - 2) * section + nRows - 1 if index < length: res += s[index] else: firstIndex = (2 * nRows - 2) * section + row if firstIndex < length: res += s[firstIndex] secondIndex = (2 * nRows - 2) * (section + 1) - row if secondIndex < length: res += s[secondIndex] section += 1 return res def main(): s = Solution() print "Passed" if "PAHNAPLSIIGYIR" == s.convert("PAYPALISHIRING", 3) else "Failed" main()
true
3d21be7ff3d017b4cf4685049a63194743820f83
honghaoz/DataStructure-Algorithm
/Python/Cracking the Coding Interview/Chapter 7_Mathematics and Probability/7.4.py
1,594
4.21875
4
# Write methods to implement the multiply, subtract, and divide operations for integers. # Use only the add operator. # multiply def multiply(a, b): summ = 0 if b == 0: return 0 elif b > 0: for i in xrange(b): summ += a return summ else: for i in xrange(b, 0): summ += a return negate(summ) def subtract(a, b): # a - b return a + negate(b) def negate(num): assert(isinstance(num, int)) if num == 0: return num elif num > 0: for i in xrange(0, num + num): num += -1 return num else: for i in xrange(num + num, 0): num += 1 return num def divide(a, b): assert(not b == 0) negativeFlag = False if a < 0 or b < 0: negativeFlag = True a = a if a > 0 else negate(a) b = b if b > 0 else negate(b) if a == b: return 1 if not negativeFlag else -1 elif a < b: return 0 else: res = 0 while a >= b: res += 1 a = subtract(a, b) return res if not negativeFlag else negate(res) def test(): print "Passed" if multiply(2, 3) == 6 else "Failed" print "Passed" if multiply(2, 0) == 0 else "Failed" print "Passed" if multiply(2, -4) == -8 else "Failed" print "Passed" if subtract(2, 3) == -1 else "Failed" print "Passed" if subtract(2, 2) == 0 else "Failed" print "Passed" if subtract(2, -2) == 4 else "Failed" print "Passed" if divide(2, 1) == 2 else "Failed" print "Passed" if divide(2, 4) == 0 else "Failed" print "Passed" if divide(2, 2) == 1 else "Failed" print "Passed" if divide(2, -1) == -2 else "Failed" print "Passed" if divide(-2, 4) == 0 else "Failed" print "Passed" if divide(-2, 2) == -1 else "Failed" test()
true
8b807ed989dddfecc2e89f7632ca3da1f6ac1f47
caveman0612/python_fundeamentals
/03_more_datatypes/4_dictionaries/03_17_first_dict.py
261
4.125
4
''' Write a script that creates a dictionary of keys, n and values n*n for numbers 1-10. For example: result = {1: 1, 2: 4, 3: 9, ...and so on} ''' dict = {} for i in range(1, 11): value = input(f"input value for {i} key") dict[i] = value print(dict)
true
dedf0e77eb39d7ff8d20d1a79162f43187ce3248
caveman0612/python_fundeamentals
/03_more_datatypes/3_tuples/03_16_pairing_tuples.py
691
4.5
4
''' Write a script that takes in a list of numbers and: - sorts the numbers - stores the numbers in tuples of two in a list - prints each tuple If the user enters an odd numbered list, add the last item to a tuple with the number 0. Note: This lab might be challenging! Make sure to discuss it with your mentor or chat about it on our forum. ''' new_list = [] list_numbers = [1, 3, 5, 6, 7, 8, 3, 5] list_numbers.sort() if len(list_numbers) % 2 != 0: list_numbers.append(0) for index, num in enumerate(list_numbers): if index % 2 != 0: continue else: new_tuple =(num, list_numbers[index + 1]) new_list.append(new_tuple) print(new_list)
true
d124098dda95e3b66e6a78d6d9f65ea76525b1b1
salisquraishi/Python-programming-1
/codes/program17.py
1,957
4.34375
4
# A website requires the users to input username and password to register. # Write a program to check the validity of password input by users. # Following are the criteria for checking the password: # 1. At least 1 letter between [a-z] # 2. At least 1 number between [0-9] # 1. At least 1 letter between [A-Z] # 3. At least 1 character from [$#@] # 4. Minimum length of transaction password: 6 # 5. Maximum length of transaction password: 12 # Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. # Example # If the following passwords are given as input to the program: # ABd1234@1,a F1#,2w3E*,2We3345 # Then, the output of the program should be: # ABd1234@1 import re pwd = input("Enter Password>") # validation funtion to check all constraints mentioned in the problem statement def validate(pwd, good = 'y'): upper_flag = 'n' spcl_flag = 'n' if (len(pwd) < 6 or len(pwd) > 12): print("Length of the password should be minimum 6 character or maximum 12 characters long") good = 'n' pass elif pwd.lower().isalpha(): print("Password should contain at least one alphabate character") good = 'n' pass elif pwd.isdigit(): print("Password should contain at least one numeric character") good = 'n' pass for c in pwd: if re.match('[A-Z]', c): upper_flag = 'y' if re.match('[$@#]', c): spcl_flag = 'y' if upper_flag == 'n': print("At least one upper case character required") good = 'n' pass if spcl_flag == 'n': print("At least one character needs to be #, @ or #") good = 'n' pass return good # call validate function good = validate(pwd) if good == 'y': print("Awesome !!, your password is set")
true
86be9953fb3c6ce6071970af31f4b614ea976e6c
salisquraishi/Python-programming-1
/codes/program29.py
581
4.3125
4
# Define a class named Shape and its subclass Square. # The Square class has an init function which takes a length as argument. # Both classes have a area function which can print the area of the shape # where Shape's area is 0 by default. class Shape(): def __init__(self): pass def area(self): self.area = 0 print(self.area) class Square(Shape): def __init__(self, l): self.length = l def area(self): self.area = self.length*self.length print(self.area) sq1 = Shape() sq1.area() sq2 = Square(4) sq2.area()
true
db651349442682ab85e0b52b8a136ba374fc9663
salisquraishi/Python-programming-1
/codes/program41.py
425
4.1875
4
# Please write a program which count and print the numbers of each character in a # string input by console. # Example: # If the following string is given as input to the program: # abcdefgabc # Then, the output of the program should be: # a,2 # c,2 # b,2 # e,1 # d,1 # g,1 # f,1 count = {} s = input(">") for c in list(s): if c.strip(): count[c] = count.get(c,0) + 1 for k,v in count.items(): print(k,v)
true
1ac3343ed21639ba7e243b65f6abc69d5e04e4ed
predatory123/byhytest
/python_practice/python0525/001.py
553
4.25
4
#定义一个汽车类 class car(): def __init__(self,make,model,year): # 描述汽车的3个属性 self.make = make self.model = model self.year = year #定义一个汇总信息的方法 def get_desciptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() #调用类和方法 class new_car(car): def __init__(self,make,model,year): super.__init__(make,model,year) my_new_car = car('Audi','RS3',2019) print(my_new_car.get_desciptive_name())
false
52de20c4cb0d29595026a8690a3f1d566040ba66
11Vladimir/algoritm
/lesson_3/task_7.py
481
4.15625
4
#!/usr/bin/python3.8 # 7. В одномерном массиве целых чисел определить два наименьших элемента. # Они могут быть как равны между собой (оба являться минимальными), так и различаться. from random import randint array = [randint(1, 20) for i in range(10)] print(array) min1 = min(array) array.remove(min1) min2 = min(array) print(min1) print(min2)
false
8ea531d7828985ff3649b1bc809d6225226a0aa0
vpivtorak/Python-home-work
/home work 1 hard.py
605
4.1875
4
print("Здравствуйте, введите:") a = str(input('Имя:')) b = int(float(input('Возраст:'))) c = int(float(input('Вес:'))) if c > 50 and c < 120 and b < 35: print (a,', ' 'у вас отличное здоровье') elif c < 50 or c > 120 and b < 35: print(a,', ' 'вам стоит изменить образ жизни') elif c < 50 or c > 120 and b > 45: print(a, ', ' 'вам требуется врачебный осмотр') else: print ('Не достаточно данных для расчёта, обратитесь к консультанту')
false
144bee13861744e0a7dd3fd7606e6d906121c43b
Graham-CO/ai_ml_python
/chapter_4/ReLU_applied.py
1,015
4.15625
4
# Graham Williams # grw400@gmail.com # Apply ReLU activation function to a dense layer import numpy as np import nnfs from nnfs.datasets import spiral_data nnfs.init() class Layer_Dense: def __init__(self, n_inputs, n_neurons): self.weights = 0.01 * np.random.randn(n_inputs, n_neurons) self.biases = np.zeros((1, n_neurons)) def forward(self, inputs): self.output = np.dot(inputs, self.weights) + self.biases class Activation_ReLU: # Forward pass def forward(self, inputs): # Calculate output values from input self.output = np.maximum(0, inputs) # Create dataset X, y = spiral_data(samples=100, classes=3) # Create Dense Layer with 2 input features and 3 output values dense1 = Layer_Dense(2,3) # Create ReLU activation activation1 = Activation_ReLU() # Forward pass training data through layer dense1.forward(X) # Forward pass through activation func. # Takes in output from previous layer activation1.forward(dense1.output) print(activation1.output[:5])
true
4861446c3fd28a9c675bb295a64895de73c2d8bb
Philosocode/python-stuff
/recursion/factorial.py
380
4.21875
4
""" Factorial of 5: 5 * factorial(4) = 120 4 * factorial(3) = 24 3 * factorial(2) = 6 2 * factorial(1) = 2 """ def factorial(num): if num == 0: return 1 return num * factorial(num - 1) def iter_factorial(num): product = 1 for num in range(num, 1, -1): product *= num print(product) num = 5 print(factorial(num)) iter_factorial(num)
false
9d4508554077b8d19e2736f10fd2186ef67058ea
fathurdanu/time-calculator
/time_calculator.py
2,545
4.3125
4
#What is n days from now? def what_day(today,how_many_days): list_of_days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] today = "".join([char.lower() for char in today]) for day in range(len(list_of_days)): now = "".join([char.lower() for char in list_of_days[day]]) if now == today: today_index = day break return list_of_days[(today_index +(how_many_days % 7))%7] #build string answer def build_string(data,day=''): # no 00 (00 to 12) if data[0] == 0: text = '12' else: text = str(data[0]) #if not include the name of day if not day: if data[1] < 10: text += ":0" else: text += ":" text += str(data[1]) + " " + data[2] if data[3] != '': text += " " + data[3] #if include the name of day else: tomorrow = what_day(day,data[4]) if data[1] < 10: text += ":0" else: text += ":" text += str(data[1]) + " " + data[2] + ", " + tomorrow if data[3] != '': text += " " + data[3] return text #create a string adverb of time def future_day(day): if day == 1: msg = "(next day)" elif day == 0: msg = "" else: msg = "("+str(day)+" days later)" return msg #calculation process def addition_time(hour,hour_duration,minute,minute_duration,meridiem): if meridiem == "PM": hour += 12 new_hour = hour + hour_duration new_minute = minute + minute_duration new_day = 0 hour_temp = int(new_minute // 60) if new_minute >= 60: new_minute -= 60 if hour_temp >= 1: for hr in range(hour_temp): new_hour += 1 if new_hour // 24 > 0: for dy in range(int(new_hour // 24)): new_day += 1 new_hour -= 24 if new_hour >= 12: meridiem = "PM" new_hour -= 12 else: meridiem = "AM" return [new_hour,new_minute,meridiem,future_day(new_day),new_day] def add_time(start, duration, day=''): #get the time and convert string to integer n_start = len(start) n_duration = len(duration) hour = int(start[0:n_start-6]) minute = int(start[n_start-5:n_start-3]) meridiem = start[-2:] hour_duration = int(duration[0:n_duration-3]) minute_duration = int(duration[-2:]) #call the addition process result = addition_time(hour,hour_duration,minute,minute_duration,meridiem) #call function to build the answer (string) if not day: new_time = build_string(result) else: new_time = build_string(result,day) return new_time
false
6b4333b7346228c192fa2b21698629235ea873d9
nuocode/python
/python-exercise/面向对象编程/类和实例.py
1,288
4.125
4
# class Student(object): # pass # #bart是指向Student的实例 # bart = Student() # print(bart) # 返回<__main__.Student object at 0x00000230C87C9630> 0x00000230C87C9630表示内存 # print(Student) # # #给实例绑定属性 # bart.name = "Simpson Blair" # print(bart.name) #### 创建模板,绑定属性 #### # class Student(object): # # 第一个参数永远是self,指向自己,不需要传参 # def __init__(self,name,score): # self.name = name # self.score = score # # bart = Student('Simpson Blair', 19) # print(bart.name) # print(bart.score) #类的方法 # class Student(object): # # def __init__(self, name, score): # self.name = name # self.score = score # # def print_score(self): # print('%s: %s' % (self.name, self.score)) # # bart = Student('Simpson Blair', 19) # result_score = bart.print_score() # print(result_score) class Student(object): def __init__(self,name,score): self.name = name self.score = score def get_grade(self): if self.score >=90: return "A" elif self.score >=60: return "B" else: return "C" lisa = Student("Lisa", 99) bart = Student("Bart", 59) print(lisa.name, lisa.get_grade()) print(bart.name, bart.get_grade())
false
df595a116cc32bd0b410ce437495a46fd4504640
mailgurudev/python
/string_list.py
272
4.375
4
word = input(str("Enter a word ")) new_word = [] for c in word: new_word.append(c) print(new_word) print(list(reversed(new_word))) if new_word == list(reversed(new_word)): print("Its is a pallindrome") else: print("it is not a pallindrome")
true
17de56cea61b7de040969163bdc810fab2df99ea
malliksiddarth/python-program
/sid3.py
297
4.40625
4
#!/usr/bin/python3 # guess what this program does? import random r=random.randint (1,6) #give random number print(r) if r<35: print(r) print(":is less than 35") elif r==30: print("30 is multiple of 10 and 3, both") elif r>=35: print(r,"is greater than 35") else: print("your number is:",r)
true
a49580e8528396802a65a6f8112fab04ed1adede
adronkin/algo_and_structures_python
/Lesson_1/6.py
688
4.25
4
# 6. Пользователь вводит номер буквы в алфавите. Определить, какая это буква. def search_letter(num, letter_list): """По числу num возвращает символ из строки под номером num""" return letter_list[num - 1] ABC = 'abcdefghijklmnopqrstuvwxyz' LETTER_NUM = int(input('Ввидите номер буквы: ')) if 1 <= LETTER_NUM <= 26: print(f'Под номером {LETTER_NUM} в английском алфавите ' f'находится буква "{search_letter(LETTER_NUM, ABC)}"') else: print('В английском алфавите 26 букв')
false
ecf342a3f0a02baa168e7e55ceb2afc5033ed4ad
revanthreddy7/HacktoberFest_2021
/Python/LinkedList.py
1,103
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.last = None def __iter__(self): return self def __next__(self): def print(self): t = self.head while(t != None): print("Node:", t.data) t = t.next def print_node(self, node): while(node != None): print("Node:", node.data) node = node.next def insert_after_pos(self, pos, data): i = 0 t = self.head while(i != pos): t = t.next n = Node(data) n.next = t.next t.next = n return n def insert_after_node(self, node, data): n = Node(data) n.next = node.next node.next = n return n def prepend(self, data): n = Node(data) n.next = self.head self.head = n return n def append(self, data): if(self.last != None): self.last.next = Node(data) self.last = self.last.next return self.last if(self.head == None): self.head = Node(data) self.last = self.head return self.head t = self.head while(t.next != None): t = t.next t.next = Node(data) self.last = t.next return t.next
false
8d0943d7c1bec41ba89e223b676244e1b55efde7
Cherry-RB/sc-projects
/stanCode_Projects/hangmen_game/complement.py
1,023
4.46875
4
""" File: complement.py Name:Cherry ---------------------------- This program uses string manipulation to tackle a real world problem - finding the complement strand of a DNA sequence. THe program asks uses for a DNA sequence as a python string that is case-insensitive. Your job is to output the complement of it. """ def main(): """ TODO: considering all words of dna and its complement """ dna = input('Please give me a DNA strand and I\'ll find the complement: ') complement = build_complement(dna) print('The complement of '+dna+' is '+complement) def build_complement(dna): complement = '' dna = dna.upper() for i in range(len(dna)): if dna[i] == 'A': complement += 'T' elif dna[i] == 'T': complement += 'A' elif dna[i] == 'G': complement += 'C' elif dna[i] == 'C': complement += 'G' return complement ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == '__main__': main()
true
e20ffa60712f7febaf611b7d53a67c50def43b06
Cherry-RB/sc-projects
/stanCode_Projects/boggle_game_solver/largest_digit.py
1,083
4.375
4
""" File: largest_digit.py Name: ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_largest_digit(281)) # 8 print(find_largest_digit(6)) # 6 print(find_largest_digit(-111)) # 1 print(find_largest_digit(-9453)) # 9 def find_largest_digit(n): """ :param n: :return: """ # Base Case if n < 0: n = -n if (n/10) < 1: # 當只剩個位 return n # Self-Similarity else: # 在還有至少兩個位數的情況下 one = n - int(n/10)*10 # 獲得個位數值 tens = int(n/10) # 獲得十位數值以上=捨去個位 ten = tens - int(tens/10)*10 # 獲得十位數值 if one > ten: # 當個位數值大於十位數值 n = int(tens/10)*10 + one # 把n中的十位數值移除 else: n = int(n/10) # 把n中的個位數值移除 return find_largest_digit(n) if __name__ == '__main__': main()
false
49692a5b089f09ed652d3122af53758c56d7f5bf
delos/dm-pta-mc
/src/parallel_util.py
1,791
4.3125
4
""" Collection of useful functions which handle parallelizing the main program """ import numpy as np def generate_job_list(n_proc, total_job_list): """ Will generate the job list to send to the processors. total_job_list - all of the jobs that need to be done """ n_jobs = len(total_job_list) len_job = total_job_list.shape[1] if n_jobs > n_proc: print("\tNumber of jobs is greater than the the number of processors.") print() n_extra_jobs = n_jobs // n_proc job_list = np.zeros((n_proc, 1 + n_extra_jobs, len_job)) count = 0 for i in range(n_proc): for j in range(n_extra_jobs + 1): if count < n_jobs: job_list[i, j, :] = total_job_list[count, :] else: job_list[i, j, :] = -1 * np.ones(len_job) count = count + 1 elif n_jobs < n_proc: n_jobs_per_proc = 1 job_list = np.zeros((n_proc, n_jobs_per_proc, len_job)) print( "\tNumber of jobs is less than the number of processors. " + "Consider running with a smaller number of processors." ) print() for i in range(n_proc): if i < n_jobs: job_list[i, 0, :] = total_job_list[i, :] else: job_list[i, 0, :] = -1 * np.ones(len_job) else: print( "\tNumber of jobs equal to the number of processors. Maximally parallized." ) print() n_jobs_per_proc = 1 job_list = np.zeros((n_proc, n_jobs_per_proc, len_job)) job_list[:, 0, :] = total_job_list[:, :] return job_list
true
ea78d8f3ebbdf04c9ce4ee372c42eca87b38468b
OlehHnyp/Home_Work_4
/Home_Work_4_Task_3_v2.py
538
4.1875
4
while 1: try: number = input("""Please insert integer number and get \ Fibonacci numbers up to this number:""") if int(number) - float(number) == 0 and int(number) == abs(int(number)): break except ValueError: pass up_border = int(number) former_number = 0 next_number = 1 print(f"Here are Fibonacci numbers up to {up_border}:\n{former_number}", end=' ') while next_number < up_border: print(next_number, end=' ') former_number, next_number = next_number, former_number + next_number
true
82aad93d10020fa7ad335e417f69950b53d07123
ThilinaTLM/code-juniors19
/BinaryTree.py
1,592
4.15625
4
""" Add given numbers to a binary tree. Author : Thilina Lakshan Email : thilina.18@cse.mrt.ac.lk """ ## Tree Travels ================================================================================= def getParent(ind): if ind == 0: return None return ((ind + 1)//2) - 1 def getLeft(ind): return 2*ind + 1 def getRight(ind): return 2*ind + 2 """ value of the node can be accessed by: -> tree[node_index] """ ## Tree Create =================================================================================== def addLevel(tree, current_height): tree.extend( ["null"]*(2**current_height) ) # add new value to the tree ## Note that "tree" (LIST), "height"(NUMBER) must have been implemented. def addValue(val): global height, tree pos = findBinaryPos(tree, val) while pos >= len(tree): addLevel(tree, height) tree[pos] = val # find relevent index for new value def findBinaryPos(tree, val): n = 0 # start node (root) while (len(tree) > n) and tree[n] != "null": if val > tree[n]: n = getRight(n) else: n = getLeft(n) return n ## ================================================================================================ ## Create empty Tree tree = [] height = 0 values = [8, 10, 3, 14, 13, 1, 6, 4, 7] # values to add in order # Adding values to the list for v in values: addValue(v) print(tree) ## format and print it. ## str(tree).replace("'", "") can be used to avoid single quotes and print as list
true
d51481c812f3d52ed6aa662f69bf3c295985f196
vaishnavi555/ppl_assignment
/ass1_4.py
336
4.28125
4
import random print("welcome to guessing game!") no = random.randrange(1,11) for x in range(3): guess = input("guess the number from 1-10: ") if guess > no: print("guess is greater than no. !") elif guess < no: print("guess is smaller than no. !") else: print("correct guess!") break print("{} was the number".format(no))
true
4b449817b6867bce05e8ac54dad93c132cd08ed6
SUKESH127/bitsherpa
/[3] CodingBat Easy Exercises /solutions/Warmup-1/pos_neg.py
334
4.28125
4
#Given 2 int values, #return True if one is negative and one is positive. #Except if the parameter "negative" is True, then return True only if both are negative. def pos_neg(a, b, negative): if negative: return (a < 0) and (b < 0) return a * b < 0 print( pos_neg(1, -1, False), pos_neg(-1, 1, False), pos_neg(-4, -5, True))
true
97595b723f01c5c7e07e15347554bd3d72c2580f
simon-pinkmartini/foundations
/class-02/dictionaries.py
303
4.28125
4
#Create a dictionary myself = { "name": "Simon", "age": 35, "home": "Upper East Side" } print (myself) print (myself.keys()) #Reference item in dictionary print ("My name is", myself["name"],".") #Loop through the keys for attribute in myself: print (attribute,":",myself[attribute])
true
9f737dd3188fa08adb3b1afc7a832b1a1c95b51f
bigpigbigpig/learning-python
/Python基础/3. 类中初始化方法.py
707
4.15625
4
# !/usr/bin/env python # -- coding:utf-8 -- # 小猫爱吃鱼,小猫要喝水 class Cat: '''cat link eat fish. cat need drink water. ''' def __init__(self): print("This is a init function.") def eat(self): print("%s like eat fish." % self.name) def drink(self): print("cat need drink water.") def play(what): print("%s play what" % what) tom = Cat() tom.name = "Tom" tom.eat() # __init__() 初始化方法定义类中有哪些对象 # 当使用类名()会自动调用初始化方法 # 创建对象时,会自动创建初始化方法 # 创建对象时,会自动创建初始化方法 # 创建对象时,会自动创建初始化方法
false
d03ea54828a02d741a030a29d6f7c4aa00088d3d
bigpigbigpig/learning-python
/Python基础/14. super.py
783
4.125
4
# super对父类方法的扩展 class Animal: def __init__(self): pass def eat(self): print('eat') def run(self): print('run') def drink(self): print('drink') class Dog(Animal): def bark(self): print('wang') class Xi(Dog): def fly(self): print('i can fly') def eat(self): self.bark() print('一般情况下,我只吃屎') def run(self): self.drink() print('神一样的叫唤') super().run() # x = Xi() x.run() # 子类中如果想要调用父类的方法,使用super就可以 # 封装也就是抽象类,应该实现抽象类,然后在外部进行定义,或者是使用其他的方法进行传递使用,并且将self传递进来
false
6b68c4831b63781058af3d477c5598bc300015c4
CarlosVGC/Codigos-Python
/2_TiposDeDatos.py
588
4.28125
4
#Tipos de datos en python numero = 89 print(numero) print(type(numero)) print('------------------------') numeroFlotante = 16.89 print(numeroFlotante) print(type(numeroFlotante)) print('------------------------') cadena = "Esto es una cadena" print(cadena) print(type(cadena)) print('------------------------') boleano = False print(boleano) print(type(boleano)) print('------------------------') hibridoentfloat = numero + numeroFlotante print(hibridoentfloat) print(type(hibridoentfloat)) print('------------------------') cadena = hibridoentfloat print(cadena) print(type(cadena))
false
b669363d3fdf0e5fffed7cb4e1fe67f5c19628e9
CarlosVGC/Codigos-Python
/3_OperadoresMat.py
605
4.28125
4
#Programa en el que se usan operadores matemáticos n1 = 10 n2 = 2 resultado = n1 + n2 print("La suma es: ", resultado) # se concatena entero con coma (,) resultado = n1 - n2 print("La resta es: ", resultado) resultado = n1 * n2 print("La multiplicacion es: ", resultado) resultado = n1 / n2 print("La division es: ", resultado) resultado = n1 // n2 print("La division entera es: ", resultado) resultado = n1 % n2 print("El modulo es: ", resultado) resultado = n1 ** n2 print("El exponente es: ", resultado) #haciendo expresion matematica res = (3**3)*(13/5*(2*4)) print("El resultado es: ", res)
false
fb8fec5701a6dd4bce19313ec45ba45a1e998c3a
CarlosVGC/Codigos-Python
/PI/04_Diccionarios.py
1,402
4.21875
4
# Ejemplo de uso de diccionarios ''' Estructuras que permite almacenar datos en un diccionario clave: valor Los elementos almacenados no estan ordenados, el orden es indiferente a la hora de almacenar informacion en un diccionario se pueden almacenar dentro de ellos:variables, listas, tuplas, diccionarios, ''' def dic(): diccionario = {'Clave': 'Valor'} #Ejemplo de estructura diccionario print(diccionario) #Imprime el diccionario preferencias = {'Carlos': 'C', 'Rocio': 'Python', 'Pedro': 'Java'} print(preferencias['Carlos']) preferencias['Juan'] = 'Ruby' #Agregando elemento en un diccionario print(preferencias) preferencias['Juan'] = 'Java' #Modificacando un elemento en un diccionario print(preferencias) del preferencias['Pedro'] #Eliminando un elemento del diccionario print(preferencias) def dic2(): #ejemplo de como se realiza un diccionario con listas tupla = ['Jorge','Juan','Pedro','Rodrigo','Elizabeth'] ndic = {tupla[0]: 'c', tupla[1]: 'Java'} print(ndic) def dic3(): #diccionarios con listas, tuplas, diccionarios pais = {'Mexico': ['Toluca','Ecatepec', 'Metepec'], 'EUA': ('Dakota', 'Salt Lake City', 'New York'), 'España':{'Madrid': 'Santiago', 'Barcelona': ['Versalles', 'Milán'] }} print(pais.keys()) print(pais.values()) print(len(pais)) dic() dic2() dic3()
false
bef5d16b5c52b3f37b2046bd452608b8af2c9de1
namratapandit/python-project1
/code/repeatloop.py
1,400
4.28125
4
# program to take 2 numeric inputs and and operation selection from user # the program repeats until the user does not exit # Perform operations like add, sub, mul, divide # keep repeating till user exits # also handle exceptions for invalid inputs def main(): validinput = False # while loop runs till valid entries are entered while not validinput: try: num1 = int(input("Enter number1")) num2 = int(input("Enter number 2:")) operation = int(input("Please choose from the following operations: Add : 1, Subtract : 2, Multiple : 3, Divide: 4. Exit: 9 ")) # ones valiinput values are taken, below operations are carried out based on the selection if operation == 1 : print("Adding...") print(num1 + num2) elif operation == 2 : print("Subtracting...") print(num1 - num2) elif operation == 3 : print("Multiplying...") print(num1 * num2) elif operation == 4 : print("Dividing...") print(num1 / num2) elif operation == 9 : print("Thank you, exiting program now!") validinput = True else: print("Wrong selection, try again") except: print("Invalid entries, try again! ") main()
true
aa6c909edb7d736d23f630be97a28871ba10fcc9
achilles8work/Python_EDX_MIT
/polysum.py
605
4.125
4
''' Grader A regular polygon has n number of sides. Each side has length s. The area of a regular polygon is: The perimeter of a polygon is: length of the boundary of the polygon Write a function called polysum that takes 2 arguments, n and s. This function should sum the area and square of the perimeter of the regular polygon. The function returns the sum, rounded to 4 decimal places. ''' import math def polysum(n,s): area_of_polygon = (0.25 * n * (s**2))/(math.tan(math.pi/n)) perimeter_of_polygon = s*n sum = area_of_polygon + perimeter_of_polygon**2 return round(sum, 4)
true
70b5e56d8f9bf558869dde812e459bd46f975f58
pixelsomatic/python-notes
/tipos.py
651
4.15625
4
tipo = input('Coloca mais um número por favor: ') print('E {} é:\n Int -> {}\n String -> {}\n Alfanumérico -> {}'.format(tipo, tipo.isnumeric(), tipo.isalpha(), tipo.isalnum())) tipos = input('Escreve alguma coisa aí: ') print('O que tu mandou só tem espaço: ', tipos.isspace()) print('O que tu mandou é número: ', tipos.isdigit()) print('O que tu mandou é alfabético: ', tipos.isalpha()) print('O que tu mandou é alfanumérico: ', tipos.isalnum()) print('O que tu mandou está em maiúscula: ', tipos.isupper()) print('O que tu mandou está em minúscula: ', tipos.islower()) print('O que tu mandou está capitalizada: ', tipos.istitle())
false
090d7811f4d90d89084d6aa8075811995f9e137d
rob-kistner/udemy-python-masterclass
/examples/functions_scope.py
1,477
4.28125
4
################################ # # FUNCTIONS - SCOPE # ################################ from modules.utils import * banner("""showing local function vs. global scope""") ############################## def my_function(): test = 1 print('my_function: ', test) test = 0 my_function() print('global: ', test) banner("""outer and inner scoping""") ############################## def outer(): # test = 1 def inner(): test = 2 print('inner: ', test) inner() print('outer: ', test) test = 5 outer() print('global: ', test) banner("""legb example: if the variable isn't defined in the function, it'll look for it down the legb chain""") ############################## def legb_example(): print('inside legb_example function: ', legb_val) legb_val = 10 legb_example() banner("""nonlocal scope: works on enclosed scopes, but not global scopes""") ############################## def outer(): test = 1 def inner(): nonlocal test test = 2 print('inner: ', test) inner() print('outer: ', test) test = 0 outer() print('global: ', test) banner("""global scope: works on global scope, but inner scopes are respected""") ############################## def outer(): global_test = 1 def inner(): global global_test global_test = 2 print('inner: ', global_test) inner() print('outer: ', global_test) global_test = 0 outer() print('global: ', global_test)
true
43120cd6adcbe8a50f8ddb2b4b30e032321ca087
RakeshSuvvari/Joy-of-computing-using-Python
/anagrams.py
298
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 17 22:34:21 2021 @author: rakesh """ str1 = input("Enter the first string: ") str2 = input("Enter the second string: ") if(sorted(str1)==sorted(str2)): print("These are Anagrams") else: print("These are not Anagrams")
true
34f5ee3e01391ac7156c416ceeb87b807ad06701
MarioMarinDev/PythonCourse
/files.py
1,153
4.3125
4
""" r = Read; Shows an error if the file does not exist a = Append; Creates the file if it does not exist w = Write; Creates the file if it does not exist x = Create; Returns an error if the file exists file.read() = Read the entire file file.read(x) = Read the first 'x' chars of the file file.readline = Read the nth line this function is called file.readlines = Returns a list of the lines on the file """ import os, json f = open("files/files_01.txt") print(f.readline()) print(f.readline()) f.close() # Create a file and then delete it f = open("files/files_02.txt", "w") f.close() if os.path.exists("files/files_02.txt"): os.remove("files/files_02.txt") print("The file was removed.") else: print("The file does not exist.") # Create and store data to JSON my_data = { "name": "Mario", "age": 25, "career": "Software Engineer", "hobbies": "Video Games" } json_data = json.dumps(my_data, indent=2) f = open("files/my_data.json", "w") f.write(json_data) f.close # Read a JSON file f = open("files/my_data.json", "r") my_read_data = json.loads(f.read()) print(my_read_data["career"])
true
c02ecb661961def9a8d7f92612f007188130ba8f
mycomath/First-Code-Upload
/madlib.py
1,024
4.28125
4
storyFormat = ''' Once upon a time, deep in an ancient jungle, there lived a { animal }. This {animal} liked to eat {food}, but the jungle had very little {food} to offer. One day, an explorer found the {animal} and discovered it liked {food}. The explorer took the {animal} back to {city} where it could eat as much {food} as it wanted. However, the {animal} became homesick, so the explorer took the {animal} back to the jungle and left a large supply of {food} for the {animal} to eat. The end. ''' def TellStory(): userPicks = dict() addPick ('animal', userPicks) addPick ('food', userPicks) addPick ('city', userPicks) story = storyFormat.format(**userPicks) print (story) def addPick(cue, dictionary): '''Prompt for a user response using the cue string, and place the cue response pair in the dictionary. ''' prompt = 'Enter an example for' '+ cue' ':' response = input (prompt) dictionary[cue] = response tellStory() input('Press enter to end the program.')
true
0d8e4f608cff645d2f765ced84b492c3c3f3338e
mohammedthasincmru/royalmech102018
/greater.py
310
4.15625
4
'''a=int(input("enter the value of a:")) b=int(input("enter the value of b:")) if(a>b): print("a is greater than b") else: print("b is greater than a")''' a=int(input("enter the value of a:")) b=int(input("enter the value of b:")) if(a<b): print("a is lesser than b") else: print("b is lesser than a")
true
07a1f9e9eb5b863e476cc5722cab3437dee44c66
fztest/Classified
/10.bit_manipulation/10.3_L371_Sum_of_two_numbers.py
1,467
4.1875
4
""" Description _______________ Calculate the sum of two integers a and b but you are not allowed to use the operator + and -. Example _____________ Given a = 1 and b = 2, return 3. Approach ______________ a&b - gives you the carry digits a^b - gives you distinctive digits (equals to plus without caring about carry) Now see the code, you will understand write this in python have extra complication since python does not use 2^32 Int Complexity __________ Time - ? Space - O(1) """ class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ if a == 0: return b if b == 0: return a while b != 0: carry = a & b a = a ^ b b = carry << 1 return a class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ # 32 bits integer max MAX = 0x7FFFFFFF # 32 bits interger min MIN = 0x80000000 # mask to get last 32 bits mask = 0xFFFFFFFF while b != 0: # ^ get different bits and & gets double 1s, << moves carry a, b = (a ^ b) & mask, ((a & b) << 1) & mask # if a is negative, get a's 32 bits complement positive first # then get 32-bit positive's Python complement negative return a if a <= MAX else ~(a ^ mask)
true
c66d8e382f798362c16cd9f9dd941c7d63db6f1b
fztest/Classified
/2.Binary_Search/2.16_L274_H-Index.py
1,623
4.15625
4
""" Description ______________ Given an array of citations (each citation is a non-negative integer) of a researcher write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each and the other N − h papers have no more than h citations each." For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. Approach ________________ Smart-ass Bucket Sort ++++++++++++++++++++++ 1. establish n buckets - bucket i represents i references, value represents the count - value in bucket n represnets the count of references >= n 2. Walk backwards for the buckets and maintain a count += value - when count is larger or equal to i we return i """ class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ n = len(citations) buckets = [0 for _ in xrange(n + 1)] for c in citations: if c >= len(citations): buckets[n] += 1 else: buckets[c] += 1 count = 0 print buckets for i in range(n, -1, -1): print i, count count += buckets[i] print 'after', i, count if count >= i: return i return 0
true
5977c9f8b609edfccd873bb3116293e5c402f0b1
fztest/Classified
/3.Binary_Tree_DC/3.15_453_Flatten_Binary_Tree_to_linked_list.py
2,228
4.46875
4
""" Description ___________ Flatten a binary tree to a fake "linked list" in pre-order traversal. Here we use the right pointer in TreeNode as the next pointer in ListNode. Notice Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded. Have you met this question in a real interview? Yes Example 1 \ 1 2 / \ \ 2 5 => 3 / \ \ \ 3 4 6 4 \ 5 \ 6 Approach _______________ The following approach is relied on right_start = root.right root.right = root.left left_tail.right = right_start root.left = None to connect the three pieces Remember, in the recursion we keep track of tail of the tree because we know the HEADS that's why if right_tail: return right_tail if left_tail: return left_tail return root another approach with extra O(N) space is to visit it pre_order and build linked_list """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None """ def helper(self, root): if root is None: return left_tail = self.helper(root.left) right_tail = self.helper(root.right) if left_tail: root_right = root.right root.right = root.left left_tail.right = root_right root.left = None class Solution: # @param root: a TreeNode, the root of the binary tree # @return: nothing def flatten(self, root): # write your code here self.helper(root) def helper(self, root): # return the tail of the flattned list if root == None: return left_tail = self.helper(root.left) right_tail = self.helper(root.right) if left_tail: right_start = root.right root.right = root.left left_tail.right = right_start root.left = None if right_tail: return right_tail if left_tail: return left_tail return root
true
10b1c8ebcb77a4a42e82ad16cb9721d6f5faddeb
fztest/Classified
/6.LinkedList&Array/6.2_599_Insert_Into_a_Cyclic_Sorted_list.py
1,919
4.1875
4
""" Description _________________ Given a node from a cyclic linked list which has been sorted, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node in the list. Return the inserted new node. Example ________________ Given a list, and insert a value 4: 3->5->1 Return 5->1->3->4 Approach ________________ This is a simple problem but by no means trivial to consider corner cases Insert x into the list There are three cases 1. x is in between prev, cur(two consective values in current list) 2. x is the extrema 3. It's neither 1,2 (did not find break and we looped back),duplicated list (1->1->1) We gracefully handle it by using prev, cur and loop through as following Complexity _______________ Time - O(N) Space - O(1) """ """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: # @param {ListNode} node a list node in the list # @param {int} x an integer # @return {ListNode} the inserted new list node def insert(self, node, x): # Write your code here if node is None: a = ListNode(x) a.next = a return a prev = None cur = node while True: prev = cur cur = cur.next # Case 1 if x >= prev.val and x <= cur.val: break # Case 2 # We detected the "end" of the list and check whether x # is the extrema # if not we have continue the looping to allow case 1 to be caught if prev.val > cur.val and (x > prev.val or x < cur.val): break # case 3 if cur is node: break a = ListNode(x) prev.next = a a.next = cur return node
true
35db605f8d41a5b2a0a0cd577da438078d289e64
fztest/Classified
/4.BFS/4.11_178_graph_valid_Tree.py
1,947
4.21875
4
""" Description ______________ Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. Notice ____________ You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. Have you met this question in a real interview? Yes Example ______________ Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true. Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false. Appraoch _____________ A tree with n nodes must be 1. has n-1 edges 2. A BFS must be able to reach all nodes (number of visits == n) This translates to following algorithm Complexity Time - O(N) SPace - O(N) """ class Solution: # @param {int} n an integer # @param {int[][]} edges a list of undirected edges # @return {boolean} true if it's a valid tree, or false def validTree(self, n, edges): # Write your code here from collections import deque if n < 0: return False if len(edges) != n - 1: return False graph = self.createGraph(n, edges) visited = set([]) q = deque() q.append(0) visited.add(0) counter = 0 while q: cur = q.popleft() counter += 1 if graph.has_key(cur): for neighbor in graph[cur]: if neighbor not in visited: q.append(neighbor) visited.add(cur) return counter == n def createGraph(self, n, edges): # return a dict node->[neighbor,neighbor...] from collections import defaultdict graph = defaultdict(list) for o, i in edges: graph[o].append(i) graph[i].append(o) return graph
true
7f639eb12ac60c72593d175c02d2b41dff6cecce
bhavyaagg/python-test
/algs4/sorting/heap.py
1,933
4.21875
4
# Created for BADS 2018 # See README.md for details # Python 3 import sys from algs4.stdlib import stdio """ The heap module provides a function for heapsorting an array. """ def sort(pq): """ Rearranges the array in ascending order, using the natural order. :param pq: the array to be sorted """ n = len(pq) for k in range(n//2, 0, -1): _sink(pq, k, n) while n > 1: _exch(pq, 1, n) n -= 1 _sink(pq, 1, n) def _sink(pq, k, n): """ Moves item at index k down to a legal position on the heap. :param k: Index of the item to be moved :param n: Amount of items left on the heap """ while 2*k <= n: j = 2*k if j < n and _less(pq, j, j+1): j += 1 if not _less(pq, k, j): break _exch(pq, k, j) k = j def _less(pq, i, j): """ Check if item at index i is greater than item at index j on the heap. Indices are "off-by-one" to support 1-based indexing :param pq: the heap :param i: index of the first item :param j: index of the second item :return: True if item at index i is smaller than item at index j otherwise False """ return pq[i - 1] < pq[j - 1] def _exch(pq, i, j): """ Exchanges the positions of items at index i and j on the heap. Indices are "off-by-one" to support 1-based indexing. :param pq: the heap :param i: index of the first item :param j: index of the second item """ pq[i-1], pq[j-1] = pq[j-1], pq[i-1] def _show(pq): """ Print the contents of the array :param pq: the array to be printed """ for i in range(len(pq)): print(pq[i]) def main(): """ Reads in a sequence of strings from stdin heapsorts them, and prints the result in ascending order. """ a = stdio.readAllStrings() sort(a) _show(a) if __name__ == '__main__': main()
true
0ecbbd7c74bffafc2b9270efbba0fb99ff2b2334
bhavyaagg/python-test
/algs4/sorting/merge.py
2,292
4.34375
4
# Created for BADS 2018 # See README.md for details # Python 3 """ This module provides functions for sorting an array using mergesort. For additional documentation, see Section 2.2 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. """ # Sorts a sequence of strings from standard input using mergesort def _is_sorted(a, lo=0, hi=None): # If hi is not specified, use whole array if hi is None: hi = len(a) # check if sublist is sorted for i in range(lo+1, hi): if a[i] < a[i-1]: return False return True # stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi] def _merge(a, aux, lo, mid, hi): # precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays assert _is_sorted(a, lo, mid) assert _is_sorted(a, mid+1, hi) # copy to aux[] for k in range(lo, hi+1): aux[k] = a[k] # merge back to a[] i, j = lo, mid+1 for k in range(lo, hi+1): if i > mid: a[k] = aux[j] j += 1 elif j > hi: a[k] = aux[i] i += 1 elif aux[j] < aux[i]: a[k] = aux[j] j += 1 else: a[k] = aux[i] i += 1 # postcondition: a[lo .. hi] is sorted assert _is_sorted(a, lo, hi) # mergesort a[lo..hi] using auxiliary array aux[lo..hi] def _sort(a, aux, lo, hi): if (hi <= lo): return mid = lo + (hi-lo)//2 _sort(a, aux, lo, mid) _sort(a, aux, mid+1, hi) _merge(a, aux, lo, mid, hi) def sort(a): """ Rearranges the array in ascending order, using the natural order. :param a: the array to be sorted """ aux = [None]*len(a) _sort(a, aux, 0, len(a)-1) assert _is_sorted(a) import sys from algs4.stdlib import stdio # Reads in a sequence of strings from standard input or a file # supplied as argument to the program; mergesorts them; # and prints them to standard output in ascending order. if __name__ == '__main__': if len(sys.argv) > 1: try: sys.stdin = open(sys.argv[1]) except IOError: print("File not found, using standard input instead") a = stdio.readAllStrings() sort(a) for elem in a: print(elem)
true