blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b197373baee082d3870197644e098d5ccdc4c9a6
evamaina/Basics
/sort.py
317
4.25
4
start_list = [5, 3, 1, 2, 4] square_list = [] # Your code here! for number in start_list: number = number**2 square_list.append(number) square_list.sort() print square_list """Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list. Then sort square_list!"""
true
68834fc74c7c5b40e0d42b732cac0612cb2a8992
evamaina/Basics
/my_dict2.py
386
4.46875
4
my_dict = { 'name': 'Nick', 'age': 31, 'occupation': 'Dentist', } print my_dict.items() print my_dict.keys() print my_dict.values() """While .items() returns an array of tuples with each tuple consisting of a key/value pair from the dictionary: The .keys() method returns a list of the dictionary's keys, and The .values() method returns a list of the dictionary's values."""
true
bce4ab96307b6335aacbdf6efcbaf38f92387e83
JPoser/python-the-hardway
/Exercise 33/ex33st5.py
389
4.1875
4
# Learn Python The Hard Way - Exercise 33 study drill 5 # Copied by Joe Poser i = 2 max = 10 numbers = [] increase = 2 def count(i): for i in range(i, max): print "At the top i is %d" % i numbers.append(i) i = i + increase print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " count(i) for num in numbers: print num
true
6e517cac536fb7bc827979ee81e448c89ca6cf9e
JPoser/python-the-hardway
/Exercise 30/ex30st4.py
1,224
4.34375
4
# Learn Python The Hard Way - Exercise 30 # Copied by JPoser # Sets the value of people to 30 people = 30 # Sets the value of cars to 40 cars = 40 # Sets the value of buses to 15 buses = 15 # Checks if cars are greater than people if cars > people: # If cars are greater than people prints this string print "We should take the cars." # Checks if cars are less than people elif cars < people: # If cars are less than people prints this string print "We should not take the cars." # Checks if neither cases are true (cars equal people) else: # if so prints this line print "We can't decide." # Checks if buses are greater than cars if buses > cars: # if so prints this string print "That's too many buses." # checks if buses are less than cars elif buses < cars: # if so prints this string print "Maybe we could take the buses." # if neither (buses = cars) else: # prints this string print "We still can't decide." # checks if people are greater than buses if people > buses: # if so prints this string print "Alright, let's just take the buses." # checks if either people are less than buses or the same else: # prints this string print "Fine, Let's stay home then."
true
cff2259fbf8e9b71c9cf246627600695c1baed45
JPoser/python-the-hardway
/Exercise 7/ex7st1.py
1,043
4.15625
4
# Learn Python The Hard Way. Exercise 7 Study Drill 1. # Copied by JPoser # prints string print "Mary had a little lamb." # prints string with string nested inside print "It's fleece was white as %s." % 'snow' # prints string print "And everywhere that mary went." # prints string 10 times print "." * 10 # what'd that do? # sets variable to string end1 = "C" # sets variable to string end2 = "h" # sets variable to string end3 = "e" # sets variable to string end4 = "e" # sets variable to string end5 = "s" # sets variable to string end6 = "e" # sets variable to string end7 = "B" # sets variable to string end8 = "u" # sets variable to string end9 = "r" # sets variable to string end10 = "g" # sets variable to string end11= "e" # sets variable to string end12 = "r" # whatch that comma at the end. try removing it to see what happens # prints concatenation of strings print end1 + end2 + end3 + end4 + end5 + end6 # prints concatenation of strings print end7 + end8 + end9 + end10 + end11 + end12
true
f4db9cf283618b2912702f42d61dca43e86f0504
JPoser/python-the-hardway
/Exercise 4/ex4st3.py
1,276
4.34375
4
# Learn Python The Hard Way, Exercise 4 Study Drill 3. # Copied by JPoser. # Assigns variable "cars" to the integer (in future written as int) 100 cars = 100 # Assigns variable "space_in_a_car" to the floating number 4.0 space_in_a_car = 4.0 # Assigns the variable "drivers" to int 30 drivers = 30 # Assigns the variable "passengers" to the int 90 passengers = 90 # Assigns the variable "cars_not_driven" to the subtraction of the variables "cars" and "drivers" cars_not_driven = cars - drivers # Assigns the variable "cars_driven" to the variable "drivers" cars_driven = drivers # Assigns the variable "carpool_capacity" to multiplication of the variables "cars_driven" and "space_in_a_car" carpool_capacity = cars_driven * space_in_a_car # Assigns the variable "average_passengers_per_car" to the division of the variables "passengers" and "cars_driven" average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "we have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car."
true
e821fa06ec048569e90cde1194aeb4faf15d10b4
RidaATariq/ITMD_413
/Assignment-4/HW_4/program-2/main.py
1,482
4.25
4
""" This program asks the user to enter two 3x3 matrices to be multiplied and then it gets the result. Name: Cristian Pintor """ matrixA = [] matrixB = [] print('Enter a 3x3 matrix for matrix A: ') for i in range(9): matrixA.append(eval(input())) print('Enter a 3x3 matrix for matrix B') for i in range(9): matrixB.append(eval(input())) print('Matrix A: ', matrixA) print('Matrix B: ', matrixB) # multiplying for i in matrixA: c_11 = (matrixA[0]*matrixB[0]) + (matrixA[1]*matrixB[3]) + (matrixA[2]*matrixB[6]) c_21 = (matrixA[3]*matrixB[0]) + (matrixA[4]*matrixB[3]) + (matrixA[5]*matrixB[6]) c_31 = (matrixA[6]*matrixB[0]) + (matrixA[7]*matrixB[3]) + (matrixA[8]*matrixB[6]) c_12 = (matrixA[0]*matrixB[1]) + (matrixA[1]*matrixB[4]) + (matrixA[2]*matrixB[7]) c_22 = (matrixA[3]*matrixB[1]) + (matrixA[4]*matrixB[4]) + (matrixA[5]*matrixB[7]) c_32 = (matrixA[6]*matrixB[1]) + (matrixA[7]*matrixB[4]) + (matrixA[8]*matrixB[7]) c_13 = (matrixA[0]*matrixB[2]) + (matrixA[1]*matrixB[5]) + (matrixA[2]*matrixB[8]) c_23 = (matrixA[3]*matrixB[2]) + (matrixA[4]*matrixB[5]) + (matrixA[5]*matrixB[8]) c_33 = (matrixA[6]*matrixB[2]) + (matrixA[7]*matrixB[5]) + (matrixA[8]*matrixB[8]) print('The multiplication of the matrices is: ') print(format(c_11, ',.1f'), format(c_12, ',.1f'), format(c_13, ',.1f')) print(format(c_21, ',.1f'), format(c_22, ',.1f'), format(c_23, ',.1f')) print(format(c_31, ',.1f'), format(c_32, ',.1f'), format(c_33, ',.1f'))
true
6f557ae80a05f830d801d159aa2e54c612e58ae3
RidaATariq/ITMD_413
/Assignment_15/cpintor_HW_15/question_17.1/main.py
2,109
4.375
4
import sqlite3 connection = sqlite3.connect('books.db') import pandas as pd # 1. Select all authors' last names from the authors # table in descending order output_1 = pd.read_sql("""SELECT last FROM authors ORDER BY last DESC""", connection) print('Question #1: \n', output_1) # 2. Select all book titles from the titles table in ascending order output_2 = pd.read_sql("""SELECT title FROM titles ORDER BY title ASC""", connection) print('Question #2: \n',output_2) # 3. output_3 = pd.read_sql("""SELECT first, last, title, copyright, ISBN FROM titles INNER JOIN authors ON authors.last = 'Deitel' AND authors.first = 'Harvey' ORDER BY title""", connection).head() print('Question #3: \n',output_3) # 4. Insert a new author into the authors table cursor = connection.cursor() cursor = cursor.execute("""INSERT INTO authors (first, last) VALUES ('Bill', 'Gates')""") output_4 = pd.read_sql('SELECT * FROM authors', connection) print('Question #4: \n',output_4) #5. # inserting isbn into author_ISBN table print('\ne. ** Inserting data pertaining to new author in author_ISBN and titles tables**') cursor.execute("""INSERT INTO author_ISBN (id, isbn) VALUES ('6', '1493379921')""") print(pd.read_sql('SELECT * FROM author_ISBN ORDER BY id ASC', connection)) #inserting data into titles table cursor.execute("""INSERT INTO titles (isbn, title, edition, copyright) VALUES ('1593279922', 'How to Write Your First Python Program', '1', '2020')""") print(pd.read_sql('SELECT * FROM titles ORDER BY title ASC', connection)) print('\n\nQuestion #5: ') print(pd.read_sql("""SELECT authors.id, titles.title, authors.last, authors.first, author_ISBN.isbn, titles.copyright FROM authors INNER JOIN author_ISBN ON authors.id = author_ISBN.id INNER JOIN titles ON author_ISBN.isbn = titles.isbn ORDER BY authors.id ASC""", connection))
true
61269f6c768d5965e50de89834b6d89fad9c88b1
RidaATariq/ITMD_413
/Assignment-2/Module-3_Lopping/while-loop-2.py
462
4.1875
4
''' This program demonstrates the concept of while loop. ''' import random # Generate a random number to be guessed number = random.randint(0, 100) print("Guess a magic number between 0 and 100") guess = -1 while guess != number: guess = eval(input("Enter your guess: ")) if guess == number: print("Yes the number is", number) elif guess > number: print("Your guess is too high") else: print("Your guess is too low")
true
3812633581de8a898f8d978cf0c7e589323d4b30
RobRoger97/test_tomorrowdevs
/cap3/63_Average.py
363
4.21875
4
#Read a value from user num = int(input("Enter a number: ")) sm=0.00 count=0 #Loop if num==0: print("Error message: the first number can't be 0") else: while num!=0: count=count+1 sm = sm+num num = int(input("Enter a number: ")) #Compute the average average=sm/count #Display the result print("The average is:",average)
true
8d68b11c78a261b452176bcf9dc7abd61732c276
RobRoger97/test_tomorrowdevs
/cap2/58_Is_It_a_Leap_Year.py
622
4.375
4
# Read the year from the user year = int(input("Enter a year: ")) # Determine if it is a leap year #Any year that is divisible by 400 is a leap year. if year % 400 == 0: isLeapYear = True #Of the remaining years, any year that is divisible by 100 is not a leap year. elif year % 100 == 0: isLeapYear = False #Of the remaining years, any year that is divisible by 4 is a leap year. elif year % 4 == 0: isLeapYear = True #All other years are not leap years. else: isLeapYear = False # Display the result if isLeapYear: print(year, "is a leap year.") else: print(year, "is not a leap year.")
true
31dca49e06b0a06e436dd8abed18510140e6ec16
RobRoger97/test_tomorrowdevs
/cap2/62_Roulette_Payouts.py
1,319
4.125
4
## # Display the bets that pay out in a roulette simulation. # from random import randrange # Simulate spinning the wheel, using 37 to represent 00 value = randrange(0, 38) if value == 37: print("The spin resulted in 00...") else: print("The spin resulted in %d..." % value) # Display the payout for a single number if value == 37: print("Pay 00") else: print("Pay", value) # Display the color payout # The first line in the condition checks for 1, 3, 5, 7 and 9 # The second line in the condition checks for 12, 14, 16 and 18 # The third line in the condition checks for 19, 21, 23, 25 and 27 # The fourth line in the condition checks for 30, 32, 34 and 36 if value % 2 == 1 and value >= 1 and value <= 9 or \ value % 2 == 0 and value >= 12 and value <= 18 or \ value % 2 == 1 and value >= 19 and value <= 27 or \ value % 2 == 0 and value >= 30 and value <= 36: print("Pay Red") elif value == 0 or value == 37: pass else: print("Pay Black") # Display the odd vs. even payout is no work to be performed. if value >= 1 and value <= 36: if value % 2 == 1: print("Pay Odd") else: print("Pay Even") # Display the lower numbers vs. upper numbers payout if value >= 1 and value <= 18: print("Pay 1 to 18") elif value >= 19 and value <= 36: print("Pay 19 to 36")
true
e8f9c0ab9af876319bcec91df8d79769920effc0
RobRoger97/test_tomorrowdevs
/cap5/ex110_Sorted_Order.py
382
4.375
4
#Read a integer from the user integ = int(input("Enter a integer: ")) # Start with an empty list lis=[] #While loop while integ!=0: lis+=[integ] print(lis) integ = int(input("Enter a integer: ")) #Sort the value of the list lis.sort() #Display the values in ascending order print("The values, sorted into ascending order, are:") for integ in lis: print(integ)
true
fad3b778a58587f27e8a349ab5195914ba9f25d1
RobRoger97/test_tomorrowdevs
/cap2/42_Note_to_Frequency.py
725
4.1875
4
#Note's frequency C4_f = 261.63 D4_f = 293.66 E4_f = 329.63 F4_f = 349.23 G4_f = 392.00 A4_f = 440.00 B4_f = 493.88 #Read the note name from user name = input ("Enter the two character note name, such as C4: ") #Store the note and its octave in separate variables note = name[0] octave = int(name[1]) #Get the frequency of the note, assuming it is in the fourth octave if note=="A": f = A4_f elif note=="B": f = B4_f elif note=="C": f = C4_f elif note=="D": f = D4_f elif note=="E": f = E4_f elif note=="F": f = F4_f elif note=="G": f = G4_f #Now adjust the frequency to bring it into the crrect octave freq = f/(2**(4-octave)) #Display the result print("The frequency of ", name, "is", freq)
true
93d7bdb71b4db9b716b7b5aa22ab1e821e1cb6e3
RobRoger97/test_tomorrowdevs
/cap3/75_Is_a_String_a_Palindrome.py
513
4.40625
4
# Read the string from the user line = input("Enter a string: ") is_palindrome = True i = 0 #While loop to scroll through the string while i < len(line) / 2 and is_palindrome: # If the characters do not match then mark that the string is not a palindrome if line[i] != line[len(line) - i - 1]: is_palindrome = False # Move to the next character i+=1 # Display a meaningful output message if is_palindrome: print(line, "is a palindrome") else: print(line, "is not a palindrome")
true
677e1fa22ecacc625f85aef5b2d586b202e0b9fe
muondu/datatypes
/megaprojects/strings/st4.py
429
4.125
4
print("Enter your name in small letters") a = input("Enter your first word of your name: ") print(a.upper()) b = input("Enter your second word of your name: ") print(b) c = input("Enter your third word of your name: ") print(c.upper()) d = input("Enter your fourth word of your name: ") print(d) e = input("Enter your fifth word of your name: ") print(e.upper()) f = input("Enter your sixth word of your name: ") print(f)
true
5766ba5c7fd8c06a386984124c24074d19f06764
sacheenanand/pythonbasics
/quick_sort.py
1,231
4.3125
4
#Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. #A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and #another array holds values greater than the pivot value. #Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. #This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are O(nLogn) and image.png(n2), respectively. #The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until all lists contains only one element. list = [3,1,2,4,5,3,5,6,7,1] def quick_sort(list, low, high): if low < high: p = partion(list, low, high) quick_sort(list, low, p-1) quick_sort(list, p+1, high) def partion(list, low, high): divider = low pivot = high for i in range(low, high): if list[i] < list[pivot]: list[i], list[divider] = list[divider], list[i] divider +=1 list[divider],list[pivot] = list[pivot],list[divider] return divider quick_sort(list, 0, 9) print("here you go", list)
true
58fbd02b4bd79c57b9ec7d5a52016ca6689bab8c
Judy-special/Python
/02-basic-201807/is_Palindrome.py
576
4.15625
4
# coding = utf8 def is_Palindrome(the_str): """ 本函数用来判别是否为回文字符串 """ l = len(the_str) - 1 n = int(l/2) if len(the_str) == 0: print("The String is Null") elif len(the_str) > 0: temp = [] for i in range(n): if the_str[i]==the_str[l-i]: temp.append("True") elif the_str[i] != the_str[l-i]: temp.append("False") if 'False' in temp: print("No,the string is not palindrome") else: print("Yse,the string is palindrome")
true
e343c335766ff26481a4daf445d7bf5615de2486
Pajace/coursera_python_miniproject
/miniproject2.py
2,442
4.125
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random # 1. initialize global variable num_range = 100 remaining_guesses = 7 user_guesses = 0 secret_number = random.randrange(0, num_range) # 2. helper function to start and restart the game def new_game(): global secret_number secret_number = random.randrange(0, num_range) print_new_game_message() def print_new_game_message(): print "New game. Range is from 0 to ", num_range print "Number of remaining guesses is ", remaining_guesses print "" def print_lose_message(): print "You ran out of guesses. The number was ", secret_number print "" def start_game_by_range(): if num_range == 100: range100() elif num_range == 1000: range1000() def is_number(number): try: int(number) return True except ValueError: return False def setGuessesRange(range, countOfGuesses): global num_range, remaining_guesses num_range = range remaining_guesses = countOfGuesses # 4. define event handlers for control panel def range100(): setGuessesRange(100, 7) new_game() def range1000(): setGuessesRange(1000, 10) new_game() def input_guess(guess): global remaining_guesses, user_guesses if not is_number(guess): print "Please input a valid integer\n" return user_guesses = int(guess) remaining_guesses = remaining_guesses - 1 print "Guess was ", user_guesses print "Number of remaining guesses is ", remaining_guesses if user_guesses == secret_number: print "Correct!\n" start_game_by_range() elif remaining_guesses == 0: print_lose_message() start_game_by_range() elif user_guesses < secret_number: print "Higher!\n" elif user_guesses > secret_number: print "Lower!\n" # 5. create frame frame = simplegui.create_frame("Guess the number", 200, 200) # 6. egister event handlers for control elements and start frame frame.add_button("Range is [0, 100)", range100, 200) frame.add_button("Range is [0, 1000)", range1000, 200) frame.add_input("Enter a guess", input_guess, 200) # 7. call new_game new_game() # always remember to check your completed program against the grading rubric
true
d4be5236a64fdc4114e017a4b5e65da20a4b6f18
aronaks/algorithms
/algorithms/gfg_arrays2.py
543
4.34375
4
def find_leaders(keys): """ Write a function that prints all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. """ keys_length = len(keys) all_leaders = [] leader = 0 for i in range(keys_length-1, -1, -1): if keys[i] > leader: leader = keys[i] all_leaders.append(leader) return all_leaders
true
e1dbe97738f28b03916540a49a6ebe0db0e25bbd
nicholas0417/python-tutorial
/data_types/product.py
238
4.15625
4
# Q1 num1 = int (input("please enter number1:")) num2 = int (input("please enter number2:")) product = num1 * num2 # If product is greater than 1000 if (product < 1000): print("The product is : " product) else: print(num1 + num2)
true
91cc8136c752f5397b51511012fe2be70a3993fd
AaronAikman/MiscScripts
/Py/AlgorithmsEtc/BuildingHeight.py
351
4.15625
4
# CalculateBuildingHeight.py # Aaron Aikman # Calculate height of a building based upon the inputted number of floors while True: numFloors = input("Enter a number of floors (returns cm):") if (numFloors == ""): break buildingHeight = ((3.1 * numFloors) + 7.75 + (1.55 * (numFloors / 30))) print buildingHeight * 100 print "\n"
true
2d635fb9dd499cd344039e1b980c938188e08b09
Gaurav715/DDS1
/main.py
2,596
4.28125
4
# Python program for implementation of BubbleSort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Python program for implementation of InsertionSort def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # Python program for implementation of MergeSort def mergeSort(arr): if len(arr) >1: mid = len(arr)//2 #Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves mergeSort(L) # Sorting the first half mergeSort(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i+=1 else: arr[k] = R[j] j+=1 k+=1 # Checking if any element was left while i < len(L): arr[k] = L[i] i+=1 k+=1 while j < len(R): arr[k] = R[j] j+=1 k+=1 # Python program for implementation of SelectionSort def selectionSort(arr): for i in range(len(arr)): # Find the minimum element in remaining minPosition = i for j in range(i+1, len(arr)): if arr[minPosition] > arr[j]: minPosition = j # Swap the found minimum element with minPosition temp = arr[i] arr[i] = arr[minPosition] arr[minPosition] = temp return arr # Example to test code above arr1 = [64, 34, 25, 12, 22, 11, 90, 123, 42134, 342,-2] # bubbleSort(arr1) # selectionSort(arr1) mergeSort(arr1) #selectionSort(arr1) print ("Sorted array is:") for i in range(len(arr1)): print (arr1[i]),
true
de3fa85ee012acb070b0023e2be345d43f3aab43
CaptainCrossbar/CodeWars
/(8) Is it a number?.py
348
4.1875
4
def isDigit(string): #Check to see if string is an integer try: int(string) return True #String was no an integer except: #Check to see if string is a float try: float(string) return True #String is no a valid integer or float except: return False
true
c1dbde41aa30ce350a1ef3266c92f8ec8cec96bd
melissav00/Python-Projects
/project_exercise2.py
479
4.1875
4
start = int(input("Pick a starting number for a list:")) end = int(input("Pick a ending number for a list:")) def generateNumbers(start,end): num_list=[] if start == end: print("Both values are equal to each other. Please input opposite values.") elif start > end: print("Enter a start values less than end.") while (start < end): start = start + 1 num_list.append(start) print(num_list) generateNumbers(start,end)
true
bdd47bd94d25de8b95debacc99fbed3fc14f294a
Moiz-khan/Piaic_Assignment01
/copiesof string.py
208
4.21875
4
#program to print copies of string str = input("Enter String: ") n = int(input("How many copies of String you need: ")) print(n, "copies of",str,"are ",end=" ") for x in range(1,n+1): print(str,end=" ")
true
5e48ffd4a519bf0a0a5e2f42f645f2ae37f9cb22
heis-divine/PythonCalculator
/main.py
1,309
4.28125
4
# Calculator project print("What Calculation would you like to perform?") print("1)Addition\n2)Subtraction\n3)Multiplication\n4)Division") choice = int(input("Enter preferred Option: ")) if choice == 1: print("Addition") num1 = int(input("Enter first number:")) num2 = int(input("Enter second number:")) total = num1 + num2 print(total) print("The sum of the two numbers entered are:", total) print("Thanks for using our calculator") elif choice == 2: print("Subtraction") num1 = int(input("Enter first number:")) num2 = int(input("Enter second number:")) total1 = num1 - num2 print("The difference of the two numbers entered are:" , total1) print("Thanks for using our calculator") elif choice == 3: print("Multiplication") num1 = int(input("Enter first number:")) num2 = int(input("Enter second number:")) total2 = num1 * num2 print("The product of the two numbers entered are:" , total2) print("Thanks for using our calculator") elif choice == 4: print("Division") num1 = int(input("Enter first number:")) num2 = int(input("Enter second number:")) total3 = num1 / num2 print("The quotient of the two numbers entered are:" , total3) print("Thanks for using our calculator")
true
75752fa8139a12de337fa40553785211469139d2
Zahidsqldba07/PythonPrac
/Time & Calendar.py
618
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import time import datetime import calendar # In[2]: ### Get the current date and time print(datetime.datetime.now()) # In[3]: ### Get just the current time print(datetime.datetime.now().time()) # In[4]: start = time.time() print("hello") end = time.time() print(end - start) # In[5]: #print calender of the given month,year yy = 2019 mm = 12 # display the calendar print(calendar.month(yy, mm)) # In[6]: print ("The calender of year 2019 is : ") print (calendar.calendar(2020, 3, 1, 2)) # year, width, height , spacing # In[ ]:
true
5e4f7196eece576d7a5cc69017c35eeee6056d75
Zahidsqldba07/PythonPrac
/Logic 1.py
2,303
4.21875
4
#!/usr/bin/env python # coding: utf-8 # # You and your date are trying to get a table at a restaurant. The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise the result is 1 (maybe). # # # In[1]: def date_fashion(you, date): if you <= 2 or date <=2: return 0 elif you >=8 or date >=8: return 2 else: return 1 date_fashion(5, 10) # # The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number. # # # In[2]: def love6(a, b): return a == 6 or b == 6 or a+b == 6 or abs(a-b) == 6 love6(6, 4) # # Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off". # # # In[4]: def alarm_clock(day, vacation): week_preset = "7:00" if not vacation else "10:00" weekend_preset = "10:00" if not vacation else "off" return week_preset if day not in [6,0] else weekend_preset alarm_clock(0, False) # # You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases # In[6]: def caught_speeding(speed, is_birthday): speeding = speed - (65 if is_birthday else 60) if speeding > 20: return 2 elif speeding > 0: return 1 else: return 0 caught_speeding(65, False) # In[ ]:
true
38c45a4fbd57093e586ed9c1fe820b958a1d0343
codevr7/samples
/one-bit_binary_adder.py
275
4.15625
4
#binary adder choices = ['0','1'] problem = input("select 2 numbers between 0 and 1(0,1)") if problem != '0' or problem != '1': print("binary adder cannot process numbers other than 1 and 0") if problem_1 != : print("binary adder cannot process numbers more than 1")
true
1b36b1abc616005a72e5b7bd72dbf081152b62e1
codevr7/samples
/odd_sort.py
536
4.28125
4
# A function for sorting only odd numbers from a list of mixed numbers def odd_sort(n): l = len(n)# The length of the input for i in range(0, l):# A range for 0 to length of input for j in range(i, l):# A second range for evaluating for each number if n[i]%2 != 0:# Evaluating each number, whether odd or not if n[j]%2 != 0:# Eval if n[i] > n[j]: n[i], n[j] = n[j], n[i] return n
true
3ece7ee246f9e1367949690c1c38ddabac94a198
pragyatwinkle06/Python_patterns_and_codes
/ZIGZAG PATTERN CHALLENGE3.py
1,149
4.40625
4
# Python3 ZIGZAG PATTERN CHALLENGE3 # Function to print any string # in zigzag fashion def zigzag(s, rows): # Store the gap between the major columns interval = 2 * rows - 2 # Traverse through rows for i in range(rows): # Store the step value for each row step = interval - 2 * i # Iterate in the range [1, N-1] for j in range(i, len(s), interval): # Print the character print(s[j], end = "") if (step > 0 and step < interval and step + j < len(s)): # Print the spaces before character # s[j+step] for k in range((interval - rows - i)): print(end = " ") # Print the character print(s[j + step], end = "") # Print the spaces after character # after s[j+step] for k in range(i - 1): print(end = " ") else: # Print the spaces for first and # last rows for k in range(interval - rows): print(end = " ") print() if __name__ == '__main__': # Given Input s = input("enter string: ") rows=int(input("enter a no")) # Function Call zigzag(s, rows) # enter no. of rows u want
true
6dbaeac22713d2537bc8eae746781641e8b0a86a
NoahNacho/python-solving-problems-examples
/Chapter7/Exercise1.py
308
4.28125
4
# Write a function to count how many odd numbers are in a list. # Base of function was taken from Chap6 Exercise14 def is_even(n): num = 0 for odd in n: if (odd % 2) == 0: pass else: num += 1 return num odd_list = [1, 2, 3, 4, 5] print(is_even(odd_list))
true
8cb6d0552df6cbd44d7462aa9a0fdc5b91f90474
denny61302/100_Days_of_Code
/Day19 Racing Game/main.py
1,371
4.1875
4
from turtle import Turtle, Screen import random colors = ["red", "yellow", "green", "blue", "black", "purple"] turtles = [] for _ in range(6): new_turtle = Turtle(shape="turtle") turtles.append(new_turtle) is_race_on = False screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win?") if user_bet: is_race_on = True index = 0 for turtle in turtles: turtle.penup() turtle.color(colors[index]) turtle.goto(x=-230, y=-170 + index * 50) index += 1 while is_race_on: for turtle in turtles: if turtle.xcor() > 230: is_race_on = False winner_color = turtle.pencolor() if winner_color == user_bet: print("You win") else: print(f"You lose, the winner is {winner_color} turtle") turtle.forward(random.randint(0, 10)) # def forward(): # turtle.forward(10) # # # def backward(): # turtle.backward(10) # # # def clock(): # turtle.right(5) # # # def counter_clock(): # turtle.left(5) # # # def reset(): # turtle.reset() # # # screen.listen() # screen.onkey(key="w", fun=forward) # screen.onkey(key="s", fun=backward) # screen.onkey(key="a", fun=counter_clock) # screen.onkey(key="d", fun=clock) # screen.onkey(key="c", fun=reset) screen.exitonclick()
true
c0f64d4b90693d45bfe23da72c3cba4a2632bd61
darrenredmond/programming-for-big-data_10354686
/CA 1/TestCalculator.py
2,884
4.15625
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 16 19:08:49 2017 @author: 10354686 """ # Import the Python unittest functions import unittest # Import the functions defined in the 'Calculator' file from Calculator import * # Create a class which extends unittest.TestCase class TestCalculator(unittest.TestCase): # This function is defined to test the add function created def testAdd(self): self.assertEqual(add(2,2),4) self.assertEqual(add(5,3),8) self.assertEqual(add(4,0),4) # This function is defined to test the subtract function created def testSubtract(self): self.assertEqual(subtract(2,2),0) self.assertEqual(subtract(5,3),2) self.assertEqual(subtract(4,0),4) # This function is defined to test the multiply function created def testMultiply(self): self.assertEqual(multiply(2,2),4) self.assertEqual(multiply(5,3),15) self.assertEqual(multiply(4,0),0) # This function is defined to test the divide function created def testDivide(self): # 4 / 1 = 4 # 4 / 2 = 2 # 2 / 2 = 1 # 0 / 1 = 0 # 5 / 4 = 1.25 # Divide by zero - return error self.assertEqual(divide(4,1),4) self.assertEqual(divide(4,2),2) self.assertEqual(divide(2,2),1) self.assertEqual(divide(0,1),0) self.assertEqual(divide(5,4),1.25) self.assertEqual(divide(5,0),'error') # This function is defined to test the exponent function created def testExponent(self): self.assertEqual(exponent(2,2),4) self.assertEqual(exponent(2,3),8) self.assertEqual(exponent(3,3),27) # This function is defined to test the square root function created def testSqrroot(self): self.assertEqual(sqrroot(4),2) self.assertEqual(sqrroot(16),4) self.assertEqual(sqrroot(36),6) # This function is defined to test the tan function created def testTan(self): self.assertEqual(tan(0),0) self.assertEqual(tan(0.5),0.5463024898437905) self.assertEqual(tan(1),1.5574077246549023) # This function is defined to test the cos function created def testCos(self): self.assertEqual(cos(0),1) self.assertEqual(cos(0.5),0.8775825618903728) self.assertEqual(cos(1),0.5403023058681397) # This function is defined to test the sin function created def testSin(self): self.assertEqual(sin(0),0) self.assertEqual(sin(0.5),0.479425538604203) self.assertEqual(sin(1),0.8414709848078965) # This function is defined to test the factorial function created def testFactorial(self): self.assertEqual(factorial(5),120) self.assertEqual(factorial(8),40320) self.assertEqual(factorial(6),720) if __name__ == '__main__': unittest.main()
true
af68068c121d2eeebb9a1f1e1daaadb89af9b634
abby-does-code/machine_learning
/quiz2.py
2,781
4.5
4
# Start# """You are to apply skills you have acquired in Machine Learning to correctly predict the classification of a group of animals. The data has been divided into 3 files. Classes.csv is a file describing the class an animal belongs to as well as the name of the class. The class number and class type are the two values that are of most importance to you. animals_train.csv download - is the file you will use to train your model. There are 101 samples with 17 features. The last feature is the class number (corresponds to the class number from the classes file). This should be used as your target attribute. However, we want the target attribute to be the class type (Mammal, Bird, Reptile, etc.) instead of the class number (1,2,3,etc.). animals_test.csv download - is the file you will use to test your model to see if it can correctly predict the class that each sample belongs to. The first column in this file has the name of the animal (which is not in the training file). Also, this file does not have a target attribute since the model should predict the target class. Your program should produce a csv file that shows the name of the animal and their corresponding class as shown in this file -predictions.csv """ import pandas as pd import csv animal_class = pd.read_csv("animal_classes.csv") X = pd.read_csv("animals_train.csv") X.columns = [ "hair", "feathers", "eggs", "milk", "airborne", "aquatic", "predator", "toothed", "backbone", "breathes", "venomous", "fins", "legs", "tail", "domestic", "catsize", "class_number", ] y = X["class_number"] X = X.drop(columns="class_number") from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier() knn.fit(X, y) test = pd.read_csv("animals_test.csv") test_data = test.drop(columns="animal_name") # feed everything except the target predicted = knn.predict(X=test_data) print(predicted[:10]) # predicted = [animal_class.target_names[i] for i in predicted] class_number = animal_class["Class_Number"] animal_name = test["animal_name"].to_list() class_names = animal_class["Class_Type"] print(class_names[:10]) # predicted = [class_number[i] for i in predicted] # print(predicted) name_num_dict = { 1: "Mammal", 2: "Bird", 3: "Reptile", 4: "Fish", 5: "Amphibian", 6: "Bug", 7: "Invertebrate", } predicted = [name_num_dict[x] for x in predicted] print(predicted[:10]) """match the animal name in test data to an animal name in the list in animal_classes based on the class number""" i = 0 with open("model_predictions_file.csv", "w") as model_file: for p in predicted: line = animal_name[i] + "," + p + "\n" i += 1 model_file.write(line)
true
b883911a98cd09445da07329c1cdca5ebb24391e
joedo29/DataScience
/MatplotlibPractices.py
733
4.25
4
import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 100) y = x*2 z = x**2 # Exercise 1: Create a single plot fig1 = plt.figure() ax1 = fig1.add_axes([0.1, 0.1, 0.8, 0.8]) ax1.set_xlabel('X') ax1.set_ylabel('Y') ax1.set_title('Outer Plot') ax1.plot(x,y) # Exercise 2: plot inside a plot ax2 = fig1.add_axes([0.25, 0.55, 0.2, 0.2]) # left - bottom - width - height ax2.set_xlabel('X') ax2.set_ylabel('Y') ax2.set_title('Inner Plot') ax2.plot(x, z, color='red') # Exercise 3: create subplot 2 row by 2 columns fig3, ax3 = plt.subplots(nrows=2, ncols=2, figsize=(12, 6)) ax3[0, 0].plot(x, y, linestyle='--', color='blue', linewidth=5) ax3[1, 1].plot(x, z, color='red', linewidth=10) # plt.tight_layout() plt.show()
true
737baea08cfb3099f127d972318818e92f915437
mattyice89/LearnPythonTheHardWay
/ex19.py
1,243
4.15625
4
# defining the argument Cheese and crackers and naming your variables def cheese_and_crackers(cheese_count,boxes_of_crackers): # printing out the first variable, named "cheese_count" print(f"You have {cheese_count} cheeses!") # printing out the second variable, named "boxes_of_crackers" print(f"You have {boxes_of_crackers} boxes of crackers!") # some bullshit print("Man that's enough for a party!") # more bullshit print("Get a blanket.\n") # loading the exact numbers you want into your function print("We can just give the function numbers directly:") cheese_and_crackers(20, 30) # you can create new variables and call them in your function print("OR, we can use variables from our script:") amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese,amount_of_crackers) # using math instead of variables - note that this doesn't then Get # stored as the variables that we defined in the previous step print("We can even do math inside too:") cheese_and_crackers(10 + 20, 5 + 6) # prints using the variables we defined two steps ago plus some math print("And we can combine the two, variables and math:") cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
true
96c2ccd7e834bb194bb50973e772580784ee9455
trustme01/PythonCrashCourse2
/ch_3/cars.py
753
4.59375
5
# Sorting a list PERMANENTLY with the sort() method. # Alphabetically: cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) # Reverse alphabetically: cars.sort(reverse=True) print(cars) # Sorting a list TEMPORARILY with the sort() method. cars2 = ['bmw', 'audi', 'toyota', 'subaru'] print('\nHere is the original list: ') print(cars2) print('\nHere is the sorted (alphabetical) list: ') print(sorted(cars2)) print('\nHere is the original list again: ') print(cars2) # Reverse alphabetically: print('\nHere is the list reversed in alphabetical order: ') print(sorted(cars2, reverse=True)) # Printing a List in Reverse Order # reverse() method cars3 = ['bmw', 'audi', 'toyota', 'subaru'] print(cars3) cars3.reverse() print(cars3)
true
9be69557321c8e1c498e26371acb00e06fc3bad5
MDCGP105-1718/portfolio-S191617
/ex8.py
730
4.25
4
portion_deposit = 0.20 current_savings = 0 r = 0.04 monthly_interest = current_savings*(r/12) monthly_salary= annual_salary/12 total_cost = float(input("Total cost of the house")) annual_salary= float(input("Enter the starting annual salary:")) portion_saved= float(input("How much money do you want to save?")) semi_annual_raise=float(input("By what proportion does you salary increase every six months?")) portion_deposit = total_cost*portion_deposit months = 0 while current_savings < total_cost*portion_deposit: current_savings += current_savings*(r/12) current_savings += monthly_salary * portion_saved months += 1 monthly_salary += monthly_salary * (semi_annual_raise/12) print("Number of months:", months)
true
2288678a651b13e959bcb43c28771c64a2ec3dd8
amey-kudari/NN_nLines
/I_am_trask/basic-python-network/2-layer-simple.py
2,282
4.15625
4
""" code taken from "https://iamtrask.github.io/2015/07/12/basic-python-network/" I learnt about neural networks from here, but I feel this is a little complicated as it needs you to actually compute the matricies on paper to see what is happening. I made a simpler model that isnt full batch training, and in my opinion, its easier to understand for a beginner who started off like me :) Also, the reason I find this easy is because I first learnt about neural networks from 3blue1brown, and my model is based on that. """ import numpy as np x=np.array([[1,1,1], [1,0,1], [0,0,1], [0,1,1]]) y=np.array([[1,1,0,0]]).T np.random.seed(1) # effectively, this is the neural network. syn=2*np.random.random((3,1))-1 # mean 0 def sig(x): return 1/(1+np.exp(-x)) def der(x): return x*(1-x) syn0 = np.array(syn) for it in range(1000): tsyn0 = np.array(syn0) serror = [] for i in range(len(x)): # layer 0, in this case is x[i], # layer 1, is the output layer, computed as # sig(x[i].syn0) for ith input. # layer 1 is a simple single node. """ neural network in this model: layer 0 | layer 1 x[i][0]___ \ tsyn[0] \ x[i][1]----tsyn[1] ========> l1 / tsyn[2] / x[i][2]--- """ error = y[i]-sig(np.dot(x[i],syn0)) serror.append(error[0]) dl = error*der(sig(np.dot(x[i],syn0))) tsyn0 += np.array([dl[0]*x[i]]).T # comment following line to get full batch training. syn0 = tsyn0 # the exact same model, just that back weights get # updated once per batch serror = np.array(serror) syn0 = tsyn0 l0=x l1=sig(np.dot(l0,syn)) error=y-l1 dl=error*der(l1) syn+=np.dot(l0.T,dl) #print(error.T) #print(dl.T) #print(np.dot(l0.T,dl)) print(syn0.T,syn.T) print(serror,error.T) while True: print("enter array to predict : ") tp = np.array([int(x) for x in input().split()]) print("my model , trask's model") print(float(sig(np.dot(tp,syn0))),float(sig(np.dot(tp,syn))))
true
eb48a58c8578f145a0b9a892c5b4efb100314fdd
Ridwanullahi-code/basic-python
/exercise1.py
313
4.4375
4
# write a python program which accepts the users's first and last name # and print them in reverse order with space between them # assign first name value first_name = 'Ridwanullahi' last_name = 'Olalekan' # To display the input values print(f'{last_name} {first_name}') print(name) print("school")
true
181165441ccf08e506b38f64ad9b5dea8de93f33
jesusdmartinez/python-labs
/14_list_comprehensions/14_04_fish.py
277
4.15625
4
''' Using a listcomp, create a list from the following tuple that includes only words ending with *fish. Tip: Use an if statement in the listcomp ''' fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus') list = [w for w in fish_tuple if w[-4:] == 'fish'] print(list)
true
fef717e2f35131316bf6f6d9bfd2b4f69df91e53
jesusdmartinez/python-labs
/03_more_datatypes/1_strings/03_04_most_characters.py
445
4.40625
4
''' Write a script that takes three strings from the user and prints the one with the most characters. ''' string1 = str(input("please input a string1")) string2 = str(input("please input a string2")) string3 = str(input("please input a string3")) len1 = len(string1) len2 = len(string2) len3 = len(string3) big = max(len1, len2, len3) if big == len1: print(string1) if big == len2: print(string2) if big == len3: print(string3)
true
1c6d7f8e10eee6f71804df3c4847cacb24e60966
jesusdmartinez/python-labs
/13_aggregate_functions/13_03_my_enumerate.py
333
4.25
4
''' Reproduce the functionality of python's .enumerate() Define a function my_enumerate() that takes an iterable as input and yields the element and its index ''' def my_enumerate(): my_num = input("create a list of anything so I can enumerate") new_num = my_num.split() print(list(enumerate(new_num))) my_enumerate()
true
347b7a7baabf1a8713e4a30df0bbc95ed1c179b0
ankitpatil30/Ankit_Python_Projects
/Python_Assignments/Task 4/11.py
592
4.125
4
# TASK FOUR # TRADITIONAL FUNCTIONS,ANONYMOUS FUNCTIONS & # HIGHER ORDER FUNCTIONS # 11. Write a program which uses map() and filter() to make a list whose elements are squares of even # numbers in [1,2,3,4,5,6,7,8,9,10]. # Hints: Use filter() to filter even elements of the given listUse map() to generate a list of squares of the # numbers in the filtered list. Use lambda() to define anonymous functions. # result = filter(lambda x: x % 2 == 0, range(1, 11)) # print(list(result)) square = map(lambda z: z ** 2, filter(lambda x: x % 2 == 0, range(1, 11))) print(list(square))
true
b8d6cefaa900afdff0cb72b063f2b8d3f2e55f38
ankitpatil30/Ankit_Python_Projects
/Python_Assignments/Task 2/4.py
499
4.15625
4
#TASK TWO #OPERATORS AND DECISION MAKING STATEMENT #4. Write a program in Python to break and continue if the following cases occurs: #If user enters a negative number just break the loop and print “It’s Over” #If user enters a positive number just continue in the loop and print “Good Going” x = int(input("Enter a number: ")) while True: if x < 0: print("It's over") break else: print("Good Going") x = int(input("Enter a number: "))
true
7e0b5ce3a86eae805fad3f1de40b0340c8978032
ankitpatil30/Ankit_Python_Projects
/Python_Assignments/Task 1/4.py
263
4.34375
4
#TASK ONE NUMBERS AND VARIABLES #4. Write a program that takes input from the user and prints it using both Python 2.x and Python 3.x Version. color = raw_input("Enter the color name: ") #print(color) color = input("Enter the colour name: ") print(color)
true
5154b91ee876350111fd6f0a8c35d268798ee742
ankitpatil30/Ankit_Python_Projects
/Python_Assignments/Task 4/9.py
624
4.34375
4
# TASK FOUR # TRADITIONAL FUNCTIONS,ANONYMOUS FUNCTIONS & # HIGHER ORDER FUNCTIONS # 9. Write a function called showNumbers that takes a parameter called limit. It should print all the # numbers between 0 and limit with a label to identify the even and odd numbers. # Sample input: show Numbers(3) (where limit=3) # Expected output: # 0 EVEN # 1 ODD # 2 EVEN # 3 ODD def showNumbers(limit): for i in range(0, limit+1): if i % 2 == 0: print(i, "EVEN") elif i % 2 != 0: print(i, "ODD") return 'Null' x = int(input("Enter the limit: ")) print(showNumbers(x))
true
4fcadc2b4105a17dc95f54cca290644e3436b75a
ujwalnitha/stg-challenges
/learning/basics12_number_converter_class.py
1,108
4.15625
4
'''' This file is to wrap number to words code in a class Reference: https://www.w3schools.com/python/python_classes.asp If we have to use a method from Class, outside calling file -we have to import the class in calling file -create an object and call function -if it is a static function, call ClassName.function_name() This method will just digits to words, not to a number sentence wrt to digit place ''' class NumberToWordsClass: def get_number_in_word(self, input_number=0): number_words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] # Each item in list hs index starting from 0, so number_words[2] will return "Two" in this case # using conversion to string to tokenize number_string = str(input_number) number_sentence = "" for x in number_string: digit = int(x) # Convert to number word = number_words[digit] print(word) # From list, get corresponding word number_sentence = number_sentence + number_words[digit] + " " return number_sentence
true
289cc536fb1d4a594155fd8f2ae37bb669feba57
vishwasanavatti/Interactive-Programming-with-python
/Interactive Programming with python/second_canvas.py
397
4.21875
4
# Display an X ################################################### # Student should add code where relevant to the following. import simplegui # Draw handler def draw(canvas): canvas.draw_text("X",[96, 96],48,"Red") # Create frame and assign callbacks to event handlers frame=simplegui.create_frame("Test", 200, 200) frame.set_draw_handler(draw) # Start the frame animation frame.start()
true
fd503ae0aae52dff9f8d209d72ff86af9943ec63
j0sht/checkio
/three_words.py
467
4.21875
4
# You are given a string with words and numbers separated by whitespaces. # The words contains only letters. # You should check if the string contains three words in succession. import re def checkio(s): return re.search(r'[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+', s) != None print(checkio("Hello World hello") == True) print(checkio("He is 123 man") == False) print(checkio("1 2 3 4") == False) print(checkio("bla bla bla bla") == True) print(checkio("Hi") == False)
true
c2991ed8c969b799c5458bac865e478122ec04af
panmari/nlp2014
/ex1/task3.py
334
4.15625
4
#!/usr/bin/python3 print("Please enter an integer") try: input_int = eval(input()) except NameError as e: print("Oops, that was not an integer!") exit(1) print("The first {} numbers of the fibonacci sequence are: ".format(input_int)) fib = [1,1] for i in range(input_int): fib.append(fib[-1] + fib[-2]) print(fib)
true
52d504ec91089e3b0eb747b99bf580e08883dc73
cesarg01/AutomateBoringPythonProjects
/collatz.py
973
4.4375
4
# This program take any natural number n. If n is even, divide it by 2 to get n/2, # if n is odd multiply it by 3 and add 1 to obtain 3n+1. Repeat the process indefinitely. # The conjecture is that no matter what number you start with, you will always eventually reach 1. # This is known as the Collatz conjecture. def collatz(number): """ # Take the user's input and apply the Collatz conjecture """ if number % 2 == 0: print(number // 2) return number // 2 elif number % 2 == 1: print(3 * number + 1) return 3 * number + 1 # Keep asking the user for a natural number until they input a natural number. while True: try: user_input = int(input('Please enter a number: \n')) break except ValueError: print('Error: Enter a integer') # Save the first collatz value value = collatz(user_input) # Keep calling collatz() until value becomes 1 while value != 1: value = collatz(value)
true
729f00cf4e463f39588ac965b873b52ba9baf5c4
CWMe/Python_2018
/Python_Learn_Night/Python_Dictionaries.py
729
4.46875
4
# Dictionaries in Python # { } # Map data type in Python # key : value paris for data. my_dictionary = {"name": "CodeWithMe", "location": "library", "learning": "Python"} # dictionaries may not retain the order in which they were created (before python 3.6.X). # print(my_dictionary) # accessing VALUES from a dictionary. print(my_dictionary["learning"]) # we can add new key value pairs. my_dictionary["date"] = "April" del my_dictionary["date"] # only 1 value per key # the keys must be IMMUTABLE (strings, numbers, or tuples) # useful methods for dictionaries # .items() # .keys() # .values() for key in my_dictionary.keys(): if key == "location": continue else: print(key, my_dictionary[key])
true
ac4062b52a08a61400ae7eb41b1554b907b23887
thewchan/python_oneliner
/ch3/lambda.py
637
4.28125
4
"""Lambda function example. Create a filter function that takes a list of books x and a minimum rating y and returns a list of potential bestsellers that have higher than minimum rating, y' > y. """ import numpy as np books = np.array([['Coffee Break Numpy', 4.6], ['Lord of the Rings', 5.0], ['Harry Potter', 4.3], ['Winnie-the-Pooh', 3.9], ['The Clown of God', 2.2], ['Coffee Break Python', 4.7]]) predict_bestseller = (lambda x, y: x[x[:, 1].astype(float) > y])(books, 3.9) print(books) print('Predicted bestsellers:') print(predict_bestseller)
true
14f266de9648b45e70a6d58b35e3f44be4611047
Adriana-ku06/programming2
/pythom/exercise26.py
2,959
4.125
4
#Adriana ku exercise 26 from sys import argv print("How old are you?", end=' ') age = input() print("How tall are you?", end=' ') tall=input() #undeclared tall variable print("How much do you weigh?", end=' ')#first error missing closing parentheses weight = input() print(f"So, you're {age} old, {tall} height and {weight} heavy.")#variable declaration error script, filename = argv #error. import from argv txt = open(filename)#variable write error print(f"Here's your file {filename}:") print(txt.read())#variable write error is txt print("Type the filename again:") file_again = input("> ") txt_again = open(file_again) print(txt_again.read())#function call error is "." no " _" print("Let's practice everything.")#error two, single quotes in a print print("You \d need to know \'bout escapes with \\ that do \n newlines and \t tabs.")#error three, line break and single quotes poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print("--------------")#error 4 missing closing quote print(poem) print("--------------")#error 5, a start quote is required five = 10 - 2 + 3 - 6 #error 6 sign without variable to subtract print(f"This should be five: {five}") def secret_formula (started): #error 8, missing ":" in the function declaration jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 # error 9, missing division operation symbols return jelly_beans, jars, crates start_point = 10000 beans, jars, crates = secret_formula(start_point) # remember that this is another way to format a string print("With a starting point of: {}".format(start_point)) # it's just like with an f"" string print(f"We'd have {beans} beans, {jars} jars and {crates} crates.") start_point = start_point / 10 print("We can also do that this way:") formula = secret_formula(start_point)##variable write error # this is an easy way to apply a list to a format string print("We'd have {} beans, {} jars, and {} crates.".format(*formula)) people = 20 cats = 30 ##variable write error dogs = 15 if people < cats: print ("Too many cats! The world is doomed!") #Error 10, parenthesis in missing print if people < cats: print("Not many cats! The world is saved!") if people < dogs: print("The world is drooled on!") if people > dogs: ##error 11, missing ":" in the declaration print("The world is dry!") dogs += 5 if people >= dogs: print("People are greater than or equal to dogs.") if people <= dogs:#error 12, missing ":" in the function declaration print("People are less than or equal to dogs.") #error 8, missing " in the function declaration if people == dogs: #error 13, missing "==" in the function declaration print("People are dogs.")
true
b7d01a00f0161216a6e5205b31638c9a8ac0a8ca
DavidM-wood/Year9DesignCS4-PythonDW
/CylinderVolCon.py
377
4.21875
4
import math print("This program calculates the volume of") print("a cylinder given radius and height") r = input("what is the radius: ") r = float(r) h = input("what is the height: ") h = float(h) v = math.pi*r*r*h v = round(v,3) print("Given") print(" radius = ",r," units") print(" height = ",h," units") print("The volume is: ",v," units cubed") print("END PROGRAM")
true
1a49be8a93de2ed7e8f6136933bcb194d62c168a
DavidM-wood/Year9DesignCS4-PythonDW
/LoopDemo.py
1,509
4.25
4
#A loop is a programjnf structure that can repeat a section of code. #A loop can run the same coede exactly over and over or #with domr yhought it can generate a patter #There are two borad catagories of loops #Conditional loops: These loop as long as a conditon is true #Counted Loops (for): These loop usikng a counter to keep teack of how many the loop has run # you can use any loop in any situation,but usually from a design #perspectie there is a better loop in terms of coding #If you know in advance how many times a loop should run a COUNTED LOOP \ #is usually the better choice. #If you don't know how many times a loop should run a CONDITIONAL LOOP #is usually the better choice print("**************************************************************************") #TAKING INPUTS word = "" #We have to declaire and inialize word so it fails the while loop #A while loop evaluates a condition when it is first reached.while #If the condition is true it enters the loop block while len(word) <6 or word.isalpha() == False: #Loop block word = input("Please input a word longer than 5 letters: ") if len(word) <6: print("Buddy, I said more than 5 letters ") if (word.isalpha() == False): print("Buddy I said a real word") #When we reach the bottom of the loop block we check the condtion #again. If it is true, we g back to the top of the block and run it again print(word+" is a seriosly long word!") #CAUTION: DO NOT USE WHILE LOOPS TO CONTROL INPUT WITH GUI PROGRAMS
true
9b7fa70f9b7c0cf967d63a5ea24afdaa38e5acdd
shach934/leetcode
/leet114.py
974
4.21875
4
114. Flatten Binary Tree to Linked List Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if root is None: return None dummy = TreeNode(0) tail = dummy stack = [] while stack or root: while root: tail.left = None tail.right = root tail = tail.right stack.append(root.right) root = root.left root = stack.pop() root = dummy.right
true
5cfb176a07bdb5473c6317586573525306cba589
shach934/leetcode
/leet403.py
2,213
4.1875
4
403. Frog Jump A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit. If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction. Note: The number of stones is ≥ 2 and is < 1,100. Each stone's position will be a non-negative integer < 231. The first stone's position is always 0. Example 1: [0,1,3,5,6,8,12,17] There are a total of 8 stones. The first stone at the 0th unit, second stone at the 1st unit, third stone at the 3rd unit, and so on... The last stone at the 17th unit. Return true. The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Example 2: [0,1,2,3,4,8,9,11] Return false. There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. 动态规划做的,也不算慢,超过了百分之五十的。可能dfs会更快一些吧。 class Solution(object): def canCross(self, stones): """ :type stones: List[int] :rtype: bool """ stone = {} for idx, pos in enumerate(stones): stone[pos] = idx step = [set() for i in range(len(stones))] step[0].add(0) for i in range(len(stones)): for j in step[i]: if stones[i]+j+1 in stone: step[stone[stones[i]+j+1]].add(j+1) if j-1>0 and stones[i]+j-1 in stone: step[stone[stones[i]+j-1]].add(j-1) if stones[i]+j>0 and stones[i]+j in stone: step[stone[stones[i]+j]].add(j) return True if len(step[-1]) else False
true
65dc7d8c342a8da41493e7dfc1459e1d468359d6
Larry-Volz/python-data-structures
/17_mode/mode.py
1,038
4.21875
4
def mode(nums): """Return most-common number in list. For this function, there will always be a single-most-common value; you do not need to worry about handling cases where more than one item occurs the same number of times. SEE TEACHER'S SOLUTION He uses a dictionary, {}.get(num, 0)+1 to ad them up then max()... convoluted but clever - worth seeing a different way to do it """ mode = 0 for ea in nums: if nums.count(ea) > nums.count(mode): mode = ea return mode print("1 = ",mode([1, 2, 1])) print("2 = ",mode([2, 2, 3, 3, 2])) #Teacher's solution (worth reviewing): # for num in nums: # counts[num] = counts.get(num, 0) + 1 #0 is default - adds one if none exist # # returns {2:3, 3:2} # # find the highest value (the most frequent number) # max_value = max(counts.values()) # # now we need to see at which index the highest value is at # for (num, freq) in counts.items(): # if freq == max_value: # return num
true
843b0e4e5ae83c783df4ddb4518f56bd974a1ccf
abigailshchur/KidsNexus
/hangman_complete.py
2,609
4.125
4
import random # we need the random library to pick a random word from list # Function that converts a list to a string split up be delim # Ex) lst_to_str(["a","b","c"],"") returns "abc" # Ex) lst_to_str(["a","b","c"]," ") returns "a b c" # Ex) lst_to_str(["a","b","c"],",") returns "a,b,c" def lst_to_str(lst, delim): return delim.join(lst) # Function th def replace_with_input(lst_current_guess, user_input, chosen_word): for i in range(len(chosen_word)): if chosen_word[i] == user_input: lst_current_guess[i] = chosen_word[i] return lst_current_guess # Opening text file with 1000 words text_file = open("words.txt", "r") # Making a list of words from that file words = text_file.read().split('\n') # picking random index in list index = random.randint(0, len(words)-1) # picking word chosen_word = words[index] len_chosen_word = len(chosen_word) print("The chosen word has " + str(len_chosen_word) + " characters") # setting up difficulty of game num_guesses = 12 #starting game game_over = False guessed_letters = [] guessed_words = [] player_current_guess = ["?"]*len_chosen_word while (not game_over): print("********************** PLAYER TURN **********************") print("You have " + str(num_guesses) + " guesses left") print("Here are all the characters you guessed so far: " + lst_to_str(guessed_letters, ',')) print("Here are all the words you guessed so far: " + lst_to_str(guessed_words, ',')) print("Your current guess is: " + lst_to_str(player_current_guess, '')) valid_user_input = False while(not valid_user_input): user_input = raw_input("What is your guess?\n") if len(user_input) == 1: valid_user_input = True have_letter_guesses = True player_current_guess = replace_with_input(player_current_guess, user_input, chosen_word) guessed_letters.append(user_input) print(lst_to_str(player_current_guess, '')) elif len(user_input) == len_chosen_word: valid_user_input = True if user_input == chosen_word: player_current_guess = chosen_word.split("(?!^)") else: print("Incorrect Guess") guessed_words.append(user_input) else: print("Invalid input (either 0 characters or too long)") # Handle game over details num_guesses = num_guesses - 1 if (sum([i=='?' for i in player_current_guess]) == 0): print("*********************** GAME OVER ***********************") print("You did it!!! the word was " + chosen_word) game_over = True if num_guesses == 0 and not game_over: print("*********************** GAME OVER ***********************") print("You lost :( the word was " + chosen_word) game_over = True
true
6b45fe344565cb148d4b0baa4b3ed2b6fe75d583
heasleykr/Algorithm-Challenges
/recursion.py
843
4.25
4
# Factorials using recursion def fact(n): # base. If n=0, then n! = 1 if n == 0: return 1 # else, calculate all the way until through return n*fact(n-1) # one liner # return 1 if not n else n*fact(n-1) def fact_loop(n): # base case return n if 0 # if n == 0: # return n # else: sum_ = n # else, calculate all the way until through while n != 1: n = n-1 sum_ *= n return sum_ #Fibonacci sequence. Sum of previous two numbers. def fib(n): #base case if n < 2: return n #Calculate Fn return fib(n-1) + fib(n-2) #homework TODO: How to cut this in half? store previous calculations #homework TODO: Turn fibonaci into iterative fn. if __name__ == '__main__': # print(fact(6)) print(fact_loop(6))
true
f374c8b57722d4677cbf9cc7cde251df8896b33d
sreerajch657/internship
/practise questions/odd index remove.py
287
4.28125
4
#Python Program to Remove the Characters of Odd Index Values in a String str_string=input("enter a string : ") str_string2="" length=int(len(str_string)) for i in range(length) : if i % 2 == 0 : str_string2=str_string2+str_string[i] print(str_string2)
true
a2807475320a5bb3849a943dbe5dd9f9331254ed
sreerajch657/internship
/practise questions/largest number among list.py
259
4.34375
4
#Python Program to Find the Largest Number in a List y=[] n=int(input("enter the limit of list : ")) for i in range(0,n) : x=int(input("enter the element to list : ")) y.append(x) y.sort() print("the largest number among list is : %d "%(y[-1]))
true
fdd72acf5565bdee962fed5471249461843d01ab
Neil-C1119/Practicepython.org-exercises
/practicePython9.py
1,511
4.28125
4
# This program is a guessing game that you can exit at anytime, and it will # keep track of the amount of tries it takes for the user to guess the number # Import the random module import random # Define the function that returns a random number def random_num(): return random.randint(1, 10) # Self explanatory print("-----The Random Number Game!-----") print("\nType 'exit' at any time to quit.") # Set the random number number = random_num() # Prepare the userGuess and tries variables userGuess = 0 tries = 0 # A loop that runs while the user's guess isn't the number AND their answer isn't exit while userGuess != number and userGuess != "exit": # Get the user's guess userGuess = input("Guess my number between 1 and 9. . . :") # If the user types exit end the loop if userGuess.lower() == "exit": break # If the guess is too high. . . if int(userGuess) > number: print("Try a little lower") # Add a try tries += 1 # If the guess is too low. . . elif int(userGuess) < number: print("It's higher than that") # Add a try tries += 1 # If the guess is correct. . . elif int(userGuess) == number: # Tell the user it is correct and show them how many tries it took print("That's right! It took you", tries,"tries!\n\n") # Reset the random number number = random_num() # Reset the user's tries tries = 0
true
2c67dd011e851c1e79a23004908cf69bc2c34607
ifegunni/Cracking-the-coding-interview
/arrays1.7.py
1,923
4.3125
4
# Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 # bytes, write a method to rotate the image by 90 degrees. Can you do this in place? #This solution is my O(n2) solution def rotate(matrix): newMatrix = [row[:] for row in matrix] #we have to copy the matrix so we don't edit the original a = len(matrix) for i in range(a): #traverse through each row and column for j in range(a): newMatrix[i][j] = matrix[a-j-1][i] # swap clockwise 90 degrees return newMatrix if __name__ == '__main__': matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix) print(rotate(matrix)) # Rotating a matrix 180 degrees clockwise from copy import deepcopy # using deepcopy to copy matrix into new matrix def rotate(matrix): oneEightyMatrix = deepcopy(matrix) n = len(matrix) for i in range(n): # algorithm for j in range(n): oneEightyMatrix[i][j] = matrix[n-i-1][n-j-1] return oneEightyMatrix if __name__ == '__main__': matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix) print(rotate(matrix)) #In place solution with O(n2) time complexity and O(1) space complexity def rotate(matrix): n = len(matrix) matrix.reverse() for i in range(n): for j in range(n): matrix[i][j] = matrix[j][i] return matrix if __name__ == '__main__': matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix) print(rotate(matrix)) #In place solution with O(n2) time complexity and O(1) space complexity def rotate(matrix): n = len(matrix) matrix.reverse() for i in range(n): for j in range(i): #only change matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # also changed return matrix if __name__ == '__main__': matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix) print(rotate(matrix))
true
238ac35d263a55d451dfd2b0f3fb1cfe4d12363d
ifegunni/Cracking-the-coding-interview
/arrays1.6.py
2,910
4.25
4
# String Compression: Implement a method to perform basic string compression using the counts # of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the # "compressed" string would not become smaller than the original string, your method should return # the original string.You can assume the string has only uppercase and lowercase letters (a - z). # this solution is O(n2) because we are concatinating a new string and that result to an O(n2) def stringCompression(string): res = "" # create an empty string count = 0 # initialize count for each element in the string to 0 prev = string[0] # to keep record of previous character in the string for char in string: if char == prev: #if the current element in a string equal to the previous element count+=1 # count the occurrence else: res += prev + str(count) #if not equal start adding the string to the new string and prev = char #set previous to current character and take not of occurence count = 1 #by initializing count to 1 res += prev + str(countConsecutive) #this last bit is called the edge case and it is important to capture the last bit of the string. if len(res) < len(string): return(res) else: return(string) if __name__ == '__main__': x = "aabcccccaaa" print(stringCompression(x)) #A better solution is to use a list rather that creating a new list Making the new solution O(n) def stringCompression(string): res = [] #using list in place of creating a new string is the only difference and changes time complexity to O(n) countConsecutive = 0 prev = string[0] for char in string: if char == prev: countConsecutive += 1 else: res += prev + str(countConsecutive) prev = char countConsecutive = 1 res += prev + str(countConsecutive) res = ''.join(res) if len(res) < len(string): return res else: return string if __name__ == '__main__': x = "aabcccccaaa" print(stringCompression(x)) # A different approach, comparing the current character with the next element in the string. def stringCompression(string): res = [] count = 1 for i in range(len(string)-1): # len(string) - 1: because we are comparing the value with the next value. if the we compare the last value with the next value(no value) then we get an error if string[i] == string[i+1]: count += 1 else: res += string[i] + str(count) count = 1 res += string[i] + str(count) # return(res) res = "".join(res) if len(res) < len(string): return res else: return string if __name__ == '__main__': x = "aabcccccaaa" print(stringCompression(x))
true
a571e0e9e507b15d778cf7c7210864c47422c138
kehsihba19/MINI-PYTHON-Beginner-Project
/Hangman.py
1,190
4.28125
4
import random def word_update(word, letters_guessed): masked_word = "" for letter in word: if letter in letters_guessed: masked_word += letter else: masked_word += "-" print( "The word:", masked_word) # List of words for the computer to pick from words = ("basketball", "football", "hockey", "lacrosse", "baseball") # Word to be guessed; picked at random word = random.choice(words) print ("="*32) print (" Guess the sport!") print ("You get to guess five letters.") print ("There are %s letters in the word." % (len(word))) print ("="*32) guesses = 5 letters_guessed = [] while guesses != 0: # make the letter lower case with .lower() letter = input("Enter a letter: ").lower() if letter in letters_guessed: print("You already guessed that letter.") else: guesses = guesses - 1 print("You have %d guesses left." % (guesses)) letters_guessed.append(letter) word_update(word, letters_guessed) # again, make input lower case guess = input("Guess the word: ").lower() if guess == word: print ("Congratulations, %s is the word!" % (guess)) else: print( "Nope. The word is %s." % (word))
true
6c00f55d6f5c28b24afd48cadf14bfee4add3c26
r121196/Python_exercise
/caluclator/simple calculator.py
668
4.1875
4
operation = input(''' type the required maths operation: + for addition - for substraction * for multiplication / for division ''') n1 = int(input('Enter the first number: ')) n2 = int(input('Enter the second number: ')) if operation == '+': print ('{} + {} = '. format(n1, n2)) print (n1 + n2) elif operation == '-': print ('{} - {} = '. format(n1 , n2)) print (n1 - n2) elif operation == '*': print ('{} * {} = '.format (n1, n2)) print (n1 * n2) elif operation == '/': print ('{} /{} = '. format(n1, n2)) print (n1 / n2) else : print (" The operation etered is invalid. Restart the programme.")
true
f32ad9099e69b7a8a70715e988aa2dde959778bf
lengau/dailyprogrammer
/233/intermediate.py
2,816
4.125
4
#!/usr/bin/env python3 # Daily Programmer #233, Intermediate: Conway's Game of Life # https://redd.it/3m2vvk from itertools import product import random import sys import time from typing import List class Cell(object): """A single cell for use in cellular automata.""" def __init__(self, state: str): self.state = state self.neighbours = () self.next_state = self.state def calculate_step(self): if not self.neighbours: raise ReferenceError('No neighbours defined') alive_neighbours = 0 for neighbour in self.neighbours: if neighbour.state and not neighbour.state.isspace(): alive_neighbours += 1 if not self.state or self.state.isspace(): if alive_neighbours == 3: self.next_state = random.choice([ n for n in self.neighbours if not n.state.isspace()]).state else: self.next_state = ' ' return if alive_neighbours not in (2, 3): self.next_state = ' ' def take_step(self): self.state = self.next_state def __str__(self) -> str: return self.state or ' ' def main(): with open(sys.argv[1]) as file: lines = file.read().splitlines() height = len(lines) width = max(len(line) for line in lines) def make_line(width: int, line: str) -> List[Cell]: """Make a line of cells.""" out_line = [] for cell_state in line: out_line.append(Cell(cell_state)) if len(out_line) < width: for _ in range(width - len(out_line)): out_line.append(Cell('')) return out_line grid = [] for line in lines: grid.append(make_line(width, line)) for y, x in product(range(height), range(width)): neighbour_coords = [] for a, b in product((-1, 0, 1), repeat=2): neighbour_coords.append((y+a, x+b)) neighbour_coords.pop(4) # The coordinates of the current cell. neighbours = [] for location in neighbour_coords: if -1 not in location and location[0] != height and location[1] != width: neighbours.append(grid[location[0]][location[1]]) grid[y][x].neighbours = neighbours for i in range(20): print("\033c"); print('Step %d:' % i) for line in grid: print(''.join(cell.state for cell in line)) for line in grid: for cell in line: cell.calculate_step() for line in grid: for cell in line: cell.take_step() if ''.join(''.join(cell.state for cell in line) for line in grid).isspace(): break time.sleep(0.75) if __name__ == '__main__': main()
true
2f395c7039ae26aa8c75b03f3727cd0c9235bcf5
Pavan-443/Python-Crash-course-Practice-Files
/chapter 8 Functions/useralbums_8-8.py
570
4.21875
4
def make_album(artist_name, title, noof_songs=None): """returns info about music album in a dictionary""" album = {} album['artist name'] = artist_name.title() album['song title'] = title.title() if noof_songs: album['no of songs'] = noof_songs return album while True: print('\ntype q to quit at any time') name = input('please enter the Artist name: ') if name.lower() == 'q': break title = input('please enter title of the song: ') if title.lower() == 'q': break print(make_album(name, title))
true
f390c30e06bdacc7e29d38fc519c95fb478bd924
zemery02/ATBS_notes
/Lesson_Code/hello.py
631
4.125
4
#! python3 # This program says hello and asks for my name print('Hello World!') print('What is your name?') #ask for their name myName = input() print('It is good to meet you, ' + myName) print('The length of your name is:') print(len(myName)) print('What is your age?') #ask for their age myAge = input() print('You will be ' + str(int(myAge) + 1) + ' in a year') if myAge == '15': print('You\'re going to be driving in no time!') elif myAge == '17': print('You\'re going to be legal next year!') elif myAge == '20': print('You can drink next year! Bottoms up!') else: print('Time sure does fly doesn\'t it?')
true
4f8383ae5d0439bb9972f2852623552e65a06527
vik13-kr/telyport-submission
/api/build_api/Q-2(Reverse character).py
494
4.3125
4
'''Reverse characters in words in a sentence''' def reverse_character(p_str): rev_list = [i[::-1] for i in p_str] #reversed characters of each words in the array rev_string = " ".join(map(str,rev_list)) #coverted array back to string return rev_string n_str = 'My name is Vikash Kumar' rev_str = reverse_character(n_str.split(' ')) # passing string as an list print('Original Character : {}'.format(n_str)) print('Reversed String : {}'.format(rev_str))
true
ac9e55e127c2972a737cdbdea7db49847381a993
DonLiangGit/Elements-of-Programming
/data_structure/Linkedlist_Node.py
1,161
4.1875
4
# define a Node class for linked list # __name__ & __main__ # http://stackoverflow.com/questions/419163/what-does-if-name-main-do # http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do class Node: def __init__ (self,initdata): self.data = initdata self.next = None def getData (self): return self.data def getNext (self): return self.next def addData(self, addedData): self.data = addedData def addNext(self, nextNode): self.next = nextNode # define an unordered list class UnorderedList: def __init__(self): self.head = None self.last = None def isEmpty(self): print("The List is empty.") return self.head == None def add(self,item): temp = Node(item) if self.head == None: temp.addNext(self.head) self.head = temp self.last = temp print("successful add.") else: self.last.next = temp self.last = temp print("add nodes") def size(self): current = self.head count = 0 print(count) while current != None: count += 1 current.getNext() return count mylist = UnorderedList() mylist.isEmpty() mylist.add(12) mylist.add(13) mylist.add(14) print(mylist.size())
true
12d289806c1323503a8a6040bc0a14f8d440711f
samuelbennett30/FacePrepChallenges
/Lists/Remove Duplicates.py
801
4.40625
4
''' Remove the Duplicate The program takes a lists and removes the duplicate items from the list. Problem Solution: Take the number of elements in the list and store it in a variable. Accept the values into the list using a for loop and insert them into the list. Use a for loop to traverse through the elements of the list. Use an if statement to check if the element is already there in the list and if it is not there, append it to another list. Print the non-duplicate items of the list. Exit. Sample Input: 5 10 10 20 20 20 Sample Output: Non-duplicate items: [10, 20] ''' arr=[] num=int(input()) for x in range(0,num): numbers=int(input()) arr.append(numbers) b=[] unique=[] for x in arr: if x not in b: unique.append(x) b.append(x) print("Non-duplicate items:") print(unique)
true
390aef3387103d3c30e03d19ff5dcf9985abee3b
tushar8871/python
/dataStructure/primeNumber.py
1,689
4.125
4
#generate prime number in range 0-1000 and store it into 2D Array #method to create prime number def primeNumber(initial,end): #create a list to store prime number in 0-100,100-200 and so-on resultList=[] try: #initialize countt because when we generate prime number between 0-100 then we have to initialize #initial from 100 not to 1 countt=1 #loop executed until initial is less than end while initial<end: #initialize temp to stop execution of loop upto 100,200 ,etc to create seperate list temp=100*countt list1=[] #execute loop utp temp and generate number for k in range(1,temp): count=0 for j in range(1,k+1): #check K mod j =0 then increment count #count is incremneted because prime number only divided by itself or one if k%j==0: count+=1 if count==2: #when we add number from 2nd execution already stored number will not be stored if k > initial: list1.append(k) #append list of prime no into main list resultList.append(list1) countt+=1 initial=temp except Exception: print("Modulo divide by error") return resultList #get range from user to find prime number initial=int(input("Enter initial vlaue of range : ")) end=int(input("Enter end vlaue of range : ")) #method call and store into listt listt=primeNumber(initial,end) #print list of prime number print("Prime Number in 2D array are : \n " ,listt)
true
d43783ac3758262be6e636db5da6a2725a1c218a
tushar8871/python
/functioalProgram/stringPermutation.py
1,002
4.28125
4
#Generate permutation of string #function to swap element of string def swap(tempList,start,count): #swapping element in list temp=tempList[start] tempList[start]=tempList[count] tempList[count]=temp #return list of string return tempList #generate permutation of string def strPermutation(Str,start,end): count=0 #if start and equal to length of string then print string if (start==end-1): print(Str) else: for count in range(start,end): #Put String in list to generate permutation tempList=list(Str) #call swap function to swap element of string swap(tempList,start,count) #recursive call until found all string strPermutation("".join(tempList),start+1,end) swap(tempList,start,count) #Get input from user Str=input("Enter string : ") #find length of string strLength=len(Str) #call function to generate permutation of string strPermutation(Str,0,strLength)
true
8973a64b33c9587d2b2f5dd4d1aaffcd54d10e17
bezdomniy/unsw
/COMP9021/Assignment_1/factorial_base.py
775
4.25
4
import sys ## Prompts the user to input a number and checks if it is valid. try: input_integer = int(input('Input a nonnegative integer: ')) if input_integer < 0: raise ValueException except: print('Incorrect input, giving up...') sys.exit() integer=input_integer ## Prints factorial base of 0 as a special case. if integer == 0: print('Decimal 0 reads as 0 in factorial base.') sys.exit() count=2 result=[] ## Generates a list of digits in factorial base. while integer > 0: result.append(str(integer % count)) integer = integer // count count += 1 ## Prints the original input and the reversed generates list for final answer. print('Decimal {} reads as {} in factorial base.'.format(input_integer,''.join(result[::-1])))
true
eb945c57d13c1364f773dd2bf64c3afcacf865ea
gtanubrata/Small-Fun
/return_day.py
1,129
4.125
4
''' return_day(1) # "Sunday" return_day(2) # "Monday" return_day(3) # "Tuesday" return_day(4) # "Wednesday" return_day(5) # "Thursday" return_day(6) # "Friday" return_day(7) # "Saturday" return_day(41) # None ''' days = {1: "Sunday", 2: "Monday", 3: "Tuesday", 4: "Wednesday", 5: "Thursday", 6: "Friday", 7: "Saturday"} def return_day(num): if num in days.keys(): return days[num] None print(return_day(2)) # # LIST VERSION ----------------------------------------------------------------------------------- # def return_day(num): # days = ["Sunday","Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday"] # # Check to see if num valid # if num > 0 and num <= len(days): # # use num - 1 because lists start at 0 # return days[num-1] # return None # # ADVANCED VERSION ------------------------------------------------------------------------------- # def return_day(num): # try: # return ["Sunday","Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday"][num-1] # except IndexError as e: # return None
true
f306b95eff6714bebe60f7b9a3332ec9f1399853
jackh423/python
/CIS41A/CIS41A_UNITC_TAKEHOME_ASSIGNMENT_1.py
2,654
4.25
4
""" Name: Srinivas Jakkula CIS 41A Fall 2018 Unit C take-home assignment """ # First Script – Working with Lists # All print output should include descriptions as shown in the example output below. # Create an empty list called list1 # Populate list1 with the values 1,3,5 # Create list2 and populate it with the values 1,2,3,4 # Create list3 by using + (a plus sign) to combine list1 and list2. Print list3. # Use sequence operator in to test list3 to see if it contains a 3, print True/False result (do with one line of code). # Count the number of 3s in list3, print the result. # Determine the index of the first 3 in list3, print the result. # Pop this first 3 and assign it to a variable called first3, print first3. # Create list4, populate it with list3's sorted values, using the sorted built-in function. # Print list3 and list4. # Slice list3 to obtain a list of the values 1,2,3 from the middle of list3, print the result. # Determine the length of list3, print the result. # Determine the max value of list3, print the result. # Sort list3 (use the list sort method), print list3. # Create list5, a list of lists, using list1 and list2 as elements of list5, print list5. # Print the value 4 contained within list5. list1 = [] for a in 1, 3, 5: list1.append(a) list2 = [1, 2, 3, 4] list3 = list1 + list2 print(f"list3 is: {list3}") print(f"list3 contains a 3: {3 in list3}") print(f"list3 contains {list3.count(3)} 3s") print(f"The index of the first 3 contained in list3 is {list3.index(3)}") first3 = list3.pop(list3.index(3)) print(f"first3 = {first3}") list4 = sorted(list3) print(f"list3 is now: {list3}") print(f"list4 is: {list4}") print(f"Slice of list3 is: {list3[2:5]}") print(f"Length of list3 is {len(list3)}") print(f"The max value of list3 is {max(list3)}") list3.sort() print(f"Sorted list3 is: {list3}") list5 = [list1, list2] print(f"list5 is{list5}") print(f"Value 4 from list5: {list5[1][3]}") # 2 e: Examine the results. Can you see how they were arrived at? # 2 c answer is arrived by performing AND on every bit of 2 numbers. # 2 d answer is arrived by performing OR on every bit of 2 numbers. ''' Execution results: /usr/bin/python3 /Users/jakkus/PycharmProjects/CIS41A/CIS41A_UNITC_TAKEHOME_ASSIGNMENT_1.py list3 is: [1, 3, 5, 1, 2, 3, 4] list3 contains a 3: True list3 contains 2 3s The index of the first 3 contained in list3 is 1 first3 = 3 list3 is now: [1, 5, 1, 2, 3, 4] list4 is: [1, 1, 2, 3, 4, 5] Slice of list3 is: [1, 2, 3] Length of list3 is 6 The max value of list3 is 5 Sorted list3 is: [1, 1, 2, 3, 4, 5] list5 is[[1, 3, 5], [1, 2, 3, 4]] Value 4 from list5: 4 Process finished with exit code 0 '''
true
af8dd324cd12deb2647eb541822000c9b377c99b
xurten/python-training
/tips/tip_54_use_lock_for_threads.py
1,317
4.125
4
# Tip 54 use lock for threads from threading import Thread, Lock HOW_MANY = 10 ** 5 class Counter: def __init__(self): self.count = 0 def increment(self, offset): self.count += offset def worker(index, counter): for _ in range(HOW_MANY): counter.increment(1) def thread_example(): how_many = 10 ** 5 counter = Counter() threads = [] for i in range(5): thread = Thread(target=worker, args=(i, counter)) threads.append(thread) thread.start() for thread in threads: thread.join() expected = how_many * 5 found = counter.count print(f'found= {found}, expected = {expected}') def thread_with_lock_example(): class LockingCounter: def __init__(self): self.lock = Lock() self.count = 0 def increment(self, offset): with self.lock: self.count += offset counter = LockingCounter() threads = [] for i in range(5): thread = Thread(target=worker, args=(i, counter)) threads.append(thread) thread.start() for thread in threads: thread.join() expected = HOW_MANY * 5 found = counter.count print(f'found= {found}, expected = {expected}') thread_example() thread_with_lock_example()
true
ff37f855eacfc27e1a7b1cd5247facac93f4b3c8
jack-evan/python
/tuples.py
239
4.21875
4
#this is a tuple someval = ("one","two",345,45.5,"summer") #print tuple print someval #prints tuple print someval[0] #prints first element of the tuple print someval[2:] #prints third element and on print someval * 2 #prints tuple twice
true
15498baa6391c1f3976f9ac752e66028ae67c632
jann1sz/projects
/school projects/python/deep copy of 2d list.py
1,215
4.25
4
def deep_copy(some_2d_list): #new_copy list is the list that holds the copy of some_2d_list new_copy = [] #i will reference the lists within some_2d_list, and j will reference the #items within each list. i = 0 j = 0 #loop that creates a deep copy of some 2d list for i in range(len(some_2d_list)): #bracket is an empty list that will append each item in the lists of #some_2d_list. #once all of the numbers in the first list are appended to bracket and #bracket is appended to the new copy list, the bracket list becomes #empty when it moves to the next list within some_2d_list bracket = [] for j in range(len(some_2d_list[i])): #value calls the first list in some 2d list #single_var calls the first item in the first list value = some_2d_list[i] single_var = value[j] #each item in the list is appended to the bracket list, which will #then be appened to the new_copy list bracket.append(single_var) new_copy.append(bracket) return new_copy deep_copy([[1,2],[3,4]])
true
cd6d6f7b6b9b4e5e7fc39d1fb56c0995147d33cc
mskaru/LearnPythonHardWay
/ex15.py
791
4.3125
4
# -*- coding: utf-8 -*- from sys import argv # script = py file name that I want to run # filename = the txt or word or whichever other file type # i want to read the information from script, filename = argv # command that calls the content of the file as txt txt = open(filename) print "Here's your file %r:" % filename # commands to read the txt print txt.read() # alternative way to get the same result print "Type the filename again:" # let's you input the file name and defines that as file_again file_again = raw_input("Write here: ") # command that calls the content of the file as txt txt_again = open(file_again) # commands to read the txt print txt_again.read() # the only difference between the two is writing the file name # in the terminal directly or asking for an input
true
87e1314624ce2cfd7672d3f8781b94135aca3796
rumbuhs/Homeworks
/HW6/hw6_t2.py
1,046
4.4375
4
from math import pi from math import sqrt def calculator(shape): """ This funktion will find the square of a rectangle, triangle or circle. depending on the user's choice. Input: name of shape Otput: the square of the shape """ shape = shape.upper() if shape == "RECTANGLE": a = int(input("Please, enter rectangle's length: ")) b = int(input("Please, enter rectangle's breadth: ")) print ((a*b), ' is a rectangle square') elif shape == 'TRIANGLE': c = int(input("Please, enter triangle's height length: ")) d = int(input("Please, enter triangle's breadth length: ")) print ((0.5*d*c), 'is a triangle square') elif shape == 'CIRCLE': r = int(input("Please, enter circle's radius length: ")) print((sqrt(r)*pi), 'is a circle square') else: print("Sorry! Chose betwen rectangle, triangle or circle") while True: shape = input('Please, enter the name of shape, you want to find a square: ', ) calculator(shape)
true
42959f7f25f93f11e5edf0f200d0f74b2dcf724d
Hunt-j/python
/PP02.py
546
4.15625
4
num = int(input("Pick a number:")) check = int(input("Pick a second number:")) if (num % 2 == 0): print("The number you've chosen is even") else: print("The number you've chosen in odd") if (num % 4 ==0): print("The number you've chose is divisible by 4") else: print("The number you've choses is not divisible by 4") if (num % check ==0): print("The first number you've chose is divisible by the 2nd number you've chosen") else: print("The first number you've chose is not divisible by the 2nd number you've chosen")
true
bd320410d6462d80f43620755a40495baa53bc0b
sshridhar1965/subhash-chand-au16
/FactorialW3D1.py
201
4.34375
4
# Factorial of a number num = int(input("Please Enter a number whose factorial you want")) product=1 while (num>=1): product = num*product num = num-1 print("The Factorial is ",product)
true
771576a2ea6f1e99200c242e3d53ea510e4a51e5
DanielVasev/PythonOnlineCourse
/Beginner/most_common_counter.py
1,244
4.34375
4
""" How to count most common words in text """ from collections import Counter text = "It's a route map, but it's only big enough to get to the starting point. Many businesses have been asking\ when they will be allowed to reopen. Now they have some rough indication, pencilled in to the calendar, but far from\ all of them, and with distancing still required. In contrast with Boris Johnson's approach for England, Nicola\ Sturgeon's statement at Holyrood was not a route map to a late summer of socialising, concerts, sports and travel.\ The plan is far more cautious. Nicola Sturgeon's idea of release, maybe by late April, is to get through the doors\ of a restaurant or bar. Both leaders had said they were putting data ahead of dates, but it was the prime minister's\ dates that the public notice, remember and plan on. Travel bookings soared on Monday and Tuesday." # We split big string to separate list elements. words = text.split() # Creating counter counter = Counter(words) # Most common 3 words we can change the attribute top_three = counter.most_common(3) # Print the result print(top_three) # Counter how many words are in the text # print(words) # sum = 1 # for n in words: # print(n, sum ) # sum +=1
true
4e2005cd521e0d50e46f64e26530224ceedd53c8
515ek/PythonAssignments
/Sample-2-solutions/soln20.py
1,343
4.3125
4
## Name: Vivek Babu G R ## Date: 26-07-2018 ## Assignment: Sample 2 ## Question: A simple substitution cipher is an encryption scheme where each letter in an alphabet to replaced by a different letter in the same alphabet ## with the restriction that each letter's replacement is unique. The template for this question contains an example of a substitution cipher ## represented a dictionary CIPHER_DICTIONARY. Your task is to write a function encrypt(phrase,cipher_dict) that takes a string phrase and a ## dictionary cipher_dict and returns the results of replacing each character in phrase by its corresponding value in cipher_dict. ## Ex: encrypt("cat", CIPHER_DICT) should return ”km “ ############################################################################################################################################################ def encrypt(phrase , cipher_dict): msg = '' for ch in phrase: msg += cipher_dict[ch] return msg CIPHER_DICT = {'e': 'u', 'b': 's', 'k': 'x', 'u': 'q', 'y': 'c', 'm': 'w', 'o': 'y', 'g': 'f', 'a': 'm', 'x': 'j', 'l': 'n', 's': 'o', 'r': 'g', 'i': 'i', 'j': 'z', 'c': 'k', 'f': 'p', ' ': 'b', 'q': 'r', 'z': 'e', 'p': 'v', 'v': 'l', 'h': 'h', 'd': 'd', 'n': 'a', 't': ' ', 'w': 't'} print(CIPHER_DICT) msg = input("Enter the phrase to encrypt\n") print(encrypt(msg, CIPHER_DICT))
true
cd4e8d94167d991aacdc132a2ca3f22a107e4c16
515ek/PythonAssignments
/Sample-1-solutions/soln18.py
385
4.1875
4
## Name: Vivek Babu G R ## Date: 26-07-2018 ## Assignment: Sample 1 ## Question: Python Program to Take in a String and Replace Every Blank Space with Hyphen. ############################################################################################ str1 = input('Enter the string\n') str2 = '' for s in str1.split(' '): if str2 != '': str2 = str2 + '-' + s else: str2 += s print(str2)
true
64d72e038c18c73bcc5ead26b026a6c3d4826e3d
ClntK/PaymentPlanner
/paymentPlanner.py
2,030
4.1875
4
""" File: paymentPlanner.py Author: Clint Kline Last Modified: 5/30/2021 Purpose: To Estimate a payment schedule for loans and financed purchases. """ # input collection price = (float(input("\nPurchase Price: "))) months = (float(input("Loan Duration(in months): "))) # example "12" for one year, "120" for 10 years downPayment = (float(input("Down Payment: "))) interestRate = (float(input("Interest Rate(as a decimal): "))) # example: .045 = 4.5% # other variables subTotal = price - downPayment total = subTotal + (subTotal * interestRate) payment = total / months # comfirm input print("\nprice: $%0.2f" % price) print("months: $%0.2f" % months) print("downPayment: $%0.2f" % downPayment) print("interestRate: $%0.2f" % interestRate) print("subTotal: $%0.2f" % subTotal) print("total w/int after down payment: $%0.2f" % total) print("payment: $%0.2f" % payment, "\n") # print table headers print("%-10s%-18s%-15s%-15s%-15s%-15s" % ("Month #:", "Init. Balance:", "Interest:", "Principal:", "Payment:", "Rem. Balance")) # begin list build if months > 0: duration = [] month = 0 # add values to list "duration" equal to number of months entered while months != 0: month += 1 duration.append(month) months -= 1 # handle no input in months variable else: print("Please enter a Duration.") # begin table build remDur = len(duration) while total > 0 and remDur > 0: # loop through each month in list "duration" to create a table of payments equal to the amount of months entered by user for i in duration: balance = total interest = balance * interestRate / remDur remDur -= 1 remBal = balance - (payment + interest) principal = payment - interest # display table row print("%-10s$%-17.2f$%-14.2f$%-14.2f$%-14.2f$%-14.2f" % (i, balance, interest, principal, payment, remBal)) total = remBal # end
true
9731d705b7cb3fdf08c13bb6790daac74765d754
ManavParmar1609/OpenOctober
/Data Structures/Searching and Sorting/MergeSort.py
1,275
4.34375
4
#Code for Merge Sort in Python #Rishabh Pathak def mergeSort(lst): if len(lst) > 1: mid = len(lst) // 2 #dividing the list into left and right halves left = lst[:mid] right = lst[mid:] #recursive call for further divisions mergeSort(left) mergeSort(right) #iterators for left and right halves i = 0 j = 0 #iterator for main list k = 0 while i < len(left) and j < len(right): #comparing values from left half with the values from right half and inserting the smaller value in the main list if left[i] < right[j]: lst[k] = left[i] i += 1 #incrementing value of iterator for left half else: lst[k] = right[j] j += 1 #incrementing value of iterator for right half k += 1 #incrementing value of iterator for main list #for all the remaining values while i < len(left): lst[k] = left[i] i += 1 k += 1 while j < len(right): lst[k] = right[j] j += 1 k += 1 #an example myList = [5, 7, 6, 1, 9] mergeSort(myList) print(myList) #Time complexity: O(nlogn)
true
b44d519c3cf9f4dd9f741d710eff3447d9991a22
ManavParmar1609/OpenOctober
/Algorithms/MemoizedFibonacci.py
927
4.3125
4
""" @author: anishukla """ """Memoization: Often we can get a performance increase just by not recomputing things we have already computed.""" """We will now use memoization for finding Fibonacci. Using this will not only make our solution faster but also we will get output for even larger values such as 1000 whereas by general recursive approch calculating fibonacci of 40 will also take very large amount of time.""" def fibonacci_memoization(n, d={}): if n in d: return d[n] elif n == 0: ans = 0 elif n == 1: ans = 1 else: ans = fibonacci_memoization(n-1, d) + fibonacci_memoization(n-2, d) d[n] = ans return ans print("Enter number of test cases you want: ") T = int(input()) for i in range(T): print("Input the position for fibonacci value: ") N = int(input()) print("Fibonacci(%d) = " %N , fibonacci_memoization(N))
true
f107b6b4d03e7557bfd26597d75acd953d1e5cda
EvgenyKirilenko/python
/herons_formula.py
320
4.4375
4
#this code calculates the area of triangle by the length of the given sides #by the Heron's formula from math import sqrt a=int(input("Enter side A:")) b=int(input("Enter side B:")) c=int(input("Enter side C:")) p=float((a+b+c)/2) s=float(sqrt(p*(p-a)*(p-b)*(p-c))) print ("Area of the triangle is : ",s)
true
c0e3604aff31861c0e38f030e91b3a5b82c29049
pratikpwr/Python-DS
/strings_6/lenghtOfStrings.py
329
4.34375
4
# length of string can be calculated by len() name = input("Enter string: ") length_of_string = len(name) print("string:", name) print("length of string:", length_of_string) # max and min of String or others maxi = max(name) mini = min(name) print("maximum:", maxi + "\nminimum:", mini) # slicing a String print(name[0:3])
true
427601166ccc5624317e9fea05adc163236321ae
ARAV0411/HackerRank-Solutions-in-Python
/Numpy Shapes.py
257
4.1875
4
import numpy arr= numpy.array(map(int, raw_input().split()) print numpy.reshape(arr, (3,3)) # modifies the shape of the array #print arr.shape() --- prints the rows and columns of array in tuples # arr.shape()= (3,4) --- reshapes the array
true
1c9ab653a40c59ba50f04719d8950a2656fdd6f5
ybharad/DS_interview_prep_python
/prime_factors.py
736
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 26 20:43:26 2020 @author: yash this function calculates the factors of any number which are only prime numbers it reduces the factors of a number to its prime factors """ import math def primeFactors(n): # Print the number of two's that divide n while n % 2 == 0: print (2), n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3, int(math.sqrt(n)) + 1, 2): # while i divides n , print i ad divide n while n % i == 0: print (i), n = n / i # Condition if n is a prime # number greater than 2 if n > 2: print (n)
true
db6ef77f8dd537603785af1ca4ff554cb837e9c7
arshad-taj/Python
/montyPython.py
260
4.28125
4
def reverse(s): if len(s) == 0: return s else: return reverse(s[1:]) + s[0] s = "Geeksforgeeks" print("The original string is : ", end="") print(s) print("The reversed string(using recursion) is : ", end="") print(reverse(s))
true