blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
eb4b36ee61f4541e2334038e366428a3b570d815
sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions
/ex7_2.py
1,030
4.1875
4
# Chapter 7 # Exercise 2: 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. # Enter the file name: mbox.txt # Average spam confidence: 0.894128046745 # Enter the file name: mbox-short.txt # Average spam confidence: 0.750718518519 count = 0 total = 0 fh = open('C:/Users/sandeep.kundala/Documents/python/mbox-short.txt') for line in fh: line = line.rstrip() if line.startswith('X-DSPAM-Confidence:'): count = count+1 atpos = line.find(':') total = total + float(line[atpos+1:]) else: continue avg = total/count print('Average spam confidence:', avg)
true
eee346b98c2726facf971db72ef2c5d6be0a7ee9
sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions
/ex8_4.py
472
4.3125
4
# Chapter 8 # Exercise 4: Write a program to open the file romeo.txt and read it line by line. For each line, # split the line into a list of words using the split function. # For each word, check to see if the word is already in a list. If the word is not in # the list, add it to the list. fh = input('Enter file: ') fopen = open(fh) word = [] for line in fopen: words = line.split() for s in words: word.append(s) word.sort() print(word)
true
697a943b2cceb74f2503fd1130bd3fa263ff57cf
Robbot/Teclado
/The Complete Python/Section1/main.py
1,533
4.28125
4
# Coding exercise 2 name = input("What is your name? ") print(f"Hello, {name}") age = int(input("What is your age? ")) print(f"You are {age*12} months old") # Coding exercise 3 nearby_people = {'Rolf', 'Jen', 'Anna'} user_friends = set() #This is an empty set friend = input("What is the name of your friend? ") user_friends.add(friend) print(nearby_people.intersection(user_friends)) #Coding exercise 4 lottery_numbers = {13, 21, 22, 5, 8} """ A player looks like this: { 'name': 'PLAYER_NAME', 'numbers': {1, 2, 3, 4, 5} } Define a list with two players (you can come up with their names and numbers). """ players = [ { 'name': 'Rob', 'numbers': {5,6,10,12,21,22} }, { 'name': 'Rolf', 'numbers': {5,10,13,21,22,48} } ] """ For each of the two players, print out a string like this: "Player PLAYER_NAME got 3 numbers right.". Of course, replace PLAYER_NAME by their name, and the 3 by the amount of numbers they matched with lottery_numbers. You'll have to access each player's name and numbers, and calculate the intersection of their numbers with lottery_numbers. Then construct a string and print it out. Remember: the string must contain the player's name and the amount of numbers they got right! """ won1 = (len((players[0]['numbers']).intersection(lottery_numbers))) print(f"Player {players[0]['name']} got {won1} numbers right. ") won2 = (len((players[1]['numbers']).intersection(lottery_numbers))) print(f"Player {players[1]['name']} got {won2} numbers right. ")
true
d5b582a3938073bfb5355322b4fe492b41de1d73
johnahnz0rs/CodingDojoAssignments
/python/python_fundamentals/scores_and_grades.py
829
4.3125
4
# Write a function that generates ten scores between 60 and 100. Each time a score is generated, your function should display what the grade is for a particular score. Here is the grade table: # Score: 60 - 69; Grade - D # Score: 70 - 79; Grade - C # Score: 80 - 89; Grade - B # Score: 90 - 100; Grade - A def scores_and_grades(): import random print "Scores and Grades" for x in range(0,10): temp = random.randint(60, 100) print "Score: " + str(temp) + "; Your grade is " + find_grade(temp) print "End of the program. Bye!" return # enter a number score, get a letter grade def find_grade(score): if score >= 60 and score <=69: return 'D' elif score >= 70 and score <= 79: return 'C' elif score >= 80 and score <= 89: return 'B' elif score >= 90 and score <= 100: return 'A' # scores_and_grades()
true
30ef3b36e9f9dddbf5526b068c1451796e78da89
nd-cse-34872-su21/cse-34872-su21-examples
/lecture02/cheatsheet.py
366
4.25
4
#!/usr/bin/env python3 v = [1, 2, 3] # Create dynamic array v.append(4) # Append to back of array v.insert(0, 0) # Prepend to front of array print(len(v)) # Display number of elements for e in v: # Traverse elements print(e) # Traverse elements with index for i, e in enumerate(v): print(f'{i}: {e}')
true
f1705276ec52154591de27009366f0e8c5e278be
anejaprerna19/LearninPython
/passwordchecker.py
396
4.25
4
#Password Checker Assignment from Udemy Course #In this simple assignment, we take user inputs for username and password and then calculate and print the length of password. username= input("What is your username? "); password= input("Enter the password "); pass_length= len(password) hidden_pass= '*' * pass_length print(f'{username}, your password {hidden_pass} is {pass_length} letters long ')
true
839764c040251100e370a5b0f24b8c3e8044961f
dhitalsangharsha/GroupA-Baic
/question5.py
204
4.125
4
'''5) Take an arbitrary input string from user and print it 10 times.''' string=input("enter a string:") print("\nprinting {} 10 times ".format(string)) for i in range(1,11): print(str(i)+':',string)
true
fc46ee5a3d68857277ffca31aa3925943c139988
irffanasiff/100-days-of-python
/day5/range.py
382
4.1875
4
# for number in range(1, 10, 3): # print(number) # total = 0 # for number in range (1, 101): # total += number # print(total) #! sum of all the even numbers from 1 to 100 total =0 for number in range(0,101,2): total += number print(total) #? or total =0 for number in range (1,101): if number%2==0: total+= number else: total+=0 print(total)
true
68ceeb0a35ee5de2f89d64d842496f112689b9ed
florinbrd/PY--
/python developer zero to mastery/Practice Exercises - pynative.com/Basic Exercises/Exercise10.py
509
4.15625
4
# Question 10: Given a two list of ints create a third list such that should contain only odd numbers from the first list and even numbers from the second list def odd_list(list1, list2): list3 = [] for item1 in list1: if item1 % 2 == 0: list3.append(item1) for item2 in list2: if item2 % 2 == 0: list3.append(item2) return list3 work_list1 = [1, 2, 3, 4, 5, 6, 7, 8] work_list2 = [10, 11, 12, 13, 14, 15] print(odd_list(work_list1, work_list2))
true
5d2ac7e730a592f9063af6ae5366608611060c67
florinbrd/PY--
/python developer zero to mastery/Practice Exercises - pynative.com/Basic Exercises/Exercise02.py
398
4.3125
4
# Question 3: Accept string from the user and display only those characters which are present at an even index def even_char(string_defined): print(f'Your original string is: {string_defined}') for item in range(0, len(string_defined)-1, 2): if item % 2 == 0: print("index[", item,"]", string_defined[item] ) word = str(input('Enter your string: ')) even_char(word)
true
77f65fd43bd51bc8ae2c59c8342d5798ab8513c0
rgion/Python-P6
/P6E1.py
394
4.25
4
#P6 E1 - rgion #Escribe un programa que te pida palabras y las guarde en una lista. #Para terminar de introducir palabras, simplemente pulsa Enter. #El programa termina escribiendo la lista de palabras. palabra=input("Escribe una palabra: ") lista=[] while (palabra!=""): lista.append(palabra) palabra=input("Escribe más palabras: ") print("Las palabras que has escrito son: ",lista)
false
8ba15361440b980c27bdc1ddd6c35a554af4f28e
rgion/Python-P6
/P6E11.py
923
4.21875
4
#P6 E11 - rgion #Escribir un programa para jugar a adivinar un número #(el ordenador "piensa" el número y el usuario lo ha de adivinar). #El programa empieza pidiendo entre qué números está el número #a adivinar, se "inventa" un número al azar y luego el usuario #va probando valores. El programa va decidiendo si son demasiado #grandes o pequeños. pista: import random minimo=int(input("Valor mínimo:")) maximo=int(input("Valor máximo:")) intentos=0 secreto=random.randint(minimo,maximo) print("A ver si adivinas un número entero entre",minimo,"y",maximo) numero=int(input("Escribe un número: ")) while (numero!=secreto): while (numero<secreto): numero=int(input("¡Demasiado pequeño! Vuelve a probar: ")) intentos+=1 while (numero>secreto): numero=int(input("¡Demasiado grande! Vuelve a probar: ")) intentos+=1 print("¡Correcto! Lo has intentado",intentos,"veces.")
false
c55de30866091747d5fcac35734d4c38d0e8154b
khuang7/python3_thehardway
/ex18.py
413
4.125
4
def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}. arg2: {arg2}") #*args is actually pointless we can just do def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") # this just takes one argument def print_one(arg1): print(f"arg1: {arg1}") def print_none(): print("I got nothin") print_two("Kevin", "Huang") print_two_again("Kevin", "Huang") print_one("First!") print_none()
false
0669fa9486066c0a53b54f782a5f9d4d0e816264
shashaank-shankar/OFS-Intern-2019
/Python Exercises/Condition Statements and Loops/Exercise 1.py
341
4.25
4
# Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included). input = int(input("Enter a number: ")) if input >= 1500 and input <= 2700: if input%7 == 0: if input%5 == 0: print(input + " is between 1500 and 2700. It is also divisable by 7 and 5.")
true
11f50308cb6450ee304af690d61f072c70924277
shashaank-shankar/OFS-Intern-2019
/Python Exercises/Condition Statements and Loops/Exercise 2.py
1,088
4.5
4
# Write a Python program to convert temperatures to and from celsius, fahrenheit. print("\nThis program converts Celsius and Farenheit temperatures.") def tempConvert (type): if type == "C": # convert to C new_temp = (temp_input - 32) * (5/9) new_temp = round(new_temp, 2) print("\n" + str(temp_input) + "F is equal to " + str(new_temp) + "C.") elif type == "F": # convert to F new_temp = (temp_input * (9/5)) + 32 new_temp = round(new_temp, 2) print("\n" + str(temp_input) + "C is equal to " + str(new_temp) + "F.") # repeats until 'C' or 'F' is entered while True: type_input = input("\nEnter 'C' to convert to Celsius\nEnter 'F' to convert to Farenheit\nEnter 'E' to Exit: ") type_input = type_input.upper() if type_input == "C": temp_input = float(input("\nEnter a temperature in Farenheit: ")) tempConvert("C") elif type_input == "F": temp_input = float(input("\nEnter a temperature in Celsius: ")) tempConvert("F") elif type_input == "E": break
true
54518c4f1dcd313da6458e664f7f8c1fa2b95b5c
Susama91/Project
/W3Source/List/list10.py
273
4.21875
4
#Write a Python program to find the list of words that are longer than n #from a given list of words. def lword(str1,n): x=[] txt=str1.split() for i in txt: if len(i)>n: x.append(i) print(x) lword('python is a open',2)
true
d1573d6ad748eaceb5747f80a42477914ece741b
ItsPepperpot/dice-simulator
/main.py
644
4.1875
4
# Dice rolling simulator. # Made by Oliver Bevan in July 2019. import random def roll_die(number_of_sides): return random.randint(1, number_of_sides) print("Welcome! How many dice would you like to roll?") number_of_dice = int(input()) # TODO: Add type checking. print("Okay, and how many sides would you like the dice to have?") number_of_sides_on_die = int(input()) print(f"You roll {number_of_dice} dice. They read:") sum_of_dice_values = 0 for i in range(0, number_of_dice): die_value = roll_die(number_of_sides_on_die) sum_of_dice_values += die_value print(die_value, end=" ") print(f"\nThey sum to {sum_of_dice_values}.")
true
1f4d2489bcfa31d9c1d3b2e82828c1533fac81d2
MarvvanPal/foundations-sample-website
/covid_full_stack_app/covid_full_stack_app/controllers/database_helpers.py
2,107
4.65625
5
# connect to the database and run some SQL # import the python library for SQLite import sqlite3 # this function will connect you to the database. It will return a tuple # with two elements: # - a "connection" object, which will be necessary to later close the database # - a "cursor" object, which will neccesary to run SQL queries. # This function is like opening a file for reading and writing. # this function takes one argument, a string, the path to a database file. def connect_to_database(database_filename): # connect to the database file, and create a connection object try: db_connection = sqlite3.connect(database_filename) except sqlite3.DatabaseError: print("Error while connecting to database file {filename}".format( filename=database_filename)) # create a database cursor object, neccesary to use SQL db_cursor = db_connection.cursor() return db_connection, db_cursor # close the connection to the database, like closing a file. def close_conection_to_database(db_connection): db_connection.close() return # This function will change either the structure or contents of your database. # This expects SQL commands like "CREATE" or "INSERT" def change_database(db_connection, db_cursor, sql_command): try: db_cursor.execute(sql_command) except sqlite3.DatabaseError: print("tried to execute the folllwing SQL, but failed:", sql_command) # commit changes - like with git. db_connection.commit() return # this function will run any SQL query and return a list of tuples, # where each tuple represents a row in the database. # the intent here is to use this for seeing what is inside the database. # SQL commands like "SELECT" are expected here def query_database(db_cursor, sql_query): try: db_cursor.execute(sql_query) except sqlite3.DatabaseError: print("tried to execute the folllwing SQL, but failed:", sql_query) # list of tuples, where each tuple represents a row in the database query_response = db_cursor.fetchall() return query_response
true
7e603d0a3d96c50104630187b700ccab8cf035d7
hemang249/py-cheatsheet
/conditions.py
479
4.15625
4
# Common Conditional Statements used in Python 3 # Basic if-else Condition x = 5 if x == 5: print("x = 5") else: print("x != 5") # Basic Logical operations # and or not a = 0 b = 1 boolean = False if a == 0 and b == 1: print("a = 0 and b = 1") if a == 0 or b == 1: print("Either a = 0 or b = 1") if not boolean : print(boolean) # elif statements x = 1 if x == 1: print("x = 1") elif x == 2: print("x = 2") elif x == 3: print("x = 3")
true
6dea2f8d8f2ae2804961d80bc0c224a174d4694b
zihu/job_interview_code
/lcs.py
866
4.1875
4
#!/usr/bin/python def lcs(xs, ys): '''Return a longest common subsequence of xs and ys. Example >>> lcs("HUMAN", "CHIMPANZEE") ['H', 'M', 'A', 'N'] ''' if xs and ys: xb = xs[:-1] yb = ys[:-1] if xs[-1] == ys[-1]: return lcs(xb, yb) + [xs[-1]] else: return max(lcs(xs, yb), lcs(xb, ys), key=len) else: return [] def lcs_len(x, y): """This function returns length of longest common sequence of x and y.""" if len(x) == 0 or len(y) == 0: return 0 xx = x[:-1] # xx = sequence x without its last element yy = y[:-1] if x[-1] == y[-1]: # if last elements of x and y are equal return lcs_len(xx, yy) + 1 else: return max(lcs_len(xx, y), lcs_len(x, yy)) if __name__ == '__main__': s1="hemllyoname" s2="whatisyournamehello" #n=lcs_len(s1, s2) #print n print lcs(s1, s2)
false
8ad114e4e5f63a56c8d560f60d05e19dcd77ee42
KimberleyLawrence/python
/for_loop_even_numbers.py
245
4.1875
4
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] for number in a: # % 2 == 0 is dividing the number by 2, and seeing if there is any remainders, any remainders mean that the number is not even. if number % 2 == 0: print number
true
efd2607c2b56baeb6866395321d6e2c5906c8b9b
lucasarieiv/Livro-Exercicio-Python
/collatz.py
352
4.15625
4
def collatz(number): if number % 2 == 0: v1 = number // 2 print(v1) return v1 elif number % 2 == 1: v2 = 3 * number + 1 print(v2) return v2 print('Enter number. ') num = input() try: collatz(int(num)) except ValueError: print('Enter an Integer Value ')
false
37e9fa37ff5e6cc968b0031e802538c1c902ad9c
Kristy16s/Think-Python-2-Exercises-By-Chapter
/2.1 Exercises.py
1,285
4.4375
4
# 2.10 Exercises # Date 8/4/2021 """ Exercise 1 Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong. """ # We’ve seen that n = 42 is legal. What about 42 = n? # 42 = n """ File "<input>", line 1 42 = n ^ SyntaxError: cannot assign to literal # Obviously, we can't assign numbers to a literal """ # How about x = y = 1? x = y = 1 print("x = ", x) print("y = ", y) """ x = 1 y = 1 """ # In some languages every statement ends with a semi-colon, ;. What happens if # you put a semi-colon at the end of a Python statement? print("testing"); """ testing # the solution has no difference, but Python doesn't need it """ # What if you put a period at the end of a statement? # print("testing"). """ print("testing"). ^ SyntaxError: invalid syntax # We can't add a period at the end of a statement. # period or the dot allows you to choose the suggested methods (functions) and properties (data) of objects. """ # In math notation you can multiply x and y like this: x y. What happens if # you try that in Python? x = y = 1 print(xy) """ print(xy) NameError: name 'xy' is not defined # We must put * between x and y. """
true
41228a26ab53da47dabc59d4d0414c23e806d902
shanksms/python_cookbook
/iterators-generators/generator-examples.py
1,272
4.6875
5
""" Here’s a generator that produces a range of floating-point numbers. Below function returns a generator object. A generator object is also an iterator. an Iterator is an Iterable. That is why you can use it in while loop. """ def frange(start, stop, increment): i = start while i < stop: yield i i += increment ''' The mere presence of the yield statement in a function turns it into a generator. Unlike a normal function, a generator only runs in response to iteration. Here’s an experiment you can try to see the underlying mechanics of how such a function works: ''' def countdown(n): print('Starting to count from n') while n > 0: yield n n -= 1 print('Done') if __name__ == '__main__': for x in frange(0, 4, 0.5): print(x) """ The key feature is that a generator function only runs in response to "next" operations carried out in iteration. Once a generator function returns, iteration stops. However, the for statement that’s usually used to iterate takes care of these details, so you don’t normally need to worry about them. """ c = countdown(3) print('printing c', c) print(next(c)) print(next(c)) print(next(c)) print(next(c))
true
40a0f176eba2fed30a0c5ed96d9ee6fbe654a70a
ssummun54/wofford_cosc_projects
/Assignments/8and10.py
1,719
4.15625
4
# 8and10.py # This progam runs two functions. The first function uss Newton's Method to find the # square root of a number. The second function creates an acronym based on the phrase # given by the user. #importing math for square root from math import * #function for problem 8 def nextGuess(guess, newton): #(this is from runProblem8(someNumber, times) #starts guess estimate = guess/2 # looping for starting with one and ending with the actual number the user input for i in range (1, newton + 1): estimate = (estimate + (guess / estimate))/2 return estimate #function for problem 10 def acronym(phrase): #splitting phrase phrase = phrase.split() #new string where the letters will concactenate newString = "" for firstLetter in phrase: newString = newString + firstLetter[0].upper() return newString #calls for problem 8 work def runProblem8(): #inputs someNumber = eval(input("Please enter a number: ")) times = eval(input("How many times do you wish to run Newton's Method? ")) #difference difference = round(float(sqrt(someNumber)) - round(nextGuess(someNumber, times), 10),14) #results print("The estimated square root of", someNumber, "is", round(nextGuess(someNumber, times), 10), "which has an error of", float(abs(difference))) def runProblem10(): phrase = input("Please enter a phrase: ") print("The acronym for your phrase is", acronym(phrase)) def main(): print("Running Program 1 (Problem 8)...") runProblem8() print("Running Program 2(Problem 10)...") runProblem10() main()
true
d92640d7336759a48656c7df4bd333ceecca69aa
ssummun54/wofford_cosc_projects
/Assignments/numerology.py
615
4.4375
4
# numerology.py # This program sums up the Unicode values of the user's full name and displays the corresponding Unicode character # A program by Sergio Sum # 3/24/17 def main(): name = input("Please enter your full name: ") # not counting spaces by turning to list name = name.split() #joining list name = "".join(name) # accumulator counter = 0 # getting unicode values for for values in name: counter = counter + ord(values) print("Your value is:", counter) print("The Unicode character for your value is:", chr(counter)) main()
true
3ed869277d2d7958bc4d4012434c826f03e88eaf
dexterchan/DailyChallenge
/MAR2020/ScheduleTasks.py
648
4.1875
4
#A task is a some work to be done which can be assumed takes 1 unit of time. # Between the same type of tasks you must take at least n units of time before running the same tasks again. #Given a list of tasks (each task will be represented by a string), # and a positive integer n representing the time it takes to run the same task again, # find the minimum amount of time needed to run all tasks. #Here's an example and some starter code: def schedule_tasks(tasks, n): # Fill this in. print(schedule_tasks(['q', 'q', 's', 'q', 'w', 'w'], 4)) # print 6 # one of the possible orders to run the task would be # 'q', 'w', idle, idle, 'q', 'w'
true
d6d4cc0dae2f1a1fc7a650798ee6dad83d6b57ed
dexterchan/DailyChallenge
/NOV2019/WordSearch.py
2,069
4.15625
4
#skills: array traversal #You are given a 2D array of characters, and a target string. Return whether or not the word target word exists in the matrix. # Unlike a standard word search, the word must be either going left-to-right, or top-to-bottom in the matrix. #Example: #[['F', 'A', 'C', 'I'], # ['O', 'B', 'Q', 'P'], # ['A', 'N', 'O', 'B'], # ['M', 'A', 'S', 'S']] #Given this matrix, and the target word FOAM, you should return true, as it can be found going up-to-down in the first column. class Solution: def findWord(self, matrix, word): numrow = len(matrix) numcol = len(matrix[0]) wordlen = len(word) for i in range(0, numrow): for j in range(0, numcol): chkL2R = self.__checkL2R(i, j, matrix, word, numrow, numcol) chkU2D = self.__checkU2D(i, j, matrix, word, numrow, numcol) if(chkL2R or chkU2D): return True return False def __checkL2R(self, x, y, matrix, word, numrow, numcol): #check if reach boundary element = [] if(y+len(word)>numcol): return False for i in range(len(word)): element.append(matrix[x][y+i]) strRef = "".join(element) if(strRef == word): return True else: return False def __checkU2D(self, x, y, matrix, word, numrow, numcol): # check if reach boundary element = [] if (x + len(word) > numrow): return False for i in range(len(word)): element.append(matrix[x+i][y]) strRef = "".join(element) if (strRef == word): return True else: return False def word_search(matrix, word): solu = Solution() return solu.findWord(matrix, word) if __name__ == "__main__": matrix = [ ['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S']] print (word_search(matrix, 'FOAM') ) # True print(word_search(matrix, 'BSl'))
true
e76e31b3bce987ce0ed9b4a39f29ad6eb1221d92
dexterchan/DailyChallenge
/MAR2020/FilterBinaryTreeLeaves.py
2,112
4.15625
4
#Hi, here's your problem today. This problem was recently asked by Twitter: #Given a binary tree and an integer k, filter the binary tree such that its leaves don't contain the value k. Here are the rules: #- If a leaf node has a value of k, remove it. #- If a parent node has a value of k, and all of its children are removed, remove it. #Here's an example and some starter code: #Analysis #dfs to the leaf with recursive function: func(node) -> boolean # if leaf value is k, return true else false # if non leaf node # check return value of recursive function.... if yes, remove that child # if all children removed, and its value is k, # return true to its caller # else return false # Time complexity O(N) Space complexity O(N) --- memory stack usage when doing recursion class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def __repr__(self): return f"value: {self.value}, left: ({self.left.__repr__()}), right: ({self.right.__repr__()})" class Solution(): def filter_recursive(self, node:Node,k:int)->bool: if node.left is None and node.right is None: return node.value == k leftRet = True rightRet = True if node.left is not None: leftRet = self.filter_recursive(node.left, k) if node.right is not None: rightRet = self.filter_recursive(node.right, k) if leftRet: node.left = None if rightRet: node.right = None return leftRet and rightRet and node.value==k def filter(tree, k): # Fill this in. solu = Solution() solu.filter_recursive(tree, k) return tree if __name__ == "__main__": # 1 # / \ # 1 1 # / / # 2 1 n5 = Node(2) n4 = Node(1) n3 = Node(1, n4) n2 = Node(1, n5) n1 = Node(1, n2, n3) print(str(filter(n1, 1))) # 1 # / # 1 # / # 2 # value: 1, left: (value: 1, left: (value: 2, left: (None), right: (None)), right: (None)), right: (None)
true
54d303d49e8e260e78b3509e332bbe733fb081ff
Liambass/Python-challenges-exercises-and-tutorials
/Exercises/intfloat.py
590
4.1875
4
# Integers and Floats # number1 = input("Enter whole number: ") # number2 = input("Enter decimal number: ") # integer_number = int(number1) # float_number = float(number2) # round_number = int(round(float_number)) # print(number1) # print(number2) # print(round_number) # What will be the output of this code? number1 = input("Enter whole number: ") #12 number2 = input("Enter decimal number: ") #12.53 integer_number = int(number1) float_number = float(number2) round_number = int(round(float_number)) print(number1) #12 print(number2) #12.53 print(round_number) #13
false
2ea7d16b392e87f58bb97d39e40df65120963c28
JoseCintra/MathAlgorithms
/Algorithms/MatrixDeterminant.py
2,070
4.46875
4
""" Math Algorithms Name: MatrixDeterminant.py Purpose: Calculating the determinant of 3x3 matrices by the Sarrus rule Language: Python Author: José Cintra Year: 2021 Web Site: https://github.com/JoseCintra/MathAlgorithms License: Unlicense, described in http://unlicense.org Online demo: https://onlinegdb.com/ByWG_1BUd Notes: 1) This algorithm is available without guarantees and must be tested before being made available in production environments 2) The data entry is fixed in the body of the algorithm, but can be changed by the user, if necessary 3) The input values are not being validated according to the allowed range !!! This is up to the user 4) The output data is being displayed without a concern for formatting 5) The goal here is just to highlight the solution of the problem through the algorithm stripped of any paradigm, with the hope that it will be useful to students in the field """ # Defining the matrix 3x3 # Change this to perform calculations with other matrices a = [ [3, 1, 2], [0, 2, 0], [0, 4, 1] ] det = 0 # Determinant r = 0 # Current line of the matrix in the loop c = 0 # Current row of the matrix in the loop l = len(a) - 1 # Lenght of Matrix (index) # Calculating the determinant of the matrix print("Matrix determinant\n") for i in range(len(a)): prod = 1 r = 0 c = i for j in range(len(a)): prod = prod * a[r][c] r = r + 1 c = c + 1 if (c > l): c = 0 det = det + prod r = 0 c = l for i in range(len(a)): prod = -1 r = 0 for j in range(len(a)): prod = prod * a[r][c] r = r + 1 c = c - 1 if (c < 0): c = l c = i det = det + prod # print results print("Matrix A:") for row in range(len(a)): for col in range(len(a[row])): print(a[row][col], end='') print(" ", end='') print("") print("\nDeterminant of the matrix A:", det)
true
7e58a06e5ad508b8d888218256f00a309bdbcd40
XuuRee/python-codecademy
/Unit 00/factorial_p3_mysol.py
331
4.15625
4
# factorial program using Python (my own solution) print("Factorial using Python 3 (my own solution)\n") number = eval(input("Enter a non-negative integer for factorial: ")) factorial = 1 for i in range(1,number + 1): # druha pozice = zadane cislo + jedna factorial = factorial * i print("Result: ",factorial)
false
c2ffdddf292da3a4fb5e7a66b27b664e52dadd48
pzavisliak/Python
/Circle/Math.py
1,376
4.125
4
import math print("Вычисление длины круга") def bugsa(): if a != "R" or a != "D": print("Нужно было ввести R или D , в следуйщий раз читай внимательнее") exit() a = input("С помощью чего ты хочешь найти длину? Радиус - R, Диаметр - D\n") bugsa() rad = "" diam = "" def bugsradius(): if rad <= str(0): print("Число не может быть меньше или равно нулю, ничего не значить, а также оно не должно быть буквой!\n\n") exit() else: return def bugsdiametr(): if diam <= str(0): print("Число не может быть меньше или равно нулю, ничего не значить, а также оно не должно быть буквой!\n\n") exit() else: return if a == "R": rad = input("Введите радиус: ") bugsradius() radius = (float(2) * math.pi * float(rad)) okr = round(radius, 2) print("Длина круга равна: " + str(okr)) elif a == "D": diam = input("Введите диаметр: ") bugsdiametr() diametr = (float(diam) * math.pi) okr = round(diametr, 2) print("Длина круга равна: " + str(okr))
false
1e38cb2f374eede29eaf6520bfb1f97d84a10f6c
TolpaBomjey/GB.Python.HW
/HW2/task2-1.py
558
4.3125
4
# Создать список и заполнить его элементами различных типов данных. # Реализовать скрипт проверки типа данных каждого элемента. # Использовать функцию type() для проверки типа. Элементы списка # можно не запрашивать у пользователя, а указать явно, в программе. someList = ["раз", 2, None, 3.14] for smth in someList: print(type(smth))
false
36f42da49b3aa743cee7722bf0def14fda5c167b
TolpaBomjey/GB.Python.HW
/HW2/task2-4.py
558
4.125
4
# Пользователь вводит строку из нескольких слов, разделённых пробелами. # Вывести каждое слово с новой строки. Строки необходимо пронумеровать. # Если в слово длинное, выводить только первые 10 букв в слове. userFrase = input("Давай вещай. Слова через пробел >>>") words = list(userFrase.split(" ")) for w, el in enumerate(words, 1): print(w, el[0:10])
false
a893cd5e53c840925e54c60af40514bb8fa51d07
mansoniakki/PY
/Reverse_Input_String.py
412
4.40625
4
print("##################This script with reverse the string input by user###########") name=input("Please enter first and last name to reverse: ") print("name: ", name) words=name.split() print("words: ", words) for word in words: lastindex = len(word) -1 print("lastindex ", lastindex) for index in range(lastindex, -1, -1): print(word[index], end='') print(end= ' ') print(end='\n')
true
63582443b16149b97f551b6a9f80845fa8b60a30
rbenf27/dmaimcoolshek6969
/PYTHON/COLOR GUESSER.py
530
4.125
4
import random color = random.randint(1,7) if color == 1: color = "yellow" if color == 2: color = "green" if color == 3: color = "orange" if color == 4: color = "blue" if color == 5: color = "red" if color == 6: color = "purple" user_choice = input("Choose a color from the rainbow...so think about those 6 colors, ONLY!!") if user_choice == color: print("good job! you guessed correctly") else: print("THE COMPUTER THOUGHT OF SOMETHING DIFFERENT, SORRY....")
true
fc7e5ec06d19b9a4a1398798f589c0982331c192
meloning/pythonSyntaxEx
/chapter9/ObjectEx.py
652
4.15625
4
class BookReader: __country = 'South Korea' def __init__(self, name): self.name = name def read_book(self): print(self.name +' is reading Book!!') def set_country(self, country): self.__country = country def get_country(self): return self.__country reader = BookReader('Chris') reader.read_book() print(dir(reader)) # Class 내 __속성명 -> private (이름 장식) br = BookReader('Junsu') print(br.get_country()) br.set_country('Korean') print(br.get_country()) # Inheritance 상속/ Multiple Inheritance 다중 상속 허용 # Polymorphism 다형성 # super().method_name() 부모꺼접근
false
f31a9a0fe3a3642263c05c365dffa4db220de581
rbrown540/Python_Programs
/Calculate.py
2,967
4.40625
4
# Richard Brown - SDEV 300 # March 16, 2020 # Lab_One - This program prompts the user to select a math function, # then performs that function on two integers values entered by the user. print ('\nWelcome to this awesome Python coded calculator\n') # provide user with the math function options print ('Select 1 for ADDITION ( + )') print ('Select 2 for SUBTRACTION ( - )') print ('Select 3 for DIVISION ( / )') print ('Select 4 for MULTIPLICATION ( * )') print ('Select 5 for MODULUS ( % )') # prompt user for selection userSelection = int(input('\nPlease make your selection: ')) userInputOne = int(input('\t>> Please provide the first integer value: ')) userInputTwo = int(input('\t>> Please provide the second integer value: ')) # determine which selection the user chose, and then execute the math function # on the set of integers input by the user # Selection 1 if userSelection == 1: print ('\nYou have chosen to ADD the two values:', userInputOne, 'and', userInputTwo) userAdditionAnswer = userInputOne + userInputTwo print ('\nThe sum of those two integers is:', userAdditionAnswer) # Selection 2 if userSelection == 2: print ('\nYou have chosen to SUBTRACT the two values', userInputOne, 'and', userInputTwo) userSubtractionAnswer = userInputOne - userInputTwo print ('\nThe difference of those two integers is: ', userSubtractionAnswer) # Selection 3 if userSelection == 3: print ('\nYou have chosen to DIVIDE the two values: ', userInputOne, 'and', userInputTwo) # alert to user that the value entered is not valid # and then re-prompts for valid value if userInputTwo <= 0: userInputTwo = int(input('\nThis program is unable to divide by zero ' 'or negative numbers,\nPlease select a non-zero' ' positive integer value: ')) userDivisionAnswer = userInputOne / userInputTwo print ('\nThe quotient of those two integers is: ', int(userDivisionAnswer)) # Selection 4 if userSelection == 4: print ('\nYou have chosen to MULTIPLE the values: ', userInputOne, 'and', userInputTwo) userMultiplicationAnswer = userInputOne * userInputTwo print ('\nThe product of those two integers is: ', userMultiplicationAnswer) # Selection 5 if userSelection == 5: print ('\nYou have chosen to find the REMAINDER of: ', userInputOne, 'and', userInputTwo) # alert to user that the value entered is not valid # and re-prompts for valid value if userInputTwo <= 0: userInputTwo = int(input('\nThis program is unable to divide by zero ' 'or negative numbers,\nPlease select a non-zero' ' positive integer value: ')) userModulusAnswer = userInputOne % userInputTwo print ('\nThe remained of those to two integers is: ', userModulusAnswer) # saying good-bye print ('\nThank you for using this awesome Python programmed calculator')
true
f366a69f898f1bc46e0495605878eefb3dcb438e
richa18b/Python
/oops.py
2,829
4.15625
4
import random import sys import os class Animal : _name = None #this is equivalent to __name = "" _height = 0 #_ means that it is a private variable _weight = 0 _sound = "" #constructor def __init__(self,name,height,weight,sound): self._name = name self._height = height self._weight = weight self._sound = sound #Getters and Setters for all attributes def get_name(self): print(self._name) def set_name(self, name): self._name = name def get_height(self): print(self._height) def set_height(self, height): self._height = height def get_weight(self): print(self._weight) def set_weight(self, weight): self._weight = weight def get_sound(self): print(self._sound) def set_sound(self, sound): self._sound = sound def get_type(self): print('Animal') def toString(self): return "{} is {} cms tall, {} kgs in weight and says {}".format(self._name, self._height, self._weight, self._sound) cat = Animal('Cat',33,10,'Meoww') print(cat.toString()) #Inheritance class Dog(Animal): _owner = "" def __init__(self,name,height,weight,sound,owner): self._owner = owner super(Dog,self).__init__(name,height,weight,sound) def set_owner(self,owner): self._owner = owner def get_owner(self): return self._owner def get_type(self): print('Dog') #Overriding the function that's in the super class def toString(self): return "{} is {} cms tall, {} kgs in weight and says {}. His owner is {}".format(self._name, self._height, self._weight, self._sound, self._owner) #Performing method overloading def multiple_sounds(self,how_many = None): #A way of saying that we do not require attributes to be passed in our function if how_many is None : print(self.get_sound()) else : print(self.get_sound() * how_many) spot = Dog("Spot",53,27,"Ruff","Ash") print(spot.toString()) #Polymorphism class AnimalTesting : def get_type(self,animal) : animal.get_type() test_animals = AnimalTesting() test_animals.get_type(cat) test_animals.get_type(spot)
true
7d6e9b19d7f2ba2da75911fc61a300d39cf1857f
kunlee1111/oop-fundamentals-kunlee1111
/Coin.py
1,790
4.21875
4
""" ------------------------------------------------------------------------------------------------------------------------ Name: Coin.py Purpose: Simulates 1000 flips of a coin, and tracks total count of heads and tails. Author: Lee.K Created: 2018/11/30 ------------------------------------------------------------------------------------------------------------------------ """ import random class Coin(): """ Class that contains three functions: intialization method, returns the value of the face. sets the value of face. """ def __init__(self): #initialization method self.face = 'heads' #Heads on top initially def get_face(self): """ returns the value of the face attribute :return: String (heads or tails) """ return self.face def flip(self): """ randonly sets the value of the face attributes to heads ot tails :return: String (heads or tails) """ return str(random.choice(["heads", "tails"])) if __name__ == '__main__': #simulates 1000 flips of a coin, keeping track of total count of heads and tails. a = 0 #iteration variable total_Heads = 0 #total numer of Heads total_Tails = 0 #total number of Tails coin = Coin() #class coin variable while a <= 1000: coin.flip() #for 1000 times, coin is flipped. a += 1 #increase in iteration if coin.get_face() == 'heads': #if coin flipped is heads, total Heads increase by one total_Heads += 1 else: #if coin flipped is tails, total tails increase by one total_Tails += 1 print ("Total Heads Count is"+ total_Heads + "Total Tails Count is"+ total_Tails) #print the output
true
df25914cc08c600e8d1e8b80f4e027dbb7640c09
kaurmandeep007/daily-diary
/dictionary.py
868
4.25
4
dict={ "brand":"ford", "model":"mustang", "year":1964 } print(dict) #acess items: x=dict["model"] x=dict.get("model") print(x) #change values: dict["year"]=2014 print(dict) #loop through a dictionary: for x in dict: print(x) #if key exists: if "brand" in dict: print("yes,'brand' is one of the keys in dict dictionary") #dictionary length: print(len(dict)) #add items: dict["color"]="red" print(dict) #remove items: dict.pop("year") print(dict) #copy a dictionary: mydict=dict.copy() print(mydict) #nested dictionaries: myfamily={ "child1":{ "name":"emil", "year":"2004" }, "child2":{ "name":"tobias", "year":"2001" }, "child3":{ "name":"limra", "year":"1998" } } print(myfamily) for x in myfamily: print(x)
false
d64728f99b0089fbca68bdef03db6982d570d8d4
gingij4/Forritun
/bmistudull.py
560
4.53125
5
weight_str = input("Weight (kg): ") # do not change this line height_str = input("Height (cm): ") # do not change this line height_float = (float(height_str) / 100) weight_float = float(weight_str) bmi = (weight_float / (height_float)**2) print("BMI is: ", bmi) # do not change this line #BMI is a number calculated from a person's weight and height. The formula for BMI is: #weight / height2 #where weight is in kilograms and heights is in meters #Write a program that prompts for weight in kilograms and height in centimeters and outputs the BMI.
true
9036deafb3980f8f986cdd902fab447f91c55c32
danielle8farias-zz/hello-world-python3
/meus_modulos/numeros.py
2,770
4.28125
4
######## # autora: danielle8farias@gmail.com # repositório: https://github.com/danielle8farias # Descrição: Funções para: # validar número float; # validar número inteiro; # validar o divisor da operação de divisão; # validar índice de raízes; # validar números naturais; ######## def ler_num_float(n): ''' Validação todo o conjuntos dos números reais ''' while True: try: num = float(input(n)) except ValueError: print('Digite um valor válido!') continue else: return num def ler_num_int(n): ''' Valida números inteiros positivos ou negativos. ''' #laço while True: try: #input() captura como string o que for digitado #int() convertendo a string recebida para tipo inteiro #atribuindo valor à variável 'num' num = int(input(n)) #criando exceção # caso o valor digitado seja diferente de um número except ValueError: #print() retorna uma string na tela print('Digite um número inteiro!') #volta para o início do laço continue #se o 'try' for válido else: #retorna valor de mes return num def ler_divisor(n): while True: ''' Valida divisor. Não aceita zero. ''' try: num = float(input(n)) if num == 0: raise Exception('Não é possível dividir por 0.') except ValueError: print('Digite um número.') continue except Exception as erro: print(f'Valor inválido: {erro}') continue else: return num def ler_indice(n): ''' valida índice de uma raiz. Deve ser maior ou igual a 2 ''' while True: try: num = int(input(n)) if num < 2: raise Exception('Índice deve ser maior ou igual a 2') except ValueError: print('Digite um número inteiro.') continue except Exception as erro: print(f'Valor inválido: {erro}') continue else: return num def ler_num_nat(n): ''' aceita somente números naturais ''' while True: try: num = int(input(n)) if num < 0: raise Exception('Digite um número maior ou igual a zero.') except ValueError: print('Apenas números naturais.') continue except Exception as erro: print(f'Valor inválido: {erro}') continue else: return num
false
7db3286c9184aa0405e47981b84fa87624ac8cee
rjrobert/daily_coding_problems
/daily12.py
1,580
4.125
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Amazon. There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. For example, if N is 4, then there are 5 unique ways: 1, 1, 1, 1 2, 1, 1 1, 2, 1 1, 1, 2 2, 2 What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time. """ # Ends up being fibonacci algorithm fib(n) def fib(n): # memo = [0] * (n + 1) # memo[0] = 1 # memo[1] = 1 # return fib_helper(n, memo) last_two = 1 last_one = 1 curr = 2 for i in range(n - curr): last_two = last_one last_one = curr curr = last_one + last_two return curr def fib_helper(n, memo): if memo[n] > 0: return memo[n] if n < 2: return 1 memo[n] = fib_helper(n - 1, memo) + fib_helper(n - 2, memo) return memo[n] def fib2(n, steps): memo = [0] * (n + 1) memo[0] = 1 memo[1] = 1 return fib_helper2(n, memo, steps) def fib_helper2(n, memo, steps): if memo[n] > 0: return memo[n] if n < 2: return 1 for i in steps: if n >= i: memo[n] += fib_helper2(n - i, memo, steps) return memo[n] print(fib(4)) assert(fib(4) == 5) print(fib2(4, {1, 3, 5})) assert(fib2(4, {1, 3, 5}) == 3)
true
1901e6e18d17b4595391d581443e672a924e2089
cse210-spring21-team4/cse210-tc06
/src/mastermind/game/player.py
1,259
4.15625
4
class Player: """A person taking part in a game. The responsibility of Player is to record player moves and hints. Stereotype: Information Holder Attributes: _name (string): The player's name. _move (Move): The player's last move. """ def __init__(self, players=list): """The class constructor. Args: self (Player): an instance of Player. players (list): a list of player names """ self.__moves = {player: [] for player in players} def get_moves(self, player=str): """Returns a player's move/hint record. If the player hasn't moved yet this method returns None. Args: self (Player): an instance of Player. """ if player in self.__moves.keys(): return self.__moves[player] return None def record_move(self, player=str, move_hint=tuple): """Sets the player's last move to the given instance of Move. Args: self (Player): an instance of Player. move_hint (tuple): a tuple of strings of the player's move, followed by the resulting hint. """ self.__moves[player].append(move_hint)
true
e17792c43909aeb873441ff67efb33b42c2d1f84
vburnin/PythonProjects
/CompoundInterestLoops.py
2,028
4.53125
5
import locale locale.setlocale(locale.LC_ALL, '') # Declare Variables nDeposit = -1 nMonths = -1 nRate = -1 nGoal = -1 nCurrentMonth = 1 # Prompt user for input, check input to make sure its numerical while nDeposit <= 0: try: nDeposit = int(input("What is the Original Deposit (positive value): ")) except ValueError: print("Input must be a positive numeric value") if nDeposit <= 0: print("Input must be a positive numeric value") while nRate <= 0: try: nRate = float(input("What is the Interest Rate (positive value): ")) except ValueError: print("Input must be a positive numeric value") if nRate <= 0: print("Input must be a positive numeric value") while nMonths <= 0: try: nMonths = int(input("What is the Number of Months (positive value): ")) except ValueError: print("Input must be a positive numeric value") if nMonths <= 0: print("Input must be a positive numeric value") while nGoal < 0: try: nGoal = int(input("What is the Goal Amount (can enter 0 but not negative): ")) except ValueError: print("Input must be zero or greater") if nGoal < 0: print("Input must be zero or greater") # Calculate Monthly Rate and save deposit for second loop nMonthRate = nRate * 0.01 / 12 nAccountBalance = nDeposit # For each month output the month and the current balance to screen while nCurrentMonth <= nMonths: nAccountBalance += nAccountBalance * nMonthRate print("Month:", nCurrentMonth, "Account Balance is:", locale.currency(nAccountBalance)) nCurrentMonth += 1 # Reset Month Counter nCurrentMonth = 0 # Find amount of months it will take to reach goal by looping monthly calculation until goal reached while nGoal > nDeposit: nDeposit += nDeposit * nMonthRate nCurrentMonth += 1 # Output the amount of months it would take to reach the goal and the goal print("It will take:", nCurrentMonth, "months to reach the goal of", locale.currency(nGoal))
true
343e43016f793b6f56dcca61a38bc7ee7eb479a5
ajuliaseverino/tutoring
/tut/basics.py
1,420
4.21875
4
# print('Hello world') # x = 5.6 # print(x) # # print("\nFor loop from 0 to 9.") # for i in range(10): # print(i) def input_switch(): """A function definition. Calling the function by typing input_switch() will run this code. The code does *not* get run when you create the function. """ user_input = input("type some stuff ") print("you typed {}".format(user_input)) if user_input == "yes": print("ok, good") elif user_input == "no": print("ok, bad") else: print("khsdf") # print("\nFunctions with arguments now.") def pos_neg(some_data_asdf): """Arguments (some_data_asdf) are used when there's some data you don't know in advance, but you *do* know what you want to do with that data. """ if some_data_asdf < 0: return some_data_asdf - 2 else: return some_data_asdf + 2 # Runs the identity function, but with all the 'some_data_asdf' replaced by 5. # identity(-5) # identity(5) # identity(6) # print("\nVery very simple calculator now.") def simple_calculator(right_hand_side, operator, left_hand_side): if operator == "+": return right_hand_side + left_hand_side elif operator == "-": return right_hand_side - left_hand_side elif operator == "*": return right_hand_side * left_hand_side elif operator == "/": return right_hand_side / left_hand_side
true
94adb3c9cce3d65357bc0fcc29bb1f0986d73877
sinadadashi21/Wave-4
/pig-latin.py
758
4.21875
4
ay = "ay" way = "way" consonant = ("B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "Y", "V", "X", "Z") vowel = ("A", "E", "I", "O", "U") word = input("Enter the word to translate to Pig Latin: ") first_letter = word[0] first_letter = str(first_letter) first_letter=first_letter.upper() if first_letter in consonant: print(first_letter,"is a consonant") length_of_word = len(word) remove_first_letter = word[1:length_of_word] pig_latin = remove_first_letter + first_letter + ay print("The word in Pig Latin is:", pig_latin) elif first_letter in vowel: print(first_letter, "is a vowel") pig_latin = word + way print("The word in Pig Latin is:" , pig_latin) else: print("I dont know what ", first_letter, "is ")
false
66536ba1353fcefb8951dec0ad9f47e4557f30b3
Hamsik2rang/Python_Study
/References_Of_Object/Tuple.py
764
4.40625
4
# tuple # tuple is immutable object. so when you create tuple once, you can't change or delete element(s) in it. t = (1,) print(t) print(" remark: you can't create tuple that have an element without using comma(,). because it is confused with parenthesis operation.\n") t = (1,2,3) print(t) t = 1,2,3 print(t) # indexing t = 1,2,3,4 print(f"t is {t}, and t[2] is {t[2]}\n") # slicing t = 1,2,3,4 print(f"t is{t}, and t[1:3] is {t[1:3]}\n") # add tuple t1 = 1,2 t2 = 3,4 print(f"t1 is {t1}, t2 is {t2}, then t1 + t2 is {t1+t2}\n") # repeat tuple t = 1,2 print(f"t is {t}, t * 3 is {t*3}\n") # count t = 1,2,1,1,4,2 print(f"t is {t}, and count of 1 in t is {t.count(1)}\n") # get Index t = 1,2,3,4 print(f"t is {t}, and index of 4 in t is {t.index(4)}\n")
true
b5b661c4c6a50e6195d672b23b9d7ce00eb18490
Hamsik2rang/Python_Study
/Day13/Sources/Day13_2.py
234
4.3125
4
def is_pelindrome(word): if len(word)<2: return True elif word[0]!=word[-1]: return False return is_pelindrome(word[1:-1]) word = input("Type word to check it is pelindrome: ") print(is_pelindrome(word))
false
cd0e80bafd2a6c761dab0c92e11c4aa82b145466
Hamsik2rang/Python_Study
/Day14/Sources/Day14_6.py
514
4.375
4
# Generator # Generator is a function contain 'yield' keyword. # Generator works like iterator object. def my_generator(): # When Interpreter(Compiler) meet 'yield' keyword, Literally yield program flow(resources) to main routine. # It means return value there is next 'yield' keyword, and stop routine until next call. yield 0 yield 1 yield 2 def not_generator(): return 10 ptr = my_generator() print(next(ptr)) print(next(ptr)) print(next(ptr)) for i in not_generator(): print(i)
true
87578912fbfeadc41774c42416ce99bc646a57cf
Hamsik2rang/Python_Study
/Day13/Sources/Day13_11.py
958
4.125
4
# Multiple Inheritance # Python support Multiple Inheritance. class Dragon: def breath(self): print("브레스!!!! 피해욧!!!!!") class Elf: def heal(self): print("치유 마법") class Player(Dragon, Elf): def attack(self): print("얍!") me = Player() me.breath() me.heal() me.attack() # Diamond Inheritance class A: def foo(self): print("A") class B(A): def foo(self): print("B") class C(A): def foo(self): print("C") class D(B, C): pass d = D() # Generally, Programmer(User) don't know what letter will be printed d.foo() # In python, it follow Method Resolution Order, MRO. # when you want to check this order, use mro() function like this: D.mro() # MRO is same with Inheritance argument order. # when class D was defined, Inheritance argument order is B->C. (class D(B, C): ...) # +a. All Python objects inherit 'Object' class. like this: print(int.mro())
true
c00c114531ecc3ccf2d29dd7457ed7c6c68ede60
daniellehoo/python
/week 1/math2.py
467
4.1875
4
# in Python you can do math using the following symbols: # + addtion # - subtaction # * multiplication # / division # ** exponent (not ^) # > greater than # >= greater than or equal to # < less than # <= less than or equal to # and more! answer = (40 + 30 - 7) * 2 / 3 print("what is the answer to life, the universe, and everything?", int(answer)) print ("is it try that 5 * 2 > 3 * 4?") print (5 * 2 > 3 * 4) # float(42) # int (42.0) will cut off decimal, won't
true
c92f0b239c93c37966774573e80496678d007f8e
lance-lh/Data-Structures-and-Algorithms
/剑指offer/printMatrix.py
1,505
4.21875
4
# -*- coding:utf-8 -*- ''' 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. ''' class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): res = [] # 类似于旋转魔方,每次先输出matrix第一行并删除 # 然后,逆时针旋转余下的魔方90度 # 继续输出魔方第一行 # 重复操作 # 直到魔方为空 while matrix: # 输出魔方第一行 res += matrix[0] # 删除魔方第一行 # list的del方法可以删除一个slice或者整个list # 区别于pop方法只删除一个元素 del matrix[0] # *matrix类似于解压原矩阵,即去掉最外层的list # zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。 # 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。 # 总的效果相当于将矩阵逆时针旋转90度 matrix = list(zip(*matrix))[::-1] return res # test m = [[1,2,3],[4,5,6],[7,8,9]] print(Solution().printMatrix(m))
false
114d909c19bfde24e1e4cbccf337b15d6479e418
zerformza5566/CP3-Peerapun-Sinyu
/assignment/Exercise5_1_Peerapun_S.py
436
4.25
4
firstNumber = float(input("1st number : ")) secondNumber = float(input("2nd number : ")) plus = firstNumber + secondNumber minus = firstNumber - secondNumber multiply = firstNumber * secondNumber divide = firstNumber / secondNumber print(firstNumber, "+", secondNumber, "=", plus) print(firstNumber, "-", secondNumber, "=", minus) print(firstNumber, "*", secondNumber, "=", multiply) print(firstNumber, "/", secondNumber, "=", divide)
true
5e0aa09e18545eb0db0f8e21b613e29007b6e25a
nicolesy/codecademy
/projects/codecademy_project_cho_han.py
1,342
4.53125
5
# codecademy_project_cho_han.py # Create a function that simulates playing the game Cho-Han. The function should simulate rolling two dice and adding the results together. The player predicts whether the sum of those dice is odd or even and wins if their prediction is correct. # The function should have a parameter that allows for the player to guess whether the sum of the two dice is "Odd" or "Even". The function should also have a parameter that allows the player to bet an amount of money on the game. # test Test test import random def roll_dice(guess, comp): if guess == comp: result = "You win!" else: result = "You lose." return result money = 100 while money > 0: user_guess = input("Is it even, or odd? ") user_bet = input("How much would you like to bet? ") user_bet = int(user_bet) calc_1 = random.randint(1,6) calc_2 = random.randint(1,6) computer_calc = calc_1 + calc_2 print(f"The random number is {computer_calc}") if computer_calc % 2 == 0: computer_calc = "even" else: computer_calc = "odd" if roll_dice(user_guess, computer_calc) == "You win!": money += user_bet else: money -= user_bet print(f"{roll_dice(user_guess, computer_calc)} You have ${money} remaining.") else: print("You are out of money.")
true
18868e88cc99d47da4052c5231e1d78d4cba6332
dmproia/java1301_myPythonPrograms
/lab8.py
934
4.28125
4
#============================ # PROGRAM SPECIFICATIONS # NARRATIVE DESCRIPTION:Lab8 # # @author (David Proia) # @version(1/27/12) #============================== repeat = "Y" print ("This program is designed to tell allow you to tell if you have a right triangle or not" ) print () while (repeat == "Y"): X = float(input("What is the length of side A of triangle? ")) Y = float(input("What is the length of side B of triangle? ")) Z = float(input("What is the length of side C of triangle? ")) if (X >= Y) and (X >= Z): A = Y B = Z C = X elif (Y >= X) and (Y >= Z): A = Z B = X C = Y elif (Z >= X) and (Z >= Y): A = Y B = X C = Z if (A**2) + (B**2) == (C**2): print ("This is a right triangle!") else: print("This is not a right triangle") repeat = input("Press Y to make more conversion or Q to quit: ")
true
215504ad95354baf30674044d4eb285dc87e8193
Nayalash/ICS3U-Problem-Sets
/Problem-Set-Five/mohammad_race.py
1,491
4.28125
4
# Author: Nayalash Mohammad # Date: October 19 2019 # File Name: race.py # Description: A program that uses the Tortoise and Hare Algorithm to simulate a race. # Import Required Libraries import random import time # Helper Function To Display Name and Progress def display(name, progress): print(name + ": " + str(progress) + "/" + str(length)) # Ask user for length of the race length = int(input("How long is this race? MIN = 20: ")) # Start Progress at zero tortoiseProg = 0 hareProg = 0 # Initialize Moves Dictionaries hareMoves = {0: 0, 1: 0, 2: 9, 3: 9, 4: -12, 5: 1, 6: 1, 7: 1, 8: -2, 9: -2} tortoiseMoves = {0: 3, 1: 3, 2: 3, 3: 3, 4: 3, 5: -6, 6: -6, 7: 1, 8: 1, 9: 1} # While Condition, Until Lengths are not less than zero while hareProg < length or tortoiseProg < length: # Pick from the nine moves moveChoice = random.randint(0, 9) # Add moves to the progress counter tortoiseProg += tortoiseMoves[moveChoice] hareProg += hareMoves[moveChoice] if(tortoiseProg < 0): tortoiseProg = 0 if(hareProg < 0): hareProg = 0 # Display place every iteration if(hareProg < length and tortoiseProg < length): display("Tortoise", tortoiseProg) display("Hare", hareProg) time.sleep(0.5) # Slow Down Text Scrolling # Display Outcome if(hareProg == tortoiseProg): print("The Hare and the Tortoise have tied.") elif(hareProg > tortoiseProg): print("The Hare has won!") else: print("The Tortoise has won!")
true
94d53ee92c8275a4b71070097047f3085972db20
Nayalash/ICS3U-Problem-Sets
/Problem-Set-Seven/mohammad_string_blank.py
1,094
4.25
4
# Author: Nayalash Mohammad # Date: November 01 2019 # File Name: string_blank.py # Description: A program that replaces multiple spaces with one # Main Code def main(): # Ask for string string = input("Enter a string with multiple blank spaces...\n") # Regex the string, and join it newString = ' '.join(string.split()) print("********************************") # Display Results print("Your Formatted String is: ") print(newString) # Re-Run menu() # Menu Method def menu(): print("To Run Program: type run, To Quit: type quit, For Help: type help") # Ask user for what they would like to do option = input() if (option == "run"): main() # Run App menu() elif (option == "quit"): exit() elif (option == "help"): print('To run program, type `run` below, or `quit` to quit the program. Refer to docs for more info.') print('Type your spaced out text, and the program will format it for you.') menu() else: print("Invalid Input") menu() # Init Program print("Welcome To String Formatter") menu()
true
d46054d6f12fb1140e5db12b87a461d140910079
Nayalash/ICS3U-Problem-Sets
/Problem-Set-Three/mohammad_zodiac.py
1,726
4.46875
4
# Author: Nayalash Mohammad # Date: October 01 2019 # File Name: zodiac.py # Description: A program that displays your # zodiac sign based on your birthday # Ask user for their birthday try: day = int(input("Enter Birth Day: ")) month = int(input("Enter Month In Number Format (ex: September = 9) ")) except ValueError: print("Invalid Input") # Use Zodiac Algorithm if month == 12: # December if (day < 22): sign = 'Sagittarius' else: sign = 'Capricorn' elif month == 1: # January if (day < 20): sign = 'Capricorn' else: sign = 'Aquarius' elif month == 2: # February if (day < 19): sign = 'Aquarius' else: sign = 'Pisces' elif month == 3: # March if (day < 21): sign = 'Pisces' else: sign = 'Aries' elif month == 4: # April if (day < 20): sign = 'Aries' else: sign = 'Taurus' elif month == 5: # May if (day < 21): sign = 'Taurus' else: sign = 'Gemini' elif month == 6: # June if (day < 21): sign = 'Gemini' else : sign = 'Cancer' elif month == 7: # July if (day < 23): sign = 'Cancer' else: sign = 'Leo' elif month == 8: # August if (day < 23): sign = 'Leo' else: sign = 'Virgo' elif month == 9: # September if (day < 23): sign = 'Virgo' else: sign = 'Libra' elif month == 10: # October if (day < 23): sign = 'Libra' else: sign = 'Scorpio' elif month == 11: # November if (day < 22): sign = 'Scorpio' else: sign = 'Sagittarius' # Print the result to the console print("The Astrological sign for your birthday is: " + sign)
false
2c3dd09d52eaa860167288b7192be1bcca2b176a
Nayalash/ICS3U-Problem-Sets
/Problem-Set-One/digit_breaker.py
277
4.125
4
# Author: Nayalash Mohammad # Date: September 20 2019 # File Name: digit_breaker.py # Description: A program that splits the digits in a number # Ask a number from the user number = input("Enter a Three Digit Number: ") # Iterate over the provided string for i in number: print(i)
true
2494877cda4f8f5ebc6f88de5bd26cc0726d695e
Isaac3N/python-for-absolute-beginners-projects
/reading files.py
1,110
4.53125
5
# read it # demonstrates reading from a text file print("opening and a closing file.") text_file= open("readit.txt", "r") text_file.close() print("\nReading characters from a file.") text_file= open ("readit.txt", "r") print(text_file.read(1)) print(text_file.read(5)) text_file.close() print("\nReading the entire file at once.") text_file = open("readit.txt","r") whole_thing= text_file.read() print(whole_thing) text_file.close() print("\nReading characters from a line.") text_file= open("readit.txt", "r") print(text_file.readline(1)) print(text_file.readline(5)) text_file.close() print("\nReading one line at a time.") text_file= open("readit.txt", "r") print(text_file.readline()) print(text_file.readline()) print(text_file.readline()) text_file.close() print("\nReading the entire file into a list.") text_file= open("readit.txt", "r") lines = text_file.readlines() print(lines) print(len(lines)) for line in lines: print (line) text_file.close() print("\nlooping through a file line by line") text_file= open("readit.txt", "r") for line in text_file: print (line) text_file.close()
true
f75b734c0b6c1848e23253466a2a637dd5220983
Isaac3N/python-for-absolute-beginners-projects
/limited tries guess my number game.py
608
4.21875
4
# welcome to the guess my number game # your to guess a number from 1-5 # your limited to 3 tries import random print (" welcome to the guess my number game \n your limited to a number tries before the game ends \n GOOD LUCK !") the_number = random.randint(1,5) guess = input (" take a guess: ") tries = 1 while guess != the_number and tries <= 3: if guess > str(the_number) : print ("lower....") else : print ("higher....") guess = input (" take a guess: ") tries += 1 print ( " congratulations! you guessed it ") print (" and you did it in only",tries, " tries" )
true
111c7e5018e2779b0cc2114a0c0883d6d40665b8
Lslonik/python_algorithm
/HW_1/HW_1.6.py
450
4.21875
4
# Пользователь вводит номер буквы в алфавите. Определить, какая это буква letter_number = int(input("Введите номер буквы английского алфавита: ")) if 97 <= ord(chr(96 + letter_number)) <= 122: your_letter = chr(96 + letter_number) print(f"Ваша буква: {your_letter}") else: print("Такой буквы нет в алфавите")
false
70c6046607605e1e817655ea5d67df32d6491468
Lslonik/python_algorithm
/HW_3/HW_3.2.py
930
4.125
4
# Во втором массиве сохранить индексы четных элементов первого массива. Например, # если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5, # (индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа. import random SIZE = int(input('Введите размер массива: ')) MIN_ITEM = 0 MAX_ITEM = 100 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(f'Сгенерированный массив: {array}.\nМассив с индексами четных элементов сгенерированного элемента' f' {[arr_index for arr_index, arr_el in enumerate(array) if arr_el % 2 == 0]}')
false
988207876d95d5de27ef0fb9e14600343a9afe56
macheenlurning/python-classwork
/Chap3Exam.py
2,478
4.3125
4
# Ryan Hutchinson # Chapter 3 Exam # Programming Projects 1 & 3 #1 - Car Loan loan = int(input("Enter the amount of the loan: ")) if int(loan) >= 100000 or int(loan) < 0: print("Total loan value {} might be incorrect...".format(loan)) response1 = input("Would you like to correct this? Type Yes or No: ").lower() if response1 == 'yes': loan = int(input("Enter the amount of the loan: ")) elif response1 == 'no': pass annual_rate = float(input("Enter the interest rate: ")) if float(annual_rate) >= 30 or float(annual_rate) < 0: print("Annual rate {} might be incorrect?".format(annual_rate)) response2 = input("Would you like to correct this? Type Yes or No: ").lower() if response2 == 'yes': annual_rate = float(input("Enter the interest rate: ")) elif response2 == 'no': pass duration = int(input("Enter the duration in months: ")) if int(duration) > 72 or int(duration) < 12: print("Duration of {} months might be incorrect?".format(duration)) response3 = input("Would you like to correct this? Type Yes or No: ").lower() if response3 == 'yes': duration = int(input("Enter the duration in months: ")) elif response3 == 'no': pass monthly_rate = round(((annual_rate/100) / 12), 8) part1 = round((loan * monthly_rate), 8) part2 = round(((1 / ((1 + monthly_rate) ** duration))), 8) part3 = round((1 - part2), 8) monthly_payment = round(float(part1 / part3), 2) tot_int = (duration * monthly_payment) - loan formatted_mp = "{:.2f}".format(monthly_payment) formatted_ti = "{:.2f}".format(tot_int) print("Monthly payment: ${}".format(formatted_mp)) print("Total interest paid: ${}".format(formatted_ti)) print() #3 - Caffeine Absorption print("CAFFEINE VALUES") total_caf = 130 hours = 0 while total_caf >= 65: total_caf = total_caf * 0.87 hours += 1 if total_caf < 65: print("One cup: less than 65mg. will remain after {} hours.".format(hours)) total_caf = 130 hours = 0 while hours <25: hours += 1 total_caf = (total_caf * 0.87) if hours == 24: print("One cup: {:.2f} mg. will remain after 24 hours.".format(total_caf)) total_caf = 130 hours = 0 while hours < 25: hours += 1 total_caf = total_caf * 0.87 total_caf = total_caf + 130 if hours == 24: print("Hourly cups: {:.2f} mg. will remain after 24 hours.".format(total_caf))
true
157677c2d65797724248e4bec4396ffc2f698b5d
samirghouri/DS-and-ALGO-In-Python
/Recursion/recursion1.py
1,480
4.34375
4
# Lets take a look at the Fibonacci Series Example # We have the following conditions # F(0) = 0, F(1) = 1, F(2) = F(1) + F(0) , F(3) = F(2) +F(1) and so on # 0,1 when n =0,1 # F(n) = # F(n-1) + F(n-1) when n >=2 # Lets implement the function using two methods - 1.Iteratively 2. Recursively # 1.Iteratively ''' # n refers to nth element def FibonacciIterative(n): if n == 0: return 0 elif n == 1: return 1 else: F_0 = 0 F_1 = 1 for i in range(2, n): number = F_0 + F_1 F_0 = F_1 F_1 = number return number print(FibonacciIterative(8)) ''' # 2.Recursively ''' def FibonacciRecursive(n): if n == 1: return 0 elif n == 2: return 1 else: return FibonacciRecursive(n-1)+FibonacciRecursive(n-2) print(FibonacciRecursive(8)) ''' # Now as we can see that Recusion take much longer the iterative methods # Because in recusion: # Fib(5) # / \ # Fib(4) Fib(3) # / \ / \ # Fib(3) Fib(2) Fib(2) Fib(1) # / \ / \ # Fib(2) Fib(1) Fib(1) Fib(0) # / \ # Fib(1) Fib(0) # The calculation of many of numbers are iterative like for n=2,Fib(2) is calculated 3 times # So the running time grows exponentially
false
a5405798c83b1ecc5b8095b4a8251ea3d6aa8fea
bapadman/PythonToddlers
/pythonTutorialPointCodes/IfElse.py
277
4.1875
4
#!/usr/bin/python # classic if else loop example flag = True if not flag: print("flag is true") print("Printing from if loop") else: print("flag is false") print("Printing from else part") #while loop sample i = 0 while i < 10: print("i = ",i) i = i +1
true
12e1b7a3613ff30f58297f3d9bd670acdb1beb98
gslmota/Programs-PYTHON
/Exercícios/Mundo 1/ex016.py
485
4.15625
4
# nome da pessoa e informações nome = str(input('Digite o nome: ')).strip() # serve para eliminar os espaços print( 'Seu nome em maiúsculas é: {}'.format(nome.upper())) print('Seu nome em minúsculas é: {}'.format(nome.lower())) print('Seu nome tem {} letras'.format(len(nome) - nome.count(' '))) print('Seu primeiro nome tem {} letras'.format(nome.find(' '))) # poderia ser assim # separa = nome.split() # separa[0] seria o primeiro nome e len(separa[0]) a quantidade de letras
false
7604537c71142580cac2e42afb4ee9f484816477
gslmota/Programs-PYTHON
/Exercícios/Mundo 1/ex00.py
428
4.21875
4
# Desafio 4 Aula 6 # Mostra informações sobre o tipo prmitivo txt = input('Digite alguma coisa: '); print('O tipo primitivo de {} é {}'.format(txt, type(txt))); print('Só tem espaços? {}'.format(txt.isspace)); print('É um número? {}'.format(txt.isnumeric)); print('É alfabético? {}'.format(txt.isalpha)); print('É alfanumérico? {}'.format(txt.isalnum)); print('Está em letras maiúsculas? {}'.format(txt.isupper));
false
55306a5cb494265ccaec0969650a6f311fe7270f
finolex/Python_F18_Abhiroop
/Lab 3 - Booleans/q3.py
485
4.125
4
import math firstLeg = int(input("Please enter the length of the first leg: ")) secondLeg = int(input("Please enter the length of the second leg: ")) hyp = float(input("Please enter the length of the hypothenuse: ")) hypCalc = math.sqrt(firstLeg**2 + secondLeg**2) if hyp == hypCalc: print("This forms a right angled triangle!") elif abs(hyp - hypCalc) < 0.00001: print("This forms a right angled triangle!") else: print("This does not form a right angled triangle.")
true
5b275184d7845c54e6b3427b353d49d1e9fa22ba
finolex/Python_F18_Abhiroop
/Lab 4 - While loops/q3.py
247
4.15625
4
dividend = int(input("Please input a positive int for dividend: ")) divisor = int(input("Please input a positive int for divisor: ")) count = 0 quotient = dividend while quotient >= divisor: quotient -= divisor count += 1 print(count)
false
5c624b55e026aa8c9c506162767176dd19e4fd7c
finolex/Python_F18_Abhiroop
/Lab 3 - Booleans/q4.py
382
4.15625
4
num1 = int(input("Please enter your first integer: ")) num2 = int(input("Please enter your second integer: ")) if num2 == 0: print("This has no solutions.") elif (-num1/num2) > 0 or (-num1/num2) < 0: print("This has a single solution and x = .", (-num1/num2)) elif (-num1/num2) == 0: print("This has a single solution.") else: print("This has infinite solutions.")
true
172720a347baa8828443ba979fb4fe01b2e7f6f5
gabrielchase/MIT-6.00.1x-
/Week2/prob3.py
1,116
4.5
4
# Write a program that calculates the minimum fixed monthly payment needed # in order pay off a credit card balance within 12 months. By a fixed monthly # payment, we mean a single number which does not change each month, but # instead is a constant amount that will be paid each month. MONTHS_IN_A_YEAR = 12 # Given by the problem balance = 999999 annualInterestRate = 0.18 def get_monthly_interest_rate(): return annualInterestRate/MONTHS_IN_A_YEAR def monthly_mimimal_payment(balance, annual_interest_rate): monthly_interest_rate = 1 + get_monthly_interest_rate() coefficient = 0 for _ in range(MONTHS_IN_A_YEAR): coefficient = (coefficient + 1) * monthly_interest_rate balance = balance * monthly_interest_rate return balance/coefficient minimal_payment = monthly_mimimal_payment(balance, annualInterestRate) print('Lowest Payment:', round(minimal_payment, 2)) assert minimal_payment == 90325.03 # Answer researched on # 'https://codereview.stackexchange.com/questions/142676/for-a-given-balance-and-an-annual-interest-rate-calculate-the-minimum-fixed-mon'
true
2db9fc416ebd7d63033eb5d30f83e7c51b1733aa
GabrielCardoso2019/Curso-de-Python
/Modulo03/A-Tuplas.py
1,130
4.34375
4
lanche = ('Hambúrger', 'Suco', 'Pizza', 'Pudim', 'Batata Frita') # Tuplas são imutáveis # lanche[1] = 'Refrigerante' <-- Não funciona # print(lanche) # trás do 1 ao 3 item print(lanche[1:3]) # Trás do 1 ao 0 (Python ignora um número) print(lanche[:2]) # Trás o 3º item de trás para frente print(lanche[-3:]) # Mostra toda a tupla print(lanche) # Mostra quantos elementos existem na tupla print(len(lanche)) print('=' * 20) for cont in range(0, len(lanche)): print(lanche[cont]) print('-=' * 30) for comida in lanche: print(f'Eu vou comer {comida}') print('Comi pra caramba!') print('-=' * 30) for cont in range(0, len(lanche)): print(f'fEu vou comer {lanche[cont]} na posição {cont}') print('-=' * 30) for pos, comida in enumerate(lanche): print(f'Eu vou comer {comida} na posição {pos}') print('Comi pra caramba!') print('-=' * 30) # Mostra a ordem em tamanho print(sorted(lanche)) print(lanche) print('=' * 20) a = (2, 5, 4) b = (5, 8, 1, 2) c = a + b print(c) print(len(c)) print(c.count(1)) print(c.index(2, 4)) print('=' * 20) pessoa = ('Gabriel', 39, 'M', 1.71) print(pessoa)
false
b785ed5bff4e17cb22b7ee84e0144ab222dedd45
green-fox-academy/FulmenMinis
/week-04/day-03/fibonacci.py
386
4.25
4
# Fibonacci # Write a function that computes a member of the fibonacci sequence by a given index # Create tests that covers all types of input (like in the previous workshop exercise) def fibonacci(n=0): if n < 0: return False elif n == 0: return 0 elif n == 1 or n == 2: return 1 else: return (fibonacci(n-1) + fibonacci(n-2))
true
a0aacffaecbcb78b56a2f2beecb7d2bf0b143f68
green-fox-academy/FulmenMinis
/week-03/day-04/number_adder.py
264
4.25
4
# Write a recursive function that takes one parameter: n and adds numbers from 1 to n. def recursive_function(n): if n == 0 or n == 1: return n else: return (recursive_function(n-1) + recursive_function(n-2)) print(recursive_function(10))
true
19684231d4bc2fa7ee4e71da4563451022e7c826
green-fox-academy/FulmenMinis
/week-04/day-03/sum.py
790
4.1875
4
# Sum # Create a sum method in your class which has a list of integers as parameter # It should return the sum of the elements in the list # Follow these steps: # Add a new test case # Instantiate your class # create a list of integers # use the assertEquals to test the result of the created sum method # Run it # Create different tests where you # test your method with an empyt list # with a list with one element in it # with multiple elements in it # with a null # Run them # Fix your code if needed class Sum(object): def sum(self, numbers): sum_of_all_numbers = 0 for number in numbers: sum_of_all_numbers += number return sum_of_all_numbers
true
29109f6f4dd6932523c63ff32de11b4598cfd4ff
green-fox-academy/FulmenMinis
/week-02/day-03/string02.py
661
4.15625
4
# Create a function called 'reverse_string' which takes a string as a parameter # The function reverses it and returns with the reversed string #Solution 1 reversed = ".eslaf eb t'ndluow ecnetnes siht ,dehctiws erew eslaf dna eurt fo sgninaem eht fI" reversed = reversed[::-1] print(reversed) #Solution 2 def slowreverse(text): s = '' for i in text: s = i + s print (s) slowreverse(".eslaf eb t'ndluow ecnetnes siht ,dehctiws erew eslaf dna eurt fo sgninaem eht fI") #Solution 3 reversed = ".eslaf eb t'ndluow ecnetnes siht ,dehctiws erew eslaf dna eurt fo sgninaem eht fI" def reverse(x): a = x[::-1] print(a) reverse(reversed)
false
3c7361f73a5fdee8d31f86f9961ba5f5239060cb
green-fox-academy/FulmenMinis
/week-02/day-05/armstrong_number.py
1,108
4.4375
4
#Exercise # #Write a simple program to check if a given number is an armstrong number. # The program should ask for a number. E.g. if we type 371, the program should print out: # The 371 is an Armstrong number. # What is Armstrong number? # An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits. # Let's demonstrate this for a 4-digit number: 1634 is a 4-digit number, # raise each digit to the fourth power, and add: 1^4 + 6^4 + 3^4 + 4^4 = 1634, so it is an Armstrong number. #Solution1 number = input("Please enter a number: ") numberlist = [] for i in range(len(number)): numberlist.insert(len(numberlist), int(number[i])) sum = 0 for i in numberlist: sum += i ** len(numberlist) print("The " + str(number) + " is an Armstrong number." if int(number) == sum else "The " + str(number) + " isn't an Armstrong number.") #Solution2 x = input("Please enter a number: ") exponent = len(x) sum = 0 for c in x: sum += int(c)**exponent if sum == int(x): print( x + " is an Armstrong number!") else: print( x + " isn't an Armstrong number!")
true
f0bcacd257e329b9376e7c1fbe00161b8772c248
chicolucio-python-learning/hacker-rank
/array_2d/array_2d.py
802
4.15625
4
def hourglass_sum(arr): """Return the maximum hourglass sum in a given array Parameters ---------- arr : array an array of integers Returns ------- integer The maximum hourglass sum in a given array """ sum_pattern = [] for line in range(len(arr) - 2): aux = 0 for column in range(len(arr[line]) - 2): aux_same_line = arr[line][column] + \ arr[line][column + 1] + arr[line][column + 2] aux_line_down = arr[line+1][column + 1] aux_two_lines_down = arr[line + 2][column] + \ arr[line + 2][column + 1] + arr[line + 2][column + 2] aux = aux_same_line + aux_line_down + aux_two_lines_down sum_pattern.append(aux) return max(sum_pattern)
false
eef3efc9d6fbb3a27978cd4bdbba4c680eee92b1
depecik/-rnekler
/PythonTemelleri/Fonksiyonlar3.py
1,404
4.15625
4
# say = input("Kontrol etmek istediğiniz sayıyı giriniz") # toplam = 0 # for i in say: # toplam += int(i)**(len(say)) # if toplam == int(say): # print("Armstrong Sayısı") # def sayiKontrol(*args): # toplam = 0 # sayi = "" # for i in args: # toplam += int(i)**(len(args)) # sayi+=i # if toplam == int(sayi): # return True # else: # return False # if sayiKontrol(*input("Kontrol etmek istediğiniz sayıyı giriniz")): # print("Budur") # N = int(input("Bir Pozitif Tam Sayı Giriniz")) # x=2 # while x<=N: # i = 2 # while i*i<=x: # if x%i==0: # break # i += 1 # else: # print(x) # x+=1 # def deneme(**kwargs): # for key,value in kwargs.items(): # if key == "Isim": # if value == "Soner": # print("Sen gonuşma Sonner") # break # def calc_factorial(x): # """This is a recursive function # to find the factorial of an integer""" # if x == 1: # return 1 # else: # return (x * calc_factorial(x-1)) # num = 4 # print("The factorial of", num, "is", calc_factorial(num)) # def f1(param): # if len(param) >= 1: # f1(param[0:len(param)-1]) # print(param) # f1("Tripanazomigambiyetsiz") # input("değişken tanımla") # exec(input("değişken tanımla")) # print(eval("25+30")) # print(a)
false
8164ea4320540ca503dc3493c629c74666eeec1f
ShivaVkm/PythonPractice
/playWithTrueFalse.py
769
4.25
4
# True means 1 and False in 0 print(True) # you will get True print(False) # you will get False print(True+False) # you will get 1 because True = 1 and False = 0 print(True == 1) # verification for trueness' value as equal to 1 print(False == 0) # verification for falseness' value as equal to 0 print(True+True) print(True-True) print(True*True) print(True/True) print(True%True) print(False+False) print(False-False) print(False*False) # print(False/False) # ZeroDivisionError: division by zero # print(False%False) # ZeroDivisionError: integer division or modulo by zero print(True+False) print(True-False) print(True*False) # print(True/False) # ZeroDivisionError: division by zero # print(True%False) # ZeroDivisionError: integer division or modulo by zero
true
fa1ead85ec576a9d9f3f7595e855b0afcc5c2abc
rpt/project_euler
/src/problem001.py
597
4.1875
4
#!/usr/bin/env python3 # Problem 1: # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. # Answer: # 233168 def problem1(n): def sumd(x, n): k = (n - 1) // x return x * k * (k + 1) // 2 return sumd(3, n) + sumd(5, n) - sumd(15, n) # print(problem1(1000)) def problem1n(n): '''Naive, slow version.''' c = 0 for i in range(1, n): if (i % 3 == 0) or (i % 5 == 0): c += i return c
true
303c154afaa831b39882865c536de7666c8af7c3
JiungChoi/NeuralNetworkOnColab
/regressionFunc2.py
914
4.21875
4
import matplotlib.pyplot as plt import numpy as np ## 입력 데이터 x의 개수 만큼 반복함 def cost(x, y, w): c = 0 for i in range(len(x)): hx = w*x[i] c = c + (hx -y[i])**2 return c/(len(x)) x_data = [1, 2, 3] y_data = [1, 2, 3] plt.plot(x_data, y_data, 'ro') plt.show() print(cost(x_data, y_data, -1)) print(cost(x_data, y_data, 0)) print(cost(x_data, y_data, 1)) print(cost(x_data, y_data, 2)) print(cost(x_data, y_data, 3)) for w in np.linspace(-3, 5, 50): c = cost(x_data, y_data, w) print(w, c) plt.plot(w, c, 'ro') plt.show def gradient(x, y, w): c = 0 for i in range(len(x)): hx = w*x[i] c = c + (hx -y[i])*x[i] return c/(len(x)) def showgradient(): x_data = [1,2,3] y_data = [1,2,3] w = 10 for i in range(200): c = cost(x_data, y_data, w) g = gradient(x_data, y_data, w) w = w - 0.1*g print(i, c, 'w=', w) print('최종 w= ',w)
false
f746de4262b1c9f975a55ee02581b7a873ce1146
tglaza/Automate-the-Boring-Stuff-with-Python
/while_break_yourName_input.py
514
4.28125
4
#this is similar the first yourName program, except it uses a break to end the program #break statements are useful if you have several different places in a while loop that would allow you to leave from that point name = '' while True: #this would never be False so it's an infinite loop because it's always True print('Please type your name.') name = input() if name == 'your name': #uses an if statement to cause a break in the program so it doesn' run forever break print('Thank you!')
true
3caa06220975d573f9400da144c54c853555addc
robbailiff/database-operations
/sqlite_functions.py
1,920
4.84375
5
""" Here is some practice code for using the sqlite3 module with Python. Here I was experimenting with applying functions in SQLite statements. I have included comments throughout explaining the code for my own benefit, but hopefully they'll help someone else too. Hope you like the code. Any tips, comments or general feedback are welcome. Thanks, Rob +++++++++++++++++++++++++++++++++++++++++ For anyone looking for a tutorial on the sqlite3 module, the tutorial I used is located here: https://www.pythoncentral.io/advanced-sqlite-usage-in-python/ Also the official documentation: https://docs.python.org/3/library/sqlite3.html """ # Import libraries import sqlite3 # Define function def temp_converter(temp): result = round((temp - 32) / 1.8, 1) return result # Connect to the database db = sqlite3.connect(':memory:') # Register the function using the create_function method of connection object, which takes 3 arguments # First is the name which will be used to call the function in an SQL statement # Second is the number of arguments in the function to be called # Third is the function object (i.e. the defined function itself) db.create_function('F_to_C', 1, temp_converter) # Create cursor object cursor = db.cursor() # Create a table in the database cursor.execute('''CREATE TABLE weather( id INTEGER PRIMARY KEY, city TEXT, temp REAL)''') # Insert data into the table but call the function to convert the temperature from Farenheit to Celcius cursor.execute('''INSERT INTO weather(city, temp) VALUES (?,F_to_C(?))''', ("London", 68.3)) # Commit the changes db.commit() # Retrieve all the data in the table cursor.execute('''SELECT * FROM weather''') # Fetch first entry of cursor selection and notice that the temperature has been converted result = cursor.fetchone() print(f"Result returned from query: \n{result}") # And finally close down the database db.close()
true
43d180dea65f2b5d65ec2da20c6524b0e42047c5
mareaokim/hello-world
/03_8번Gregorian.py
456
4.1875
4
def main(): print("Gregorian epact value of year.") print() year = int(input("Enter the year (e.g. 2020) : ")) c = year // 100 epact = (8+(c//4) - c + ((8*c+13)//25) + 11 * (year % 19)) % 30 print() print("The epact value is" , epact, "days.") main() >>>>>>>>>>>>>>> Gregorian epact value of year. Enter the year (e.g. 2020) : 2030 The epact value is 25 days. Press any key to continue . . .
true
d0a504f3603a3c9471c2826dd00cada6044f1a21
mareaokim/hello-world
/03_3번weight.py
700
4.28125
4
def main(): print("This program calculates the molecular weight of a hydrocarbon.") print() h = int(input("Enter the number of hydrogen atoms : ")) c = int(input("Enter the number of carbon atoms : ")) ox = int(input("Enter the number of oxygen atoms : ")) weight = 1.00794 * h + 12.0107 * c + 15.9994 * ox print() print("The molecular weight is :" , weight) main() >>> This program calculates the molecular weight of a hydrocarbon. Enter the number of hydrogen atoms : 45 Enter the number of carbon atoms : 56 Enter the number of oxygen atoms : 55 The molecular weight is : 1597.9234999999999 Press any key to continue . . .
true
e18412d42429782751836ec1759665325a172b4f
mareaokim/hello-world
/03_12번number2.py
975
4.375
4
def main(): print("This program finds the sum of the cubes of the first n natural numbers.") print() n = int(input("Please enter a value for n : ")) sum = 0 for i in range(1,n+1): sum = sum + i**3 print() print("The sum of cubes of 1 through through", n, "is : ",sum) main() >>>>>>>>>>>>>>>> This program finds the sum of the cubes of the first n natural numbers. Please enter a value for n : 9 The sum of cubes of 1 through through 9 is : 1 The sum of cubes of 1 through through 9 is : 9 The sum of cubes of 1 through through 9 is : 36 The sum of cubes of 1 through through 9 is : 100 The sum of cubes of 1 through through 9 is : 225 The sum of cubes of 1 through through 9 is : 441 The sum of cubes of 1 through through 9 is : 784 The sum of cubes of 1 through through 9 is : 1296 The sum of cubes of 1 through through 9 is : 2025 Press any key to continue . . .
true
2decab40de10c88aa8102ab675e9fa1f3a46c8b0
riteshsahu16/python-programming
/2 loop/ex1.10_check_ifprime.py
270
4.125
4
#Q10. Write a program to check whether a number is prime or not. n = int(input()) i = 2 is_prime = True while(i <= n//2): if n%i==0: is_prime = False break i += 1 if is_prime: print("The no. is prime") else: print("The no. is NOT prime")
true
7dde7fa7aac2351a1d6eeead7dba6877f177db3b
riteshsahu16/python-programming
/1 if else/ex9_min_three.py
576
4.21875
4
#[9] Find minimum number out of given three numbers. print("Enter three no.") a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) if(a==b and b==c): print("all are equal") elif (a==b and a<c) or (a==c and a<b) or (a<b and a<c): if(a==b): print("a and b are equal & minimum") elif(a==c): print("a and c are equal & minimum") else: print("a is minimum") elif (b==c and b<a) or (b<a and b<c): if(b==c): print("b and c are equal & minimum") else: print("b is minimum") else: print("c is minimum")
false
a0a1fbc6a48d45ccb858529ca0f5718390adeb00
MOIPA/MyPython
/practice/basic/text_encode.py
473
4.21875
4
# in RAM all text would be translated to Unicode # while in Disk there are UTF-8 str = u'编码' # Unicode now str = str.encode('utf-8') # UTF-8 print(str) str = str.decode('utf-8') print(str) # riverse a = u'\u5916' print(a) a = a.encode('utf-8') print(a) # -*- coding: utf-8 -*- # the above line means read the code file in utf-8 # format string str = 'hello,%s, the num is %d' % ('world',10) print(str) str = '%.2f' % 3.14111 print(str) str = '%d%%' % 10 print(str)
true
6e0e2c9518732023f4416e5971029e73947d5ea3
MOIPA/MyPython
/practice/basic/list_tuple.py
372
4.15625
4
list_num = [1, 2, 3, 4, 5] print(list_num[-1]) # 3 # delete list_num.pop() # delete the end one list_num.pop(2) # delete the third one print(list_num) # add list_num.append(6) list_num.insert(0, -1) # update list_num[0] = 0 # tow dimensional array one = [2.1, 2.2, 2.3] array = [1, one, 2, 3] print(array[1][0]) # tuple ,can't be changed once inited t = (1, 2, 3)
true
de89cb68e9d89a50e82a89a6711bb1fca137a703
kaysu97/Algorithm
/Recursion&Stack.py
2,489
4.15625
4
#!/usr/bin/env python # coding: utf-8 # f()的複雜度是多少 def f(problemSize): work = 0 for i in range(problemSize): for j in range(i, problemSize): work += 1 class Solution01: def complexity(self): print("n^2") # print your answer here. # 把所有位數相加用Recursion的方式 class Solution02: def addDigits(self, num): if num < 10: return num else: num = num % 10 + self.addDigits(int((num)/10)) if (num >=10): return self.addDigits(num) else: return (num) # In[8]: s = Solution02() s.addDigits(258) # In[3]: class Solution02_Re: def addDigits(self, num): return (num%9) s = Solution02_Re() s.addDigits(258) #找出palindrome的單字,palindrome是一種正的寫跟反過來寫是一樣的單字,例如:madam class Solution04: def isPalindrome(self, s): s = ''.join(c for c in s if c.isalpha()) if s==s[::-1]: return True else: return False s = Solution04() print(s.isPalindrome("never odd or even")) print(s.isPalindrome("madam")) print(s.isPalindrome("mad")) #用Stack的方式找出palindrome的單字 class Stack: # variables # __size__ = 0 # another way to implement size() items = None # functions def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def size(self): return len(self.items) def push(self, item): self.items.append(item) # The method append() appends a passed obj into the existing list. def pop(self): return self.items.pop() # The method pop() removes and returns last object or obj from the list. def peek(self): return self.items[len(self.items)-1] # In[234]: class Solution04_stack: def isPalindrome(self,s): st=Stack() for c in s : if c.isalpha(): st.push(c) for c in st.items: if c != st.pop(): return False break else: return True # In[235]: s=Solution04_stack() print(s.isPalindrome("never odd or even")) print(s.isPalindrome("madam")) print(s.isPalindrome("mad"))
false
17793d481db169e050b08a1c5dd1e281aa08e094
j16949/Programming-in-Python-princeton
/3.3/20_time/time_seconds.py
1,724
4.1875
4
#python官方文档time模块写道: #此模块中定义的大多数函数的实现都是调用其所在平台的C语言库的同名函数。因为这些函数的语义可能因平台而异,所以使用时最好查阅对应平台的相关文档。 #且python或C获取的时间都为运行程序的终端的时间,所以依据题意,想获得当前时间无论如何都得引入系统时间,无论是OS.SYSTEM()还是time。 #python有两个主要处理时间的模块:1.datetime;2.time,其中datetime也可以计算日期。datetime.datetime可以作运算返回datetime.timedelta对象,time.time()则返回float对象 #由于需要创建0点的时间,而time模块中time_struct是只读的,无法创建,方法有二:1.用datetime.datetime创建;2.用striptime格式化。此处采用方法1 #此处使用time,用秒来计算 import datetime import time as rt #防止重名 class time: def __init__(self): a = datetime.datetime.today() b = datetime.datetime(a.year,a.month,a.day) self._t = rt.time()-b.timestamp() def curHour(self): return self._t//3600 def curMinute(self): return self._t//60 def curSecond(self): return self._t def __str__(self): hour = self.curHour() minute = self.curMinute()-hour*60 second = self.curSecond()-hour*60*60-minute*60 return '当前时间是:'+str(int(hour))+':'+str(int(minute))+':'+str(int(second)) def main(): t = time() print('hour:',t.curHour()) print('minute:',t.curMinute()) print('second:',t.curSecond()) print(t) rt.sleep(2) print(time()) if __name__ == '__main__': main()
false
d47af399c0c701882f4c78b20395df6808d2c503
Douglass-Jeffrey/Unit-5-06-Python
/rounder.py
1,330
4.375
4
#!/usr/bin/env python3 # Created by: Douglass Jeffrey # Created on: Nov 2019 # This program turns inputs into a proper address format def rounding(number, rounder): # This function rounds the user's number # Process rounded_number = (number[0]*(10**rounder)) rounded_number = rounded_number + 0.5 rounded_number = int(rounded_number) rounded_number = rounded_number/(10**rounder) return rounded_number def main(): # This function takes the user's number then outputs the number rounded # rounder list rounding_number = [] # Process while True: decimal = input("Enter the number you wish to be rounded: ") rounder = input("Enter how many decimal places you want left: ") try: decimal = float(decimal) rounder = int(rounder) rounding_number.append(decimal) if decimal == float(decimal) and \ rounder == int(rounder): rounded_val = rounding(rounding_number, rounder) print("") print("Your number rounded is", rounded_val) break else: print("Please input proper values") except Exception: print("Please input proper values") print("") if __name__ == "__main__": main()
true
74ae9c1c92272b3cd54e2a76269ddf32994c5822
brentholmes317/Project_Euler_Problems_1-10
/Project_Euler/13_adjacent.py
1,086
4.34375
4
from sys import argv, exit from check_integer import check_input_integer """ This reads a file and finds the largest product that can be had by multiplying 13 adjancent numbers. The program needs the final line in the text to be blank. """ script, filename = argv txt = open(filename) reading = 1 #keeps track of if the file has concluded array_of_digits = [] #converts our file to an array of digits while(reading == 1): sequence = txt.readline() if sequence == '': reading = 0 else: line = check_input_integer(sequence) for i in range(sequence.__len__()-1): array_of_digits.append(line % (10**(sequence.__len__()-1-i)) // 10**(sequence.__len__()-2-i)) biggest = 0 biggest_array = [0,0,0,0,0,0,0,0,0,0,0,0,0] for i in range(array_of_digits.__len__()-12): product = 1 for j in range(13): product = product * array_of_digits[i+j] if biggest < product: biggest = product for k in range(13): biggest_array[k] = array_of_digits[i+k] print(f"{biggest} is the product of {biggest_array}")
true
a743aabc9ab1fc15f8f5264af3b59dcbad5fc870
brentholmes317/Project_Euler_Problems_1-10
/Project_Euler/Pallindrome.py
1,250
4.53125
5
"""This program will find the largest pallindromic product of two three digit numbers""" #this program checks whether a 5-6 digit number is a pallindrome def is_pallindrome(number): #first we find if it is a 5 or 6 digit number if number // 100000 == 0: d5 = number // 10000 d4 = (number % 10000) // 1000 d2 = (number % 100) // 10 d1 = number % 10 if d5 == d1 and d4 == d2: return True else: return False else: d6 = number // 100000 d5 = (number % 100000) // 10000 d4 = (number % 10000) // 1000 d3 = (number % 1000) // 100 d2 = (number % 100) // 10 d1 = number % 10 if d6 == d1 and d5 == d2 and d4 == d3: return True else: return False i = 999 j = 999 cap = 0 tentative_answer = [0,0,0] while i > cap: while j > cap: if is_pallindrome(i*j) == True: if i*j > tentative_answer[0]: tentative_answer = [i*j,i,j] cap = j j -= 1 i -= 1 j = i if tentative_answer[0] == 0: print("No such pallindrome") else: print(f"The largest pallindrome is {tentative_answer[0]} which is the product of {tentative_answer[1]} and {tentative_answer[2]}")
false