blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1c551d5fdea25beebc8b9c566d17fc4c23a1c3b1
jimibarra/cn_python_programming
/04_conditionals_loops/04_10_squares.py
237
4.34375
4
''' Write a script that prints out all the squares of numbers from 1- 50 Use a for loop that demonstrates the use of the range function. ''' for num in range(1,51): square = num ** 2 print(f'The square of {num} is {square} ')
true
6bfee747928fa37a7cbcf03d73fd118133f6c930
jimibarra/cn_python_programming
/01_python_fundamentals/01_07_area_perimeter.py
277
4.1875
4
''' Write the necessary code to display the area and perimeter of a rectangle that has a width of 2.4 and a height of 6.4. ''' area = 6.4 * 2.4 perimeter = 2 * (6.4 + 2.4) print(f"The area of the rectangle is {area}") print(f"The perimeter of the rectangle is {perimeter}")
true
d0e9358885e01dee964f826d9302180cb7d3ab90
AmyShackles/LearnPython3TheHardWay
/ex7.py
1,396
4.28125
4
# prints the string 'Mary had a little lamb' print("Mary had a little lamb.") # prints 'Its fleece was white as snow', the {} indicated replacement and 'snow' was the replacement text print("Its fleece was white as {}.".format('snow')) # prints 'And everywhere that Mary went' print("And everywhere that Mary went.") # prints 10 periods print("." * 10) # what'd that do? # assigns letter 'C' to variable end1 end1 = "C" # assigns letter 'h' to variable end2 end2 = "h" # assigns letter 'e' to variable end3 end3 = "e" # assigns letter 'e' to variable end4 end4 = "e" # assigns letter 's' to variable end5 end5 = "s" # assigns letter 'e' to variable end6 end6 = "e" # assigns letter 'B' to variable end7 end7 = "B" # assigns letter 'u' to variable end8 end8 = "u" # assigns letter 'r' to variable end9 end9 = "r" # assigns letter 'g' to variable end10 end10 = "g" # assigns letter 'e' to variable end11 end11 = "e" # assigns letter 'r' to variable end12 end12 = "r" # prints end1 plus end2 plus end3 plus end4 plus end5 plus end6 # with end=' ' at the end, it prints 'Cheese Burger' to screen # without end=' ' at the end, it prints 'Cheese\nBurger' to screen # end is an argument of print and by default equals new line print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') # prints end7 plus end8 plus end9 plus end10 plus end11 plus end12 print(end7 + end8 + end9 + end10 + end11 + end12)
true
7d9600f2d3b44ba69232a20d4586c61dc48fb8b6
shkyler/gmit-cta-problems
/G00364753/Q2d.py
957
4.375
4
# Patrick Moore 2019-03-05 # This is a script to create a function that finds the max value in a list # using an iterative approach, as directed by Question 2(d) of the # Computational Thinking with Algorithms problem sheet # define a function that takes a list as an argument def max_iter(data): # set the maximum value to be the first item in the list maximum = data[0] # create a counter variable for the while loop counter = 0 # use a while loop to iterate over the length of the list while counter < len(data): # check if any item in the list is greater than the current maximum if data[counter] > maximum: # if so, set maximum to that value maximum = data[counter] # increment the counter counter = counter + 1 # once the while loop terminates, return the max value return maximum # create a variable to store the data list y = [0, -247, 341, 1001, 741, 22] # call the finder # function print(max_iter(y))
true
9d6e2e6e6d8c55965fe4206b140c78b2ee145772
michaelobr/gamble
/Gamble.py
1,667
4.3125
4
#Short introduction of the purpose of this program print("This short little program will help determine the probability of profitability and ROI from playing 50/50 raffles.") #The number of tickets the user will purchase num_user_tickets = int(input("How many tickets will you purchase? ")) #The total amount of tickets sold to everybody participating in the 50/50 raffle, this includes the user's. sum_tickets_sold = int(input("How many tickets in total are expected to be purchased? ")) #Parentheses must be used here, because multiplication comes before divsion in the order of operations which Python adheres to. winning_probability = (num_user_tickets / sum_tickets_sold) * 100 ticket_price = int(input("What is the price per 50/50 ticket? ")) #Only 50% of the total ticket sales is available to win, so we must divide by 2 here possible_winnings = (sum_tickets_sold * ticket_price) / 2 #profit = revenue - cost. If the number is negative, then it is a loss, but the same formula is still used. profit = possible_winnings - (num_user_tickets * ticket_price) #Return on Investment = profit (or loss) from investment / cost of investment ROI = ((profit) / (num_user_tickets * ticket_price)) * 100 #No " " is needed after "purchase," num_user_tickets, etc. because Python automatically includes a space. print("If you purchase", num_user_tickets, "ticket(s) at a price per ticket of $", ticket_price, "for a total of $", (num_user_tickets * ticket_price), "you have a", (winning_probability), "% of winning $", possible_winnings, ".") print("This would result in a profit of $", profit, "and a ROI of", ROI, "%.")
true
bca2eb0df154973cc48900b3493b812846429288
Izabela17/Programming
/max_int.py
727
4.25
4
"""If users enters x number of positive integers. Program goes through those integers and finds the maximum positive and updates the code. If a negative integer is inputed the progam stops the execution """ """ num_int = int(input("Input a number: ")) # Do not change this line max_int = num_int while num_int >= 0: if num_int > max_int: max_int = num_int num_int = int(input("Input a number: ")) print ("The maximum is", max_int) """ n = int(input("Enter the length of the sequence: ")) # Do not change this line num1 = 0 num2 = 0 num3 = 1 i = 1 for i in range(n): temp3 = num3 num3 = num1 + num2 + num3 if i > 1: num1 = num2 num2 = temp3 print(num3)
true
62f9cca5ef39e633b5a20ffd6afb27772a5291fc
NikolaosPanagiotopoulos/python-examples-1
/Addition.py
225
4.21875
4
#this program adds two numbers num1=input('Enter first number: ') num2=input('Enter second number: ') #Add two numbers sum=float(num1)+float(num2) #display the sum print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
true
14765ce398a35e4730122fb867cd45d386d19c7f
allysonvasquez/Python-Projects
/2-Automating Tasks/PhoneAndEmail.py
852
4.15625
4
# author: Allyson Vasquez # version: May.15.2020 # Practice Exercises: Regular Expressions # https://www.w3resource.com/python-exercises/re/index.php import re # TODO: check that a string contains only a certain set of characters(a-z, A-Z and 0-9) charRegex = re.compile(r'\d') test_str = str('My name is Allyson and I am 20 years old') # TODO: match a string that contains only upper and lowercase letters, numbers, and underscores # TODO: remove leading zeros from an IP address # TODO: convert a date from yyyy-mm-dd to mm-dd-yyyy # TODO: separate and print the numbers of a given string # TODO: abbreviate Road as Rd. in a home address # TODO: replace all spaces with a - # TODO: find all words that are 5 characters long in a string # TODO: extract values between quotation marks in a string # TODO: remove all the .com from a list of websites
true
a9842c9896f227bb707b36906ec06f6fe93c0fc2
talrab/python_excercises
/fibonacci.py
707
4.3125
4
run_loop = True num_elements = int(input("Please enter the number of elements: ")) if num_elements < 0: run_loop = False while (run_loop): answer = [] for x in range(num_elements): print( "X=" + str(x)) if (x+1==1): answer.append(1) elif (x+1==2): answer.append(1) else: answer.append (answer[x-2] + answer[x-1]) print (answer) num_elements = int(input("Please enter the number of elements: ")) if num_elements < 0: run_loop = False # a 'classier' solution to find the nth element of fibonacchi: def fib(n): a,b = 0,1 for i in range(n): a,b = b,b+a return a print(fib(5))
true
51a4bcb49223b93ebc60b0cce21f4cbde2c5b8da
yankwong/python_quiz_3
/question_1.py
506
4.25
4
# create a list of number from 1 to 10 one_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # using list comprehension, generate a new list with only even numbers even_from_one_to_ten = [num for num in one_to_ten if (num % 2 == 0)] # using list comprehension, generate a new list with only odd numbers odd_from_one_to_ten = [num for num in one_to_ten if (num % 2 == 1)] # print out the sum of all even numbers print(sum(even_from_one_to_ten)) # print out the sum of all odd numbers print(sum(odd_from_one_to_ten))
true
421ce0dabf326248c65348bd3506e5596570730a
pnthairu/module7_Arrays
/sort_and_search_array.py
2,039
4.3125
4
from array import array as arr from filecmp import cmp # Start Program """ Program: sort_and_Search_array.py Author: Paul Thairu Last date modified: 06/23/2020 You can make a new files test_sort_and_search_array.py and sort_and_search_array.py. In the appropriate directories. For this assignment, you can hard-code a list you pass to the sort_array() and search_array(). Eventually write 2 functions sort_array() and search_array(). search_array() will return the index of the object in the list or a -1 if the item is not found sort_array() will sort the list """ # declaring getList function and with array list parameter def get_array(arr): print(arr) # print the list of items # Declaring searchList function with array list and subject to search parameters def search_array(arr, subject): print("****************************************************") print(subject) # element to search on th list for i in arr: # looping through the list to find an element if (i == subject): # if car is not in the list break break if subject in arr: pass else: return -1 # returning a value that does not exit in the array def sort_array(arr): arr.sort() # in build sort function to sort subject in alphabetical order print("Subjects in alphabetical order") print(arr) # Print list of subjects in order if __name__ == '__main__': arr = ['Maths', 'English', 'Biology', 'Chemistry', 'Physics'] # my hard coded array list subject = "French" # car to search subject in the array list get_array(arr) # function call and assigning to array of subjects if (search_array(arr, subject) == -1): # If subject not found print(subject + " 'Does not exit in the ARRAY !!!!!!!'") else: # if subject is found print(subject + " FOUND in the subject array..") print("****************************************************") sort_array(arr) # sorting list in alphabetical order
true
0d7b86cad05e0a7391f3eb150175446a58f20c6b
ratneshgujarathi/Encryptor-GUI-
/encrypt_try.py
1,299
4.4375
4
#ceasor cipher method encryption #this is trial module to easy encrypyt the message #c=(x-n)%26 we are ging to follow this equation for encrytion #c is encryted text x is the char n is the shifting key that should be in numbers % is modulus 26 is total alphabets #function for encrytion def encryption(string,shift): cipher='' for char in string: if char=='': cipher=cipher+char elif char.isupper(): cipher=cipher+chr((ord(char)+shift-65)%26+65) else: cipher=cipher+chr((ord(char)+shift-97)%26+97) return cipher def decryption(string,shift): cipher1='' for char in string: if char=='': cipher1=cipher1+char elif char.isupper(): cipher1=cipher1+chr((ord(char)-shift-65)%26+65) else: cipher1=cipher1+chr((ord(char)-shift-97)%26+97) return cipher1 ascii_text='' text=input("Enter your text here ") for i in text: ascii_text=ascii_text+int(i) print(ascii_text) s=int(input("enter the desired shifting key ")) print("the original text was ",text) print("the encrypted message is ",encryption(text,s)) en=encryption(text,s) print("The encrypted message is ",en) print("decrypted message is ",decryption(en,s))
true
a7ca5c75d43d8fbdb082f89d549b1db9959e101a
praveendareddy21/ProjectEulerSolutions
/src/project_euler/problem4/problem4.py
2,395
4.21875
4
''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. Created on Feb 18, 2012 @author: aparkin ''' from project_euler.timing import timeruns, format_runs def ispalindrome(num): ''' Simple predicate to test if num is a palindromic number. @return: true if num is a palindrome, false otherwise ''' str_num = str(num) return str_num == (str_num[::-1]) def prob4(numdigits=3): ''' 1st attempt to solve problem 4, pretty much brute force. @param numdigits: how many digits should the two factors have. @type numdigits: int @return: a 3-tuple (factor1, factor2, num) such that num is the largest palindrome that is a product of two numdigits numbers: factor1 and factor2 @rtype: (int, int, int) ''' biggest = 10**numdigits-1 smallest = 10**(numdigits-1) palindromes = {} # loop over all possible 3 digit factors, taking advantage of the # commutivity of multiplication (ie 3 x 4 == 4 x 3) for num1 in range(biggest, smallest, -1): for num2 in range(num1, smallest, -1): if ispalindrome(num1 * num2): palindromes[num1*num2] = (num1, num2, num1 * num2) return palindromes[sorted(palindromes, reverse=True)[0]] def prob4v2(numdigits=3): ''' Same as v1, but using a dict comprehension to see if the move from nested for loop to nested dict comprehension would be faster ''' biggest = 10**numdigits-1 smallest = 10**(numdigits-1)-1 palindromes = {i * j : (i, j, i * j) for i in range(biggest, smallest, -1) for j in range(i, smallest, -1) if ispalindrome(i * j)} return palindromes[sorted(palindromes, reverse=True)[0]] def main(): print prob4(3) print prob4v2(3) # time different approaches setup = """ from project_euler.problem4.problem4 import prob4, prob4v2 """ runs = [("""prob4(3)""", setup, "Nested For Loop"), ("""prob4v2(3)""", setup, "Dict comprehension"), ] num_iterations = 100 print format_runs(timeruns(runs, num_iterations)) if __name__ == "__main__": main()
true
eea1a67f02c852cd6ca7b2997c9bb7ffdff4e7ba
coomanky/game-v1
/main.py
2,848
4.3125
4
#user information print("hello and welcome to (game v2) , in this game you will be answering a series of questions to help inprove your knowledge of global warming ") print (" ") name = input ("What is your name? ") print ("Hello " + name) print(" ") # tutorial def yes_no(question): valid = False while not valid: response = input(question).lower() if response == "yes" or response == "y": response = "yes" return response elif response == "no" or response == "n": response = "no" return response else: print("Please answer yes / no") show_instructions = yes_no("Have you played the " "game before? ") print("You chose {}".format(show_instructions)) # rounds start rounds_played = 0 play_again = input("Press <Enter> to play...").lower() def new_game(): guesses = [] correct_guesses = 0 question_num = 1 for key in questions: print("-------------------------") print(key) for i in options[question_num-1]: print(i) guess = input("Enter (A, B, C, or D): ") guess = guess.upper() guesses.append(guess) correct_guesses += check_answer(questions.get(key), guess) question_num += 1 display_score(correct_guesses, guesses) # ------------------------- def check_answer(answer, guess): if answer == guess: print("CORRECT!") return 1 else: print("WRONG!") return 0 # ------------------------- def display_score(correct_guesses, guesses): print("-------------------------") print("RESULTS") print("-------------------------") print("Answers: ", end="") for i in questions: print(questions.get(i), end=" ") print() print("Guesses: ", end="") for i in guesses: print(i, end=" ") print() score = int((correct_guesses/len(questions))*100) print("Your score is: "+str(score)+"%") # ------------------------- def play_again(): response = input("Do you want to play again? (yes or no): ") response = response.upper() if response == "YES": return True else: return False # ------------------------- questions = { "is the ice melting in the artic?: ": "A", "why is the ice melting in the artic?: ": "B", "is it effecting the animals that live there?: ": "C", "are there any ways we could fix this issue?: ": "A" } options = [["A. yes", "B. no", "C. maybe", "D. sometimes"], ["A. because of trees", "B. because of humans", "C. because of sharks", "D. because of penguins"], ["A. no", "B. sometimes", "C. yes", "D. only on weekends"], ["A. yes","B. no", "C. sometimes", "D. maybe"]] new_game() while play_again(): new_game() # completed game
true
52dad76686a481f7218cc435f240c3086897bc37
DesignisOrion/DIO-Tkinter-Notes
/grid.py
467
4.40625
4
from tkinter import * root = Tk() # Creating Labels label1 = Label(root, text="Firstname") label2 = Label(root, text="Lastname") # Creating Text fields entry1 = Entry(root) entry2 = Entry(root) # Arrange in the grid format label1.grid(row=0, column=0) label2.grid(row=1, column=0) # Want to have the labels place in front of the entry level respectively.add() entry1.grid(row=0, column=1) entry2.grid(row=1, column=1) root.mainloop()
true
39d2367ba2910304e1e50724783ffbd3ece60b0f
divyakelaskar/Guess-the-number
/Guess the number .py
1,862
4.25
4
import random while True: print("\nN U M B E R G U E S S I N G G A M E") print("\nYou have 10 chances to guess the number.") # randint function to generate the random number between 1 to 100 number = random.randint(1, 100) """ number of chances to be given to the user to guess the number or it is the inputs given by user into input box here number of chances are 10 """ chances = 0 print("Guess a number (1 - 100):") # While loop to count the number of chances while chances < 10: # Enter a number between 1 to 100 guess = int(input()) # Compare the user entered number with the number to be guessed if guess == number: """ if number entered by user is same as the generated number by randint function then break from loop using loop control statement "break" """ print("Congratulation YOU WON!!!") break # Check if the user entered number is smaller than the generated number elif guess < number: print("Your guess was too low: Guess a number higher than", guess) # The user entered number is greater than the generated number else: print("Your guess was too high: Guess a number lower than", guess) # Increase the value of chance by 1 as 1 chance is used chances += 1 # Check whether the user guessed the correct number if not chances < 10: print("YOU LOSE!!! The number is", number) ans=input("Do you want to play again (y/n) : ") if ans != 'y' : break print("\n T H A N K S F O R P L A Y I N G ! ! ! ! !\n")
true
356ad2bf5d602c408dd3c44c2e475c5a8379da0a
emorycs130r/Spring-2021
/class_8/lists_intro.py
454
4.25
4
fruits = ['Apple', 'Strawberry', 'Orange'] # Index = Position - 1 # print(fruits[3]) print(type(fruits)) vegetables = [] print(f"Before adding value: {vegetables}") vegetables.append('Brocolli') print(f"After adding value: {vegetables}") # print(vegetables) fruits.append('Kiwi') print(f"Fruits are: {fruits}") fruits.insert(2, 'Raspberry') print(f"Updated fruit list: {fruits}") fruits.remove('Apple') print(f"Updated fruit list 2: {fruits}")
true
9af404e0faeff67ace5589e05ecb3fdc9c680104
emorycs130r/Spring-2021
/class_6/temperature_conversion.py
662
4.40625
4
''' Step 1: Write 2 functions that converts celsius to farenheit, celsius to kelvin. Step 2: Get an input from user for the celsius value, and f/k for the value to convert it to. Step 3: Based on the input call the right function. ''' def c_to_f(temp): return (9/5) * temp + 32 def c_to_k(temp): return temp + 273.15 if __name__ == "__main__": function = input("Which conversion? (F or K) ") temp = float(input("Enter a temperature in Celsius: ")) if function == "F" or function == "f": print(c_to_f(temp)) elif function == "K" or function == "k": print(c_to_k(temp)) else: print("Invalid conversion")
true
90653fca5369a36f393db2f49b30322080d0a944
emorycs130r/Spring-2021
/class_11/pop_quiz_1.py
458
4.1875
4
''' Create a dictionary from the following list of students with grade: bob - A alice - B+ luke - B eric - C Get input of name from user using the "input()" and use it to display grade. If the name isn't present, display "Student not found" ''' def working_numbers_set(input_list): return list(dict.fromkeys(input_list)) if __name__ == "__main__": input_list = [2,2,3,5,6,8,7,6,2] result = working_numbers_set(input_list) print(result)
true
c0cb66d637c94a99eb4255c5991a2fcc0aae122c
vparjunmohan/Python
/Basics-Part-II/program30.py
513
4.125
4
'''Write a Python program to reverse the digits of a given number and add it to the original, If the sum is not a palindrome repeat this procedure. Note: A palindrome is a word, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar.''' def rev_number(n): while True: k = str(n) if k == k[::-1]: break else: m = int(k[::-1]) n += m return n print(rev_number(1234)) print(rev_number(1473))
true
6da942919c4afcaf3e6a219f42c642b4a34761c3
vparjunmohan/Python
/Basics-Part-I/program19.py
334
4.40625
4
'Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.' str = input('Enter a string ') if str[:2] != 'Is': newstr = 'Is' + str print('New string is',newstr) else: print('String unchanged',str)
true
a73d72582cc340a3c517b4f5ecde7a396175b7cc
vparjunmohan/Python
/Basics-Part-I/program150.py
241
4.1875
4
'Python Program for sum of squares of first n natural numbers.' def squaresum() : sm = 0 for i in range(1, n+1): sm = sm + (i * i) return sm n = int(input('Enter a number ')) print('Sum of squares is',squaresum())
true
55e157e4a5c65734f28ef1a72c3c987732ca8ebc
vparjunmohan/Python
/Basics-Part-I/program7.py
375
4.46875
4
''' Write a Python program to accept a filename from the user and print the extension of that. Sample filename : abc.java Output : java''' filename = input('Enter file name: ') extension = filename.split('.') #split() method returns a list of strings after breaking the given string by the specified separator. print('Extension of the file',extension[0],'is',extension[1])
true
b07684fbb0a42f18683a21a8fc4d08abe25c5712
vparjunmohan/Python
/String/program1.py
215
4.15625
4
'Write a Python program to calculate the length of a string.' def strlen(string): length = len(string) print('Length of {} is {}'.format(string, length)) string = input('Enter a string ') strlen(string)
true
b206558992aed8a4b4711787dff8f4933ad1d2ec
vparjunmohan/Python
/Basics-Part-II/program45.py
671
4.15625
4
'''Write a Python program to that reads a date (from 2016/1/1 to 2016/12/31) and prints the day of the date. Jan. 1, 2016, is Friday. Note that 2016 is a leap year. Input: Two integers m and d separated by a single space in a line, m ,d represent the month and the day. Input month and date (separated by a single space): 5 15 Name of the date: Sunday''' from datetime import date print('Input month and date (separated by a single space):') m, d = map(int, input().split()) weeks = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'} w = date.isoweekday(date(2016, m, d)) print('Name of the date: ', weeks[w])
true
97cc5bf2f5ebc0790d157a8ad00a2006aa53ca64
AbhishekKunwar17/pythonexamples
/11 if_elif_else condition/unsolved02.py
236
4.21875
4
Write Python code that asks a user how many pizza slices they want. The pizzeria charges Rs 123.00 a slice if user order even number of slices, price per slice is Rs 120.00 Print the total price depending on how many slices user orders.
true
1ac7a9e8d9ee10eeb8e571d3dd6e5698356a1a47
NitinSingh2020/Computational-Data-Science
/week3/fingerExc3.py
1,503
4.28125
4
def stdDevOfLengths(L): """ L: a list of strings returns: float, the standard deviation of the lengths of the strings, or NaN if L is empty. """ if len(L) == 0: return float('NaN') stdDev = 0 avgL = 0 lenList = [len(string) for string in L] for a in lenList: avgL += a avgL = avgL/float(len(L)) N = len(L) for string in L: stdDev += (len(string) - avgL)**2 return (stdDev/float(N))**0.5 L = ['a', 'z', 'p'] print stdDevOfLengths(L) # 0 L = ['apples', 'oranges', 'kiwis', 'pineapples'] print stdDevOfLengths(L) # 1.8708 # =============================================== def avg(L): """ L: a list of numbers returns: float, the average of the numbers in the list, or NaN if L is empty """ if len(L) == 0: return float('NaN') avgL = 0 for a in L: avgL += a avgL = avgL/float(len(L)) return avgL def stdDev(L): """ L: a list of numbers returns: float, the standard deviation of the numbers in the list, or NaN if L is empty """ if len(L) == 0: return float('NaN') stdDev = 0 avgL = avg(L) for a in L: stdDev += (a - avgL)**2 return (stdDev/float(len(L)))**0.5 def coeffOfVar(L): avgL = avg(L) stdDevL = stdDev(L) return stdDevL/float(avgL) print coeffOfVar([10, 4, 12, 15, 20, 5]) print coeffOfVar([1, 2, 3]) print coeffOfVar([11, 12, 13]) print coeffOfVar([0.1, 0.1, 0.1])
true
80d674fa13606ccecb4943feb34ea9878cf45cca
AutumnColeman/python_basics
/python-strings/caesar_cipher.py
688
4.5625
5
#Given a string, print the Caesar Cipher (or ROT13) of that string. Convert ! to ? and visa versa. string = raw_input("Please give a string to convert: ").lower() cipher_list = "nopqrstuvwxyzabcdefghijklm" alpha_list = "abcdefghijklmnopqrstuvwxyz" new_string = "" for letter in string: if letter == "m": new_string += "z" elif letter == " ": new_string += " " elif letter == "!": new_string += "?" elif letter == "?": new_string += "!" elif letter not in alpha_list: print "Invalid character" else: i = cipher_list.index(letter) new_letter = alpha_list[i] new_string += new_letter print new_string
true
3bac6dcded9f050f8c3d8aff2e2f9f5083310d00
nishesh19/CTCI
/educative/rotateLinkedList.py
1,146
4.1875
4
from __future__ import print_function class Node: def __init__(self, value, next=None): self.value = value self.next = next def print_list(self): temp = self while temp is not None: print(temp.value, end=" ") temp = temp.next print() def rotate(head, rotations): # TODO: Write your code here if (not head) or (not head.next) or rotations == 0: return head curr = head ll_len = 1 while curr.next: ll_len += 1 curr = curr.next jumps = rotations % ll_len curr = head while jumps > 1: curr = curr.next jumps -= 1 new_head = curr.next curr.next = None new_tail = new_head while new_tail.next: new_tail = new_tail.next new_tail.next = head head = new_head return head def main(): head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) print("Nodes of original LinkedList are: ", end='') head.print_list() result = rotate(head, 3) print("Nodes of rotated LinkedList are: ", end='') result.print_list() main()
true
9c091e4e3c4090e276eaad3b8ae15ea5e8fb6654
nishesh19/CTCI
/Arrays and Strings/Urlify.py
721
4.28125
4
# Write a method to replace all spaces in a string with '%20: You may assume that the string # has sufficient space at the end to hold the additional characters, and that you are given the "true" # length of the string. (Note: If implementing in Java, please use a character array so that you can # perform this operation in place.) # EXAMPLE # Input: "Mr John Smith "J 13 # Output: "Mr%20John%20Smith" #!/bin/python3 import math import os import random import re import sys def URLify(sentence): char_list = list(sentence.rstrip()) for i in range(len(char_list)): if char_list[i] == " ": char_list[i] = "%20" print(''.join(char_list)) if __name__ == '__main__': URLify(str(input()))
true
6e58c3d2c52524ae138b55a4d4dbaf57512d363b
nishesh19/CTCI
/LinkedList/deletemiddlenode.py
1,892
4.125
4
''' 2.3 Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node. EXAMPLE Input: the node c from the linked list a->b->c->d->e->f Result: nothing is returned, but the new linked list looks like a->b->d->e->f ''' class Node: def __init__(self, value): self._next = None self._value = value @property def value(self): return self._value @value.setter def value(self, value): self._value = value @property def next(self): return self._next @next.setter def next(self, next): self._next = next class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert(self, item): newNode = Node(item) if self.head == None: self.head = newNode if self.tail: self.tail.next = newNode self.tail = newNode def size(self): head = self.head length = 0 while head: length += 1 head = head.next return length def iterate(self): head = self.head print('\n') while head: print(head.value) head = head.next def delete(self,node): node.value = node.next.value node.next = node.next.next if __name__ == '__main__': nodes = input().split() no_of_nodes = int(nodes[0]) k = int(nodes[1]) sl = SinglyLinkedList() for i in range(no_of_nodes): sl.insert(int(input())) head = sl.head while k>0: head = head.next k -= 1 print(f'Node to delete : {head.value}') sl.delete(head) print('Updated list') sl.iterate()
true
e94f1f07150945766804cb28a1e831429bc880de
L0GI0/Python
/Codes/functions_with_lists.py
919
4.25
4
#!/usr/bin/python3 lucky_numbers = [32, 8, 15, 16, 23, 42] friends = ["Kevin", "Karen", "Jim", "Oscar", "Tom"] print(friends) #append another lists at the end of a list friends.extend(lucky_numbers) print(friends) #adding indivitual elements at the end of given list friends.append("Creed") #adding individual elements at the specific index friends.insert(1, "Kelly") #remobing specific element friends.remove("Jim") #removing whole list friends.clear() #poping an item from a list, getting rid of the last element friends.pop() #checking the existence of a element if it is on the list it give its index print(friends.index("Kevin")) #couting duplicates print(friends.count("Jim")) #sorting the list in alphabetical order friends.sort() print(friends) lucky_numbers.sort(); print(lucky_numbers) #reversing the list lucky_numbers.reverse() #copying a list, creates a copy of given list friends2 = friends.copy()
true
e4434cfa2ff0b2b53664dd678bb0d6c9490e8e67
ibnahmadCoded/how_to_think_like_a_computer_scientist_Chapter_5
/palindrom_checker.py
248
4.21875
4
def is_palindrome(word): """Reverses word given as argument""" new_word = "" step = len(word) + 1 count = 1 while step - count != 0: new_word += word[count * -1] count += 1 return new_word == word
true
0ff0a238da2e48a751d66401f303090375a03ed1
Sandbox4KidsTM/Python_Basics
/Supplemental_Material/PythonProjects/14. ALGEBRA/ALGEBRA/StringManipulation.py
733
4.125
4
# https://www.youtube.com/watch?v=k9TUPpGqYTo&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=2 # MATH FUNCTIONS in Python: https://docs.python.org/3.2/library/math.html #all key methods related to string manipulation message = "Hello World" print(message[0:3]) #including lower limit, but not including upper limit print(message.lower()) #prints lower case print(message.upper()) #prints uppoer case print(message.count('l')) #counts the number of occurances of substring 'l' print(message.find('World')) #prints index of first occurance of substring 'l' print(message.find('bobo')) #prints -1, if substring is not found print(message.casefold()) message = message.replace('World', 'Universe') print(message)
true
fa987c3d6e2c2e1dba192beee4cb430cb9d265ce
DZGoldman/Google-Foo-Bar
/problem22.py
2,284
4.40625
4
# things that are true: """ Peculiar balance ================ Can we save them? Beta Rabbit is trying to break into a lab that contains the only known zombie cure - but there's an obstacle. The door will only open if a challenge is solved correctly. The future of the zombified rabbit population is at stake, so Beta reads the challenge: There is a scale with an object on the left-hand side, whose mass is given in some number of units. Predictably, the task is to balance the two sides. But there is a catch: You only have this peculiar weight set, having masses 1, 3, 9, 27, ... units. That is, one for each power of 3. Being a brilliant mathematician, Beta Rabbit quickly discovers that any number of units of mass can be balanced exactly using this set. To help Beta get into the room, write a method called answer(x), which outputs a list of strings representing where the weights should be placed, in order for the two sides to be balanced, assuming that weight on the left has mass x units. The first element of the output list should correspond to the 1-unit weight, the second element to the 3-unit weight, and so on. Each string is one of: "L" : put weight on left-hand side "R" : put weight on right-hand side "-" : do not use weight To ensure that the output is the smallest possible, the last element of the list must not be "-". x will always be a positive integer, no larger than 1000000000. """ def answer(x): # helper: converts int input to base-three string def toBase3(n): convertString = "012" return str(n) if n < 3 else toBase3(n // 3) + convertString[n % 3] # find max power of three such that power of 3 series is still less than x current_sum = 2 current_power = 0 while current_sum +3**(current_power+1) <= x: current_power += 1 current_sum += 3**current_power difference = x - current_sum # convert difference of x and 3-series to base 3 base_three = toBase3(difference) # prepend 0s to base 3 number while len(base_three) < current_power: base_three = '0'+base_three # convert number into instructions string instructions = 'R'+ base_three.replace('0', 'L').replace('1', '-').replace('2', 'R') return list(reversed(instructions)) print(answer(23))
true
79a7c011b0ed82c278939fef81f60c4be7c88320
ashutoshfolane/PreCourse_1
/Exercise_2.py
2,030
4.34375
4
# Exercise_2 : Implement Stack using Linked List. class Node: # Node of a Linked List def __init__(self, data=0, next=None): self.data = data self.next = next class Stack: def __init__(self): # Head is Null by default self.head = None # Check if stack is empty def isEmpty(self): if self.head == None: return True else: return False def push(self, data): if self.head is None: self.head = Node(data) else: newnode = Node(data) newnode.next = self.head self.head = newnode def pop(self): if self.isEmpty(): return None else: poppednode = self.head self.head = self.head.next poppednode.next = None return poppednode.data def peek(self): if self.isEmpty(): return None else: return self.head.data def show(self): headnode = self.head if self.isEmpty(): print("Stack is empty") else: while headnode is not None: print(headnode.data, "->", end=" ") headnode = headnode.next return # Driver code a_stack = Stack() while True: print('push <value>') print('pop') print('peek') print('show') print('quit') do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'push': a_stack.push(int(do[1])) elif operation == 'pop': popped = a_stack.pop() if popped is None: print('Stack is empty.') else: print('Popped value: ', int(popped)) elif operation == 'peek': peek = a_stack.peek() if peek is None: print('Stack is empty') else: print('Peek value: ', int(peek)) elif operation == 'show': a_stack.show() elif operation == 'quit': break
true
6686ad3efa4b2036988196c50b0ab6f56c1903f7
debajyoti-ghosh/Learn_Python_The_Hard_Way
/Exe8.py
527
4.125
4
formatter = "{} {} {} {}" #format can take int as argument print(formatter.format(1, 2, 3, 4)) #.format can take string as argument print(formatter.format('one', 'two', 'three', 'four')) #.format can take boolean as argument print(formatter.format(True, False, True, False)) #.format can take variable as argument print(formatter.format(formatter, formatter, formatter, formatter)) #.format can take line separated string as argument print(formatter.format( "Radio Mrich", "Sunle wale", "Always", "Khus" ))
true
72301ec7c64df86bd3500a01d59262d2037866dd
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/1 Problems on numbers/10_EvenFactors/Demo.py
411
4.125
4
''' Write a program which accept number from user and print even factors of that number Input : 24 Output: 2 4 6 8 12 ''' def PrintEvenFactors(no): if(no<0): no = -no; for i in range(2,int(no/2)+1): if(no%i == 0): print("{} ".format(i),end = " "); def main(): no = int(input("Enter number:")); PrintEvenFactors(no); if __name__ == "__main__": main();
true
408babae6f2e8b73ff56eaab659d421628c46cab
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/6 Problems on characters/2_CheckCapital/Demo.py
408
4.15625
4
''' Accept Character from user and check whether it is capital or not (A-Z). Input : F Output : TRUE Input : d Output : FALSE ''' def CheckCapital(ch): if((ch >= 'A') and (ch <= 'Z')): return True; else: return False; def main(): ch = input("Enter character:"); result = False; result = CheckCapital(ch); print(result); if __name__ == "__main__": main();
true
c3c59745e3de6f17d1f404221048e9ce92aed2e3
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/1 Problems on numbers/22_DisplayTable/Demo.py
348
4.125
4
''' Write a program which accept number from user and display its table. Input : 2 Output : 2 4 6 8 10 12 14 16 18 20 ''' def PrintTable(num): if(num == 0): return; for i in range(1,11): print(num*i,end = " "); def main(): no = int(input("Enter number: ")); PrintTable(no); if __name__ == "__main__": main();
true
f31b354b73c09c00f6c797bbefd5e89017b93fe2
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/1 Problems on numbers/3_Print_Numbers_ReverseOrder/Demo.py
356
4.15625
4
#Accept a positive number from user and print numbers starting from that number till 1 def DisplayNumbers(no1): if(no1 < 0): print("Number is not positive"); else: for i in range(no1,0,-1): print(i); def main(): no1 = int(input("Enter number: ")); DisplayNumbers(no1); if __name__ == "__main__": main();
true
c40119ce76ad55a08ee28a35e120940d643a2b49
DMSstudios/Introduction-to-python
/input.py
726
4.28125
4
#first_name = input('enter your first name: ') #second_name = input('enter your first name: ') #print( f'My name is:' first_name, second_name') #print(f"My name is,{first_name},{second_name}") #print("My name is {} {}" .format(first_name,second_name)) taskList = [23, "Jane", ["Lesson 23", 560, {"currency": "KES"}], 987, (76,"John")] """ Determing type of variable in taskList using an inbuilt function Print KES Print 560 Use a function to determine the length of taksList Change 987 to 789 without using an inbuilt -method (I.e Reverse) Change the name “John” to “Jane” . """ print(type(taskList)) print(taskList[2][2]['currency']) print(taskList[2][1]) print(len(taskList)) taskList[3]=789 print(taskList)
true
7a1ae6018cb2d4f2eba4296c4a1e928de77f9089
Watersilver/cs50
/workspace/pset6/mario/less/mario.py
390
4.125
4
# Draws hash steps from left to right. Last step is double as wide as others from cs50 import get_int # Gets height by user height = -1 while height < 0 or height > 23: height = get_int("Height: ") # Prints half pyramid # Iterate rows for i in range(height): # Iterate collumns for j in range(height + 1): print(" " if j < height - 1 - i else "#", end="") print()
true
78cc32c777d2be27d9a280fd1b8478b02d2d78d2
thakopian/100-DAYS-OF-PYTHON-PROJECT
/BEGIN/DAY_03/005.2-pizza-order-nested-conditional.py
1,149
4.25
4
# 🚨 Don't change the code below 👇 print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L ") add_pepperoni = input("Do you want pepperoni? Y or N ") extra_cheese = input("Do you want extra cheese? Y or N ") # 🚨 Don't change the code above 👆 # Write your code below this line 👇 # size and toppings inputs already established, now write the code # set the bill variable to 0 # recursion example from class notes - https://www.udemy.com/course/100-days-of-code/learn/lecture/17965124#content # start with conditional statement using elif not nested (nested is ok but longer) # then add a nested if / else statement for the pepperoni depending on size # then add a if statement for the cheese (just one option so no alternatives here) # your inputs must exactly match the capital cases or will end up with the wrong sum bill bill = 0 if size == 'S': bill += 15 elif size == 'M': bill += 20 else: bill += 25 if add_pepperoni == 'Y': if size == 'S': bill += 2 else: bill += 3 if extra_cheese == 'Y': bill += 1 print(f"your final bill is ${bill}")
true
70c1be0fa061a29d265589d2fc8390769d219330
thakopian/100-DAYS-OF-PYTHON-PROJECT
/BEGIN/DAY_03/001.flow-if-else-conditional.py
277
4.28125
4
print("Can you the rollercoaster!?") height = int(input("What is your height in cm? ")) ''' #pseudo code if condition: do this else: do this ''' if height >= 125: print("Get on board and ridet he rollercoaster!!!") else: print("sorry not good enough kid!")
true
a8d94cc1c75e67f5f965b11f2ae74973f4147c6a
thakopian/100-DAYS-OF-PYTHON-PROJECT
/BEGIN/DAY_04/04.1-day-4-2-exercise-solution.py
1,817
4.3125
4
# https://repl.it/@thakopian/day-4-2-exercise#main.py # write a program which will select a random name from a list of names # name selected will pay for everyone's bill # cannot use choice() function # inputs for the names - Angela, Ben, Jenny, Michael, Chloe # import modules import random # set varialbles for input and another to modify the input to divide strings by comma names_string = input("Give me everybody's names, separated by a comma. ") names = names_string.split(", ") # get name at index of list (example) print(names[0]) # you can also print len of the names to get their range print(len(names)) # set random module for the index values # > this is standard format > random.randint(0, x) # using the len as a substitute for x in the randint example with a variable set to len(names) num_items = len(names) # num_items - 1 in place of x to get the offset of the len length to match a starting 0 position on the index values # set the function to a variable choice = random.randint(0, num_items - 1) # assign the mutable name variable with an index of the choice variable to another variable for storing the index value of the name based on the index vaule person_who_pays = names[choice] # print that stored named variable out with a message print(person_who_pays + " is going to buy the meal today") ####### # This exercise isn't a practical application of random choice since it doesn't use the .choice() function # the idea is to replace variables, learn by retention and problem solve # create your own random choice function to understand how the code can facilitate that withouth the .choice() function # that way you learn how to go through problem challenges and how to create your own workaround in case the out of the box content isn't everything you need for a given problem
true
ae31c6cde30707ffccaf9bc0ed9eb70756f11514
xc13AK/python_sample
/week_v2.0.py
655
4.46875
4
#!/usr/bin/python3.4 #-*- coding:UTF-8 -*- import datetime #get the feature day from input year=int(input("enter the year:")) month=int(input("enter the month:")) day=int(input("enter the day:")) new=datetime.date(year,month,day) print("the day is %s-%s-%s"%(new.year,new.month,new.day)) weekday=int(new.weekday()) if weekday==0: print("it is MONDAY!") elif weekday==1: print("it is TUSDAY!") elif weekday==2: print("it is WENDAY!") elif weekday==3: print("it is THSDAY!") elif weekday==4: print("it is FRIDAY!") elif weekday==5: print("it is SARTDAY!") elif weekday==6: print("it is SUNDAY!") else: print("UNKNOWN")
true
3b105b43f202b9ca5f35fe8a65a3e5ce7ca4815c
RandomStudentA/cp1404_prac
/prac_04/lists_warmup.py
984
4.34375
4
numbers = [3, 1, 4, 1, 5, 9, 2] # What I thought it would print: 3 # What it printed: 3 print(numbers[0]) # What I thought it would print: 2 # What it printed: 2 print(numbers[-1]) # What I thought it would print: 1 # What it printed: 1 print(numbers[3]) # What I thought it would print: 2 # What it printed: [3, 1, 4, 1, 5, 9] print(numbers[:-1]) # What I thought it would print: 1, 5 # What it printed: 1 print(numbers[3:4]) # What I thought it would print: True # What it printed: True print(5 in numbers) # What I thought it would print: False # What it printed: False print(7 in numbers) # What I thought it would print: False # What it printed: 0 print("3" in numbers) # What I thought it would print: 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 # What it printed: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] print(numbers + [6, 5, 3]) # Question 1 numbers[0] = "ten" print(numbers) # Question 2 numbers[-1] = 1 print(numbers) # Question 3 print(numbers[2:7]) # Question 4 print(9 in numbers)
true
c67eee77631f9ef0d3a325eadeaab4039f3d8b1b
Systematiik/Python-The-Hard-Way
/ex15_1.py
429
4.21875
4
# reading textfiles by user input # open() opens file when in same directory # read() reads file from sys import argv # takes argument and puts under variable txt and function open, opens filename filename = input("Give me a text file to read (.txt): ") txt = open(filename) print(f"Here's your file {filename}: ") print(txt.read()) # prints contents of file into terminal txt.close() # closes file after reading
true
ad8927d675907b661391b785026adaae2f33d3bd
Systematiik/Python-The-Hard-Way
/ex15.py
702
4.15625
4
#reading textfiles by passing args and user input #open() opens file when in same directory #read() reads file from sys import argv script, filename = argv #takes argument and puts under variable txt and function open, opens filename txt = open(filename) print(f"Here's your file {filename}: ") print(txt.read()) #prints contents of file into terminal txt.close() print("Type the filename again: ") file_again = input("> ") #asks for the name of the file again #sets the file_again as a parameter for the open function in the variable txt_again txt_again = open(file_again) #reads and prints the file txt_again into terminal print(txt_again.read()) txt_again.close()
true
9c738875350bec148a14096eec94605fe89c99b0
vibhorsingh11/hackerrank-python
/04_Sets/02_SymmetricDifference.py
467
4.3125
4
# Given 2 sets of integers, M and N, print their symmetric difference in ascending order. The term symmetric difference indicates # those values that exist in either M or N but do not exist in both. # Enter your code here. Read input from STDIN. Print output to STDOUT a, b = (int(input()), input().split()) c, d = (int(input()), input().split()) x = set(b) y = set(d) p = y.difference(x) q = x.difference(y) r = p.union(q) print('\n'.join(sorted(r, key=int)))
true
7276c10f1e342e0f6ca8170a299fc4471cd955a6
menasheep/CodingDojo
/Python/compare_arrays.py
1,165
4.15625
4
list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] if list_one == list_two: print True print "These arrays are the same!" else: print False print "These arrays are different. Womp womp." # ***** list_one = [1,2,5,6,5] list_two = [1,2,5,6,5,3] if list_one == list_two: print True print "These arrays are the same!" else: print False print "These arrays are different. Womp womp." # ***** list_one = [1,2,5,6,5,16] list_two = [1,2,5,6,5] if list_one == list_two: print True print "These arrays are the same!" else: print False print "These arrays are different. Womp womp." # ***** list_one = ['celery','carrots','bread','milk'] list_two = ['celery','carrots','bread','cream'] if list_one == list_two: print True print "These arrays are the same!" else: print False print "These arrays are different. Womp womp." # **Output** # C:\Users\Mal\Desktop\Coding Dojo\Python>python compare_arrays.py # True # These arrays are the same! # These arrays are different. Womp womp. # These arrays are different. Womp womp. # These arrays are different. Womp womp. # C:\Users\Mal\Desktop\Coding Dojo\Python>
true
0dfe39b515dc391753d29b540d6af13abefd8269
yshshadow/Leetcode
/201-250/211.py
2,515
4.1875
4
# Design a data structure that supports the following two operations: # # void addWord(word) # bool search(word) # search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. # # Example: # # addWord("bad") # addWord("dad") # addWord("mad") # search("pad") -> false # search("bad") -> true # search(".ad") -> true # search("b..") -> true # Note: # You may assume that all words are consist of lowercase letters a-z. class TrieNode: def __init__(self): self.is_word = False self.children = dict() class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ root = self.root for ch in word: if ch not in root.children: root.children[ch] = TrieNode() root = root.children[ch] root.is_word = True def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ root = self.root return self.dfs(root, word, 0) def dfs(self, node, word, index): if index == len(word) - 1: if word[index] != '.' and word[index] in node.children and node.children[word[index]].is_word: return True elif word[index] == '.' and any(node.children[child].is_word for child in node.children): return True else: return False else: if word[index] == '.': return any(self.dfs(node.children[child], word, index + 1) for child in node.children) elif word[index] in node.children: return self.dfs(node.children[word[index]], word, index + 1) else: return False # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word) s = WordDictionary() s.addWord('bad') s.addWord('dad') s.addWord('mad') print(s.search('pad')) print(s.search('bad')) print(s.search('.ad')) print(s.search('b..')) print(s.search('c..')) print(s.search('...'))
true
9137c399473cded62f26e36e512433eb4faaa00f
yshshadow/Leetcode
/1-50/48.py
1,614
4.125
4
# You are given an n x n 2D matrix representing an image. # # Rotate the image by 90 degrees (clockwise). # # Note: # # You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. # # Example 1: # # Given input matrix = # [ # [1,2,3], # [4,5,6], # [7,8,9] # ], # # rotate the input matrix in-place such that it becomes: # [ # [7,4,1], # [8,5,2], # [9,6,3] # ] # Example 2: # # Given input matrix = # [ # [ 5, 1, 9,11], # [ 2, 4, 8,10], # [13, 3, 6, 7], # [15,14,12,16] # ], # # rotate the input matrix in-place such that it becomes: # [ # [15,13, 2, 5], # [14, 3, 4, 1], # [12, 6, 8, 9], # [16, 7,10,11] # ] class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ # length = len(matrix) # for x in range(int(length / 2)): # for y in range(x, length - x - 1): # a1, b1 = x, y # a2, b2 = b1, length - a1 - 1 # a3, b3 = b2, length - a2 - 1 # a4, b4 = b3, length - a3 - 1 # temp = matrix[a4][b4] # matrix[a4][b4] = matrix[a3][b3] # matrix[a3][b3] = matrix[a2][b2] # matrix[a2][b2] = matrix[a1][b1] # matrix[a1][b1] = temp matrix[::] = zip(*matrix[::-1]) s = Solution() m = [ [5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16] ] s.rotate(m) print(m)
true
b99592d95dcd3f2ce168808da0f08c2b5a83da5d
yshshadow/Leetcode
/51-100/94.py
1,376
4.125
4
# Given a binary tree, return the inorder traversal of its nodes' values. # # For example: # Given binary tree [1,null,2,3], # 1 # \ # 2 # / # 3 # return [1,3,2]. # # Note: Recursive solution is trivial, could you do it iteratively? # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] self.iterative(root, res) # self.recursive(root, res) return res def recursive(self, root, res): if not root: return self.recursive(root.left, res) res.append(root.val) self.recursive(root.right, res) def iterative(self, root, res): if not root: return stack = [] top = root while top or len(stack) != 0: while top: stack.append(top) top = top.left if len(stack) != 0: top = stack[len(stack) - 1] res.append(top.val) stack.pop() top = top.right s = Solution() root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) s.inorderTraversal(root)
true
c73e65896ce89c0ae540e9330a0214a0a5ba5a93
yshshadow/Leetcode
/51-100/88.py
1,074
4.21875
4
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # # Note: # You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. # class Solution: def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ nums1[m: m + n] = nums2 # copy nums2 into nums1 slow, fast = 0, m if m == 0 or n == 0: return while fast < m + n: if nums1[slow] > nums1[fast]: temp = nums1[slow] nums1[slow] = nums1[fast] nums1[fast] = temp slow += 1 if slow == fast: fast += 1 s = Solution() nums1 = [4,5,6,0,0,0] m = 3 nums2 = [1,2,3] n = 3 s.merge(nums1, m, nums2, n) print(nums1)
true
310b99e9b68a2f81323c619977371e3638fc66b1
yshshadow/Leetcode
/300-/572.py
1,583
4.21875
4
# Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. # # Example 1: # Given tree s: # # 3 # / \ # 4 5 # / \ # 1 2 # Given tree t: # 4 # / \ # 1 2 # Return true, because t has the same structure and node values with a subtree of s. # Example 2: # Given tree s: # # 3 # / \ # 4 5 # / \ # 1 2 # / # 0 # Given tree t: # 4 # / \ # 1 2 # Return false. # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ return self.traverse(s, t) def traverse(self, s, t): return s is not None and (self.equal(s, t) or self.traverse(s.left, t) or self.traverse(s.right, t)) def equal(self, s, t): if not s and not t: return True elif not s or not t: return False else: return s.val == t.val and self.equal(s.left, t.left) and self.equal(s.right, t.right) so = Solution() s = TreeNode(3) s.left = TreeNode(4) s.right = TreeNode(5) s.left.left = TreeNode(1) s.right.left = TreeNode(2) t = TreeNode(3) t.left = TreeNode(1) t.right = TreeNode(2) print(so.isSubtree(s, t))
true
b1868ddb16d474b647edabf6aa4d8233a6d6fde4
yshshadow/Leetcode
/101-150/103.py
1,115
4.15625
4
# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). # # For example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its zigzag level order traversal as: # [ # [3], # [20,9], # [15,7] # ] # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] self.zigzag(root, res, 1) for x in range(len(res)): if x % 2 != 0: res[x].reverse() return res def zigzag(self, root, res, level): if not root: return if len(res) < level: res.append([]) res[level - 1].append(root.val) self.zigzag(root.left, res, level + 1) self.zigzag(root.right, res, level + 1)
true
584b822e45b7cb26ccb8e5cacc66cdb8eae399a4
yshshadow/Leetcode
/251-300/261.py
1,396
4.125
4
# Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. # # Example 1: # # Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]] # Output: true # Example 2: # # Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]] # Output: false # Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges. # class Solution(object): def validTree(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool """ m = [[0 for _ in range(n)] for _ in range(n)] for i, j in edges: m[i][j] = 1 # m[j][i] = 1 visited = set() visited.add(0) def dfs(m, i): for j, e in enumerate(m[i]): if e == 0: continue if j in visited: return False visited.add(j) if not dfs(m, j): return False return True if not dfs(m, 0): return False if len(visited) != n: return False return True s = Solution() print(s.validTree(5, [[0, 1], [0, 2], [0, 3], [1, 4]]))
true
ee7a31838dbba2216f509bfd2a764b6d825cbe4a
jamiezeminzhang/Leetcode_Python
/_Google/282_OO_Expression_Add_Operators.py
1,717
4.1875
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 22 10:57:57 2016 282. Expression Add Operators Total Accepted: 7924 Total Submissions: 33827 Difficulty: Hard Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. Examples: "123", 6 -> ["1+2+3", "1*2*3"] "232", 8 -> ["2*3+2", "2+3*2"] "105", 5 -> ["1*0+5","10-5"] "00", 0 -> ["0+0", "0-0", "0*0"] "3456237490", 9191 -> [] *** My answer didn't consider the case of "105", 5 -> ["1*0+5","10-5"] that 105 could be regarded as 10 and 5 should not transcript into stack first 注意:包含前导0的运算数是无效的。 例如,通过"00+9"获得目标值9是不正确的。 @author: zzhang04 """ class Solution(object): def addOperators(self, num, target): res, self.target = [], target for i in range(1,len(num)+1): if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number self.dfs(num[i:], num[:i], int(num[:i]), int(num[:i]), res) # this step put first number in the string return res def dfs(self, num, temp, cur, last, res): if not num: if cur == self.target: res.append(temp) return for i in range(1, len(num)+1): val = num[:i] if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number self.dfs(num[i:], temp + "+" + val, cur+int(val), int(val), res) self.dfs(num[i:], temp + "-" + val, cur-int(val), -int(val), res) self.dfs(num[i:], temp + "*" + val, cur-last+last*int(val), last*int(val), res)
true
f791001ef212e94de7adbf9df8df4812bc198622
jamiezeminzhang/Leetcode_Python
/others/073_Set_Matrix_Zeroes.py
1,863
4.21875
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 28 10:55:49 2016 73. Set Matrix Zeroes Total Accepted: 69165 Total Submissions: 204537 Difficulty: Medium Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. click to show follow up. Follow up: Did you use extra space? A straight forward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution? **** Constant space solution ******* class Solution(object): def setZeroes(self, matrix): m, n, first_row_has_zero = len(matrix), len(matrix[0]), not all(matrix[0]) for i in range(1,m): for j in range(n): if matrix[i][j] == 0: matrix[i][0]=0 matrix[0][j]=0 for i in range(1,m): for j in range(n-1,-1,-1): # 这里希望最后再算第一列。如果0,0是0,那么希望第一列最后也变成0. if matrix[i][0]==0 or matrix[0][j]==0: matrix[i][j] = 0 if first_row_has_zero: matrix[0] = [0]*n @author: zeminzhang """ class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ m,n = len(matrix), len(matrix[0]) row,col = [],[] for i in range(m): for j in range(n): if matrix[i][j] == 0: row.append(i) col.append(j) for i in row: for j in range(n): matrix[i][j] = 0 for i in col: for j in range(m): matrix[j][i] = 0
true
442531f67bbcb62c307af612b26aa1d4d12d5bcf
gkalidas/Python
/practice/censor.py
658
4.3125
4
#Write a function called censor that takes two strings, text and word, as input. #It should return the text with the word you chose replaced with asterisks. #For example: #censor("this hack is wack hack", "hack") #should return: #"this **** is wack ****" #Assume your input strings won't contain punctuation or upper case letters. #The number of asterisks you put should correspond to the number of letters in the censored word. def censor(text,word): text = text.split(" ") for char in range(0,len(text)): if text[char]==word: text[char] = len(text[char]) * "*" else: text[char]=text[char] text = " ".join(text) return text
true
6ae7d434d182efebea2ee20dd122860f6bafde8b
TamaraJBabij/ReMiPy
/dictOps.py
550
4.15625
4
# -*- coding: utf-8 -*- # Applies a function to each value in a dict and returns a new dict with the results def mapDict(d, fn): return {k: fn(v) for k,v in d.items()} # Applies a function to each matching pair of values from 2 dicts def mapDicts(a, b, fn): return {k: fn(a[k], b[k]) for k in a.keys()} # Adds matching values from 2 dicts with the same keys def addDicts(a,b): return mapDicts(a, b, lambda x, y: x + y) # Multiply all values in a dict by the same constant def multiplyDict(d, c): return mapDict(d, lambda x: x * c)
true
085f60472146523cbf36d36e75ba002cba379e10
nachoba/python
/introducing-python/003-py-filling.py
2,302
4.59375
5
# Chapter 3 : Py Filling: Lists, Tuples, Dictionaries, and Sets # ------------------------------------------------------------------------------ # Before started with Python's basic data types: booleans, integers, floats, and # strings. If you thinks of those as atoms, the data structures in this chapter # are like molecules. That's, we combine those basic types in more complex ways. # Lists and Tuples # ---------------- # Most computer languages can represent a sequence of items indexed by their in- # teger position: first, second, and so on down to the last.Python's strings are # sequences, sequences of characters. # Python has two other sequence structures: tuples and lists. These contain zero # or more elments. Unlike strings, the elements can be of different types. # In fact, each element can be any Python object. This lets you create struc- # tures as deep and complex as you like. # The difference between lists and tuples is that tuples are immutable; when you # assign elements to a tuple, they can't be changed. # Lists are mutable, meaning you can insert and delete elements. # Lists # ----- # Lists are good for keeping track of things by their order, especially when the # order and contents might change. Unlike strings, lists are mutable.You can add # delete, and remove elements. # Create with [] and list() # ------------------------- # A list is made from zero or more elements, separated by commas, and surrounded # by square brackets: empty_list = [ ] weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] big_birds = ['emu', 'ostrich', 'cassowary'] first_names = ['Graham', 'John', 'Terry', 'Terry', 'Michael'] # You can also make an empty list with the "list()" function: another_empty_list = list() # In a list values do not need to be unique. If you know you only want to keep # track of unique values and do not care about order, a Python "set" might be a # better choice than a list. print(weekdays) print(another_empty_list) # Conver other Data Types to Lists with list() # -------------------------------------------- # Python's "list()" function, converts other data types to lists: cat_list = list('cat') print(cat_list) # This example converts a tuple to a list: a_tuple = ('ready', 'fire', 'aim') print(list(a_tuple))
true
209d380eeb75040a3911371e2b1297f210c66adb
berketuna/py_scripts
/reverse.py
253
4.40625
4
def reverse(text): rev_str = "" for i in range(len(text)): rev_str += text[-1-i] return rev_str while True: word = raw_input("Enter a word: ") if word == "exit": break reversed = reverse(word) print reversed
true
e1752393679416438c2c0c1f1d4015d3cc776f58
Jaredbartley123/Lab-4
/Lab 4.1.3.8.py
783
4.21875
4
#lab 3 def isYearLeap(year): if year < 1582: return False elif year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True else: return False def daysInMonth(year, month): leap = isYearLeap(year) if leap and month == 2: return 29 elif month == 2: return 28 elif month == 4 or month == 6 or month == 9 or month == 11: return 30 else: return 31 def dayOfYear(year, month, day): dayInYear = 0 for days in range (month - 1): dayInYear += daysInMonth(year, days+1) dayInYear += day return(dayInYear) print(dayOfYear(2000, 12, 31))
true
a8d29b3e2247885d8dd9648343f7b0ba27b83a4f
sathappan1989/Pythonlearning
/Empty.py
579
4.34375
4
#Starting From Empty #Print a statement that tells us what the last career you thought of was. #Create the list you ended up with in Working List, but this time start your file with an empty list and fill it up using append() statements. jobs=[] jobs.append('qa') jobs.append('dev') jobs.append('sm') jobs.append('po') print(jobs) #Print a statement that tells us what the first career you thought of was. print('first carrer '+ jobs[0].upper()+'!') #Print a statement that tells us what the last career you thought of was. print('first carrer '+ jobs[-1].upper()+'!')
true
f04c7247ba0b372240ef2bc0f118f340b0c9054b
angela-andrews/learning-python
/ex9.py
565
4.28125
4
# printing # Here's some new strange stuff, remember type it exactly. # print the string on the same line days = "Mon Tue Wed Thu Fri Sat Sun" # print Jan on the same line as and the remaining months on new lines months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print("Here are the days: ", days) print("Here are the months: ", months) # this allows you to break your string up over multiple lines. print(""" There's something going on here. With the the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """)
true
c73358f413572fdfa0e1f309c4d0e762e50c5ef2
angela-andrews/learning-python
/ex33.py
1,268
4.40625
4
# while loops i = 0 numbers = [] while i < 6: print(f"At the top is {i}") numbers.append(i) i = i + 1 print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num) # convert while-loop to a function def test_loop(x): i = 0 numbers = [] while i < x: print(f"At the top is {i}") numbers.append(i) i = i + 1 print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num) test_loop(11) #=============================================== def test_loop2(x, y): i = 0 numbers = [] while i < x: print(f"At the top is {i}") numbers.append(i) i = i + y print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num) test_loop2(29,5) #====================================== # testing out turning a while into a for using a range def test_loop3(y): numbers = [] numbers = list(range(y)) print(numbers) for i in numbers: print(f"Range made it easy to create a list of numbers: {i}") test_loop3(26)
true
49bb1b18646aa0aad8ec823f7206ccb08709e36a
rojit1/python_assignment
/q9.py
247
4.375
4
# 9. Write a Python program to change a given string to a new string where the first # and last chars have been exchanged. def exchange_first_and_last(s): new_s = s[-1]+s[1:-1]+s[0] return new_s print(exchange_first_and_last('apple'))
true
62ed4994bb2ff26ee717f135a50eddff151e0643
rojit1/python_assignment
/q27.py
298
4.21875
4
# 27. Write a Python program to replace the last element in a list with another list. # Sample data : [1, 3, 5, 7, 9, 10], [2, 4, 6, 8] # Expected Output: [1, 3, 5, 7, 9, 2, 4, 6, 8] def replace_last(lst1, lst2): return lst1[:-1]+lst2 print(replace_last([1, 3, 5, 7, 9, 10], [2, 4, 6, 8]))
true
4f9ff83562f99c636dee253b7bfdbac93f46facc
rojit1/python_assignment
/functions/q3.py
263
4.46875
4
# 3. Write a Python function to multiply all the numbers in a list. # Sample List : (8, 2, 3, -1, 7) # Expected Output : -336 def multiply_elements(lst): ans = 1 for i in lst: ans *= i return ans print(multiply_elements([8, 2, 3, -1, 7]))
true
7b0614ad3f05e76bb8ca6400bc9e230f130c3d5e
xala3pa/Introduction-to-Computer-Science-and-Programming-with-python
/week4/Problems/L6PROBLEM2.py
960
4.1875
4
def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' ans = () index = 1 for c in aTup: if index % 2 != 0: ans += (c,) index += 1 return ans def oddTuples2(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' # a placeholder to gather our response rTup = () index = 0 # Idea: Iterate over the elements in aTup, counting by 2 # (every other element) and adding that element to # the result while index < len(aTup): rTup += (aTup[index],) index += 2 return rTup def oddTuples3(aTup): ''' Another way to solve the problem. aTup: a tuple returns: tuple, every other element of aTup. ''' # Here is another solution to the problem that uses tuple # slicing by 2 to achieve the same result return aTup[::2]
true
6b588b64560ceacfba4cbe1676eae2d565a28358
bshep23/Animation-lab
/Animation.py
1,388
4.15625
4
# ------------------------------------------------- # Name: Blake Shepherd and Lilana Linan # Filename: Animation.py # Date: July 31th, 2019 # # Description: Praticing with animation # # ------------------------------------------------- from graphics import * import random class Fish: """Definition for a fish with a body, eye, and tail""" def __init__(self, win, position): """constructs a fish made of 1 oval centered at `position`, a second oval for the tail, and a circle for the eye""" red = random.randint(0,255) green = random.randint(0,255) blue = random.randint(0,255) # body p1 = Point(position.getX()-40, position.getY()-20) p2 = Point(position.getX()+40, position.getY()+20) self.body = Oval( p1, p2 ) self.body.setFill(color_rgb(red, green, blue)) # tail p1 = Point(position.getX()+30, position.getY()-30) p2 = Point(position.getX()+50, position.getY()+30) self.tail = Oval( p1, p2 ) self.tail.setFill( "black" ) # eye center2 = Point( position.getX()-15, position.getY()-5 ) self.eye = Circle( center2, 5 ) self.eye.setFill( "black" ) def draw( self, win ): """draw the fish to the window""" self.body.draw( win ) self.tail.draw( win ) self.eye.draw( win ) x = GraphWin("Hello", 600 , 400) Bob = Fish(x, Point(300,200)) Bob.draw(x)
true
baefdc82a2d2af26940678bd040c871350cc6a77
swang2017/python-factorial-application
/factorial.py
390
4.15625
4
try: input_number = int(raw_input("please enter an integer\n")) except ValueError: print("Hey you cannot enter alphabets") except FileNotFound: print("File not found") else: print("no exceptions to be reported") # result = 1 # for index in range (1, input_number+1): # result = result * index # # print("The factorial of " + str(input_number) + " is " + str(result))
true
2b7470c9569abd1a45a8ab79b20e9f82418dc941
savithande/Python
/strings1.py
1,290
4.4375
4
# single quote character str = 'Python' print(str) # fine the type of variable print(type(str)) print("\n") # double quote character str = "Python" print(str) # fine the type of variable print(type(str)) print("\n") # triple quote example str = """Python""" print(str) # fine the type of variable print(type(str)) print("\n") # methods of string # 1) finding the index value string = "Python" print("Python".index("t")) print("Python_programing_language".index("_")) print ("\n") # join the list of strings by using join condition combine_string = "%".join(["1","2","3"]) print(combine_string) print("\n") # split the string based on the condition by using the split() print("1:2:3:4".split(":")) print("1 2 3 4".split(" ")) print("1,2,3,4,5,6".split(",")) print("\n") # accessing the individual character in the string # by using the index values of the given string # the python index value stating with "0" string = "Python" print(string[4]) print(string[0]) print("\n") # formatting methods usage examples print("hii, my name is %s" % ("Python")) print("%s is a one of the %s language" % ("Python","scripting")) print("\n") # truth value testing of string using boolean(bool) keyword print(bool("")) # '0' argument method print(bool("Python")) # with argument method
true
a2fb730cc784a3720dc845069b9a0e1a4821adbe
jovian34/j34_simple_probs
/elementary/05sum_multiples/sum_of_multiples.py
1,239
4.1875
4
# http://adriann.github.io/programming_problems.html # Write a program that asks the user for a number n and prints # the sum of the numbers 1 to n # Modify the previous program such that only multiples of three or # five are considered # in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17 def get_number_from_user(): print('Enter a number: ', end='') return input() def sum_range(number): sum_total = 0 for i in range(1, number + 1): print(i, end='') sum_total = sum_total + i print('...{}'.format(sum_total)) return sum_total def sum_range_of_multiples(number): sum_total = 0 for i in range(1, number + 1): if i % 3 == 0 or i % 5 == 0: sum_total = sum_total + i print('{} ... {}'.format(i, sum_total)) return sum_total def main(): user_number = get_number_from_user() try: user_number = int(user_number) except: print('This program only works on integer values.') print('Please try again') return main() sum_num = sum_range_of_multiples(user_number) print('The sum of the multiple of 3 and 5 from 1 to ' '{} is {}.'.format(user_number, sum_num)) if __name__ == '__main__': main()
true
b29e7eba5620eb7d8c54715543b62cae65aaeee4
yashgugale/Python-Programming-Data-Structures-and-Algorithms
/NPTEL Course/Concept Practices/inplace_scope_exception2.py
1,222
4.1875
4
L1 = [10, 20 ,30] print("Global list L: ", L1) def f1(): L1[2] = 500 print("L1 from function on in place change is is: ", L1) print("\nShallow copy of L1 to L2") L2 = L1 L2.append(600) print("Lists L1 and L2 are: L1:", L1, "L2: ", L2) print("\nDeep copy of L1 to L3") L3 = L1.copy() L3.append(700) print("Lists L1 and L3 are: L1:", L1, "L3: ", L3) f1() print("\nGlobally L1 after all the changes is: ", L1) # how can we, from a local function without using a 'global' or a 'nonlocal' # change the value of a LIST used globally? # It is true for both dimensions of mutability: 1. in place change 2. grow/shrink, so, # is this property applicable to all mutable data types? List, Dict, Set? S = { 10, 20, 30} print("\nThe global value of set S", S) def f2(): S.add(400) print("The values of set S are: ", S) f2() print("The value of set S after function f2 is: ", S) D = { 'a' : 10, 'b' : 20, 'c' : 30} print("\nThe dictionary is: ", D) def f3(): D.update({'d' : 40}) print("The value of dict D is: ", D) f3() print("The value of dict D after function f3 is: ", D) # as we can see, we are able to do do without using 'global' or 'nonlocal' # why does this work?
true
9e750b872b0d154f74f64353e71b0bdeb7e4f122
nguyeti/mooc_python_10_app
/OOP/example.py
1,880
4.21875
4
class Machine: def __init__(self): print("I am a Machine") class DrivingMachine(Machine): def __init__(self): print("I am a DrivingMachine") def start(self): print("Machine starts") class Bike(DrivingMachine): def __init__(self, brand, color): self.brand = brand # __attrName > makes it private self.color = color print("I am a Bike") def start(self): print("Override : Bike starts") def getattr(self, name): return self.name class Car(DrivingMachine): def __init__(self, brand, color): self.__color = color # __attrName > makes it private Can't be seen and accessed from outside self._brand = brand # _A > makes it protected Like a public member, but they shouldn't be directly accessed from outside. print("I am a Car") def start(self): print("Override : car starts") def changeColor(self, color): self.__color = color # machine = Machine() # d = DrivingMachine() # bike = Bike("Suzuki", "red") # car = Car("Toyota", "black") # d.start() # calls the parent's start() method # bike.start() # car.start() # # print("Bike : " + bike.brand + " : " + bike.color) # print("Bike : " + getattr(bike,"brand") + " : " + getattr(bike,"color")) # print(hasattr(bike, "color")) # setattr(bike, "color", "yellow") # print("Bike : " + getattr(bike,"brand") + " : " + getattr(bike,"color")) # # print(issubclass(Bike,Machine)) # # print(issubclass(Bike,DrivingMachine)) # # print(isinstance(bike,Machine)) # # print(isinstance(bike,DrivingMachine)) # # # print("Car : " + car.brand + " : " + car.color) # AttributeError: 'Car' object has no attribute 'brand' # # print("Car : " + getattr(car, "brand") + " : " + car.color) # pareil fonctionne pas # print("Car :" + car._Car__color) # car._Car__color ="purple" # print("Car :" + car._Car__color)
true
eb2b71845ab019e7fa8131669bf3777e6d93c3d5
nguyeti/mooc_python_10_app
/ex1_c_to_f.py
541
4.1875
4
""" This script converts C temp into F temp """ # def celsiusToFahrenheit(temperatureC): # if temperatureC < -273.15: # print("That temperature doesn't make sense!") # else: # f = temperatureC * (9/5) + 32 # return f temperatures = [10, -20, -289, 100] def writer(temperatures): """This is the function to convert C into F""" with open("example.txt",'w') as file: for c in temperatures: if c > -273.15: f = c * (9/5) + 32 file.write(str(f) + "\n")
true
1f90807c81934fd38d38dd8bd5e42102813efa86
c18441084/Python
/Labtest1.py
1,056
4.375
4
#Function to use Pascal's Formula def make_new_row(old_row, limit): new_row = [] new_list = [] L=[] i=0 new_row = old_row[:] while i < limit: new_row.append(1) long = len(new_row) - 1 j=0 h=0 if i ==0: new_list = new_row[:] #Print list of lists print("Printing list of lists, one list at a time: ") print(old_row) #Formula for Pascal Triangle for j in range(new_row[0], long): new_row[j]= new_list[h] + new_list[h+1] j = j+1 h = h+1 new_list = new_row[:] #Printing lists print(new_row) #Adding list into whole lists L.append(new_row) i=i+1 print("Print whole list of lists: ") print(L) #Asking user for height of triangle ans = input("Enter the desired height of Pascal's triangle: ") lim = int(ans) old_row = [1,1] #Sending the row and limit to the function make_new_row(old_row, lim)
true
d0092057d615ba0067f48a07be80c37e423b0cd9
bachns/LearningPython
/exercise24.py
278
4.3125
4
# Write a Python program to test whether a passed letter is a vowel or not. def isVowel(v): vowels = ("u", "e", "o", "a", "i") return v in vowels vowel = input("Enter a letter: ") if isVowel(vowel): print("This is a vowel") else: print("This isn't a vowel")
true
ece0d3f409b258a7a098917b0a865f2569c8eb10
bachns/LearningPython
/exercise27.py
255
4.15625
4
# Write a Python program to concatenate all elements in a list into # a string and return it def concatenate(list): conc_str = "" for number in list: conc_str += str(number) return conc_str print(concatenate([3, 4, 1000, 23, 2]))
true
60fe76e0b3bd43e87dde6e7e7d77ad4d5108c326
bachns/LearningPython
/exercise7.py
315
4.25
4
# Write a Python program to accept a filename from the user and print # the extension of that. # Sample filename : abc.java # Output : java filename = input("Enter file name: ") parts = filename.rsplit(".", 1) print("Extension:" + parts[-1]) index = filename.rfind(".") + 1 print("Extension:" + filename[index:])
true
c3a0e29d457803d6bbae306b86c2ed98e476d77d
bachns/LearningPython
/exercise21.py
334
4.25
4
# Write a Python program to find whether a given number (accept from the user) # is even or odd, print out an appropriate message to the user def check_number(number): if number % 2: return "This is an odd number" return "This is an even number" number = int(input("Enter a number: ")) print(check_number(number))
true
a2bc4a35e26f590c738178bdaffac36e42b56993
hitendrapratapsingh/python_basic
/user_input.py
229
4.28125
4
# input function #user input function name = input("type your name") print("hello " + name) #input function type alwase value in string for example age = input("what is your age") #because herae age is string print("age: " + age)
true
750900f9be03aac96ec39601a667b6c3948c0ad3
injoon5/C3coding-python
/2020/04/22/02.py
388
4.125
4
height =int(input("your height : ")) if height<110: print("Do not enter!") if height>= 110: print("have a nice time!") if height == 110: print("perfect!") if height != 110: print("Not 110.") if 100 <= height <110: print("Next year~") print("Booltype = ", height< 110,height >= 110, height == 110) print("Booltype =", height != 110, 100 <= height < 110)
true
c1a3c8305447e8ef79212e07731b4744759074f7
shakibaSHS/pythonclass
/s3h_1_BMI.py
245
4.15625
4
weight = int(input('input your weight in kg\n weight=')) height = float(input('input your height in meter\n height=')) def BMI(weight , height): B = weight / (height ** 2) return B print(f'Your BMI is= {BMI(weight , height)}')
true
b2b54b45e806acff0d0d7efee18c0bf5b6b4d0b0
abhishek5135/Python_Projects
/snakewatergun.py
1,550
4.125
4
import time import random def turn(num): player_1=0 player_2=0 listcomputer=['snake','water','gun'] computer=random.choice(listcomputer) num2=0 while(num2!=num): print("snake","water","gun") players_inpu = input("Player 1 Enter your choice from above ") print(f"computer choice {computer}") if(computer=='snake' and players_inpu=='water'): player_2+=1 elif (computer=='gun' and players_inpu=='water'): player_1+=1 elif(computer=='water' and players_inpu=='water'): print("Turn draw") elif(computer=='gun' and players_inpu=='snake'): player_2+=1 elif (computer=='water' and players_inpu=='snake'): player_1+=1 elif(computer=='snake' and players_inpu=='snake'): print("Turn draw") elif(computer=='snake' and players_inpu=='gun'): player_1+=1 elif (computer=='water' and players_inpu=='gun'): player_2+=1 elif(computer=='gun' and players_inpu=='gun'): print("Turn draw") num2+=1 if(player_1>player_2): print("You are winner of This game ") elif (player_2>player_1): print("You lose the game") print("Better luck next time") if __name__ == "__main__": start=time.time() num3=int(input("Enter how Turns you want to play ")) turn(num3) end=time.time() print(f"Runtime of the program is {end - start}")
true
16cf1423d8a7840f49b7ad206f0f8b9f5104a514
meet29in/Sp2018-Accelerated
/students/mathewcm/lesson04/trigrams.py
1,217
4.125
4
#!/usr/bin/env Python """ trigrams: solutions to trigrams """ sample = """Now is the time for all good men to come to the aid of the country""" import sys import random words = sample.split() print(words) def parse_file(filename) """ parse text file to makelist of words """ with open(filename) as infile: words = [] for line in infile: print(line) wrds = line.strip().split() # print(wrds) words.extend(wrds) return words def build_trigram(words): tris = {} for i in range(len(words) - 2): first = words[i] second = words[i + 1] third = words[i + 2] # print(first, second, third) tris[(first, second)] = [third] # print(tris) return tris def make_new_text(trigram) pair = random.choice(list(trigram.keys())) sentence = [] sentence.extend(pair) for i in range(10): followers = trigram[pair] sentence.append(random.choice(followers)) pair = tuple(sentence[-2]) print(pair) return sentence if __name__ == "__main__" words = parse_file("sherlock_small.txt") print(words) # trigram = build_trigram(words)
true
3580488590a479d85b7e0bce53567e00608b2d61
ShadowStorm0/College-Python-Programs
/day_Of_The_Week.py
824
4.34375
4
#Day of Week List Week = ['I can only accept a number between 1 and 7. Please try again.', 'Sunday', 'Monday', 'Tuesday', 'Wedensday', 'Thursday', 'Friday' ,'Saturday'] #Introduce User to Program print('Day of the Week Exercise') print('Enter a number for the day of the week you want displayed.') #Input prompt / Input Validation while True: try: #User Input userInput = int(input("(Days are numbered sequentially from 1 - 7, starting with Sunday.): ")) #Check if Number except ValueError: print("I can only accept a number between 1 and 7. Please try again.\n") continue else: #Check if in Range if (userInput < 0 or userInput > 7): print("I can only accept a number between 1 and 7. Please try again.\n") continue break #Output print(Week[userInput])
true
1eb61779347687b166f28a48fb2a69747482c8fe
LuckyLub/crashcourse
/test_cc_20190305.py
2,316
4.3125
4
'''11-1. City, Country: Write a function that accepts two parameters: a city name and a country name. The function should return a single string of the form City, Country , such as Santiago, Chile . Store the function in a module called city _functions.py. Create a file called test_cities.py that tests the function you just wrote (remember that you need to import unittest and the function you want to test). Write a method called test_city_country() to verify that calling your function with values such as 'santiago' and 'chile' results in the correct string. Run test_cities.py, and make sure test_city_country() passes. 11-2. Population: Modify your function so it requires a third parameter, population . It should now return a single string of the form City, Country – population xxx , such as Santiago, Chile – population 5000000 . Run test_cities.py again. Make sure test_city_country() fails this time. Modify the function so the population parameter is optional. Run test_cities.py again, and make sure test_city_country() passes again. Write a second test called test_city_country_population() that veri- fies you can call your function with the values 'santiago' , 'chile' , and 'population=5000000' . Run test_cities.py again, and make sure this new test passes. ''' import unittest import cc_20190305 class TestPlace(unittest.TestCase): def setUp(self): self.employee1 = cc_20190305.Employee("Mark", "Moerman", "100000") def test_if_2_strings_are_joined_together(self): self.assertEqual(cc_20190305.place("Santiago","Chile"),"Santiago, Chile") def test_if_population_can_be_added_to_description(self): self.assertEqual(cc_20190305.place("Santiago", "Chile", 5000000), "Santiago, Chile - population 5000000") def test_if_raise_method_adds_5000_to_annual_salary(self): expected_outcome = self.employee1.annual_salary + 5000 self.employee1.give_raise() self.assertEqual(self.employee1.annual_salary, expected_outcome) def test_if_raise_method_adds_user_defined_raise_to_annual_salary(self): user_defined_raise = 30000 expected_outcome = self.employee1.annual_salary + user_defined_raise self.employee1.give_raise(user_defined_raise) self.assertEqual(self.employee1.annual_salary, expected_outcome)
true
c4a6190da0cdbfc05b981df0e3db311bc1ca8ec7
yashsf08/project-iNeuron
/Assignment2-python/program-one.py
481
4.1875
4
""" 1. Create the below pattern using nested for loop in Python. * * * * * * * * * * * * * * * * * * * * * * * * * """ from math import ceil def draw_pattern(data): upper_limit = ceil(data/2) print(upper_limit) lower_limit = 0 for i in range(upper_limit): print('*'*(i+1)) for i in range(upper_limit-1,0,-1): print('*'*i) number = int(input("Dear User, provide number of lines for you wish to draw pattern: " )) draw_pattern(number)
true
251975745094bce828e72eb2571e38a470aae3a1
vladskakun/TAQCPY
/tests/TestQuestion12.py
595
4.125
4
""" 12. Concatenate Variable Number of Input Lists Create a function that concatenates n input lists, where n is variable. Examples concat([1, 2, 3], [4, 5], [6, 7]) ➞ [1, 2, 3, 4, 5, 6, 7] concat([1], [2], [3], [4], [5], [6], [7]) ➞ [1, 2, 3, 4, 5, 6, 7] concat([1, 2], [3, 4]) ➞ [1, 2, 3, 4] concat([4, 4, 4, 4, 4]) ➞ [4, 4, 4, 4, 4] Notes Lists should be concatenated in order of the arguments. """ def concat(*lists): summ = [] for list1 in lists: summ = summ + list1 return summ a=[1,3,5] b=[2,4,6] c=[0,-1] #print(concat(a,b,c))
true
604eb41c794380ba4cc3b4542518b7246889f582
vladskakun/TAQCPY
/tests/TestQuestion19.py
918
4.5
4
""" 19. Oddish vs. Evenish Create a function that determines whether a number is Oddish or Evenish. A number is Oddish if the sum of all of its digits is odd, and a number is Evenish if the sum of all of its digits is even. If a number is Oddish, return "Oddish". Otherwise, return "Evenish". For example, oddish_or_evenish(121) should return "Evenish", since 1 + 2 + 1 = 4. oddish_or_evenish(41) should return "Oddish", since 4 + 1 = 5. Examples oddish_or_evenish(43) ➞ "Oddish" oddish_or_evenish(373) ➞ "Oddish" oddish_or_evenish(4433) ➞ "Evenish" """ def oddish_or_evenish(num_num): numbers_of_num = [] for i in range(0, len(str(num_num))): numbers_of_num.append(num_num % 10) num_num=num_num // 10 summ = 0 for number in numbers_of_num: summ = summ + number if summ % 2 == 0: return 'Evenish' else: return 'Oddish'
true
c86585ae6baf8cd8772c752f335e161ce6382f38
vladskakun/TAQCPY
/tests/TestQuestion24.py
753
4.15625
4
""" 24. Buggy Uppercase Counting In the Code tab is a function which is meant to return how many uppercase letters there are in a list of various words. Fix the list comprehension so that the code functions normally! Examples count_uppercase(['SOLO', 'hello', 'Tea', 'wHat']) ➞ 6 count_uppercase(['little', 'lower', 'down']) ➞ 0 count_uppercase(['EDAbit', 'Educate', 'Coding']) ➞ 5 """ def count_uppercase(data_list): i = 0 rez = 0 while(i < len(data_list)): j = 0 while(j < len(data_list[i])): if data_list[i][j].isupper(): rez += 1 j += 1 i += 1 return rez print(count_uppercase(['EDAbit', 'Educate', 'Coding']))
true
bef9c39d7a11dbedc7633555a0b6c370384d737f
HakimZiani/Dijkstra-s-algorithm
/dijkstra.py
2,356
4.28125
4
#---------------------------------------------------------------------- # Implementation of the Dijkstra's Algorithm # This program requires no libraries like pandas, numpy... # and the graph DataStructure is a dictionary of dictionaries # # Created by [HakimZiani - zianianakim@gmail.com] #---------------------------------------------------------------------- # the key in the graph dic is the node and the value is its neighbors graph = {'A':{'B':1,'D':7}, 'B':{'A':1,'C':3,'E':1}, 'C':{'B':3,'D':2,'E':8}, 'D':{'A':7,'C':2,'E':1}, 'E':{'D':1,'E':8,'B':1}, } def printGraph(graph): for x , y in graph.items(): print(x + " in relation with : " + str(y)) printGraph(graph) # Initialize the Start and End node StartNode = input("Enter Start Node : ") EndNode = input("Enter End Node : ") # initList function for crating the queues of unvesited nodes # and data # The Structure is : {'node':[Distance,'prev-node']} def initList(graph,StartNode,EndNOde): d={} for x in graph.keys(): if x == StartNode: d[x] = [0,''] else: d[x] =[99999,''] return d # getMinimalValue function to return the label of the node that # has the minimal value def getMinimalValue(d): min = 999999 a = 'ERROR' # to see if the value don't change for x,y in d.items(): if y[0] < min: a = x min = y[0] return a d= initList(graph,StartNode,EndNode) unvisited = initList(graph,StartNode,EndNode) while(True): #get the node to work with focus = getMinimalValue(unvisited) # Break if it's the destination if focus == EndNode: break # Setting the Data queue for x,y in graph[focus].items(): if d[x][0] > d[focus][0]+y: d[x][0] = d[focus][0]+y d[x][1] = focus try: unvisited[x][0] = unvisited[focus][0]+y unvisited[x][1] = focus except: pass del unvisited[focus] road = [] node= EndNode # d now contains the final data queue we need # All we have to do is getting the right path from the EndNode # to the StartNode using the prev states stored in d while (node != StartNode): road.append(node) node = d[node][1] road.append(StartNode) # Showing the result print("The shortest road is : "+"-->".join(reversed(road)))
true
faa19462725653c83f971c0ca8717b085e16973d
eishk/Udacity-Data-Structures-and-Algorithms-Course
/P0/Task4.py
1,188
4.3125
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) calls_caller = set() calls_called = set() texts_texter = set() texts_texted = set() for text in texts: texts_texter.add(text[0]) texts_texted.add(text[1]) for call in calls: calls_caller.add(call[0]) calls_called.add(call[1]) list = [] for call in calls_caller: if (call not in calls_called and call not in texts_texted and call not in texts_texter): list.append(call) list.sort() print("These numbers could be telemarketers: ") for l in list: print(l) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """
true
8318d4a5b9e442193b267dd7e045f60adabfe243
ramendra-singh/Practice
/DataStructure/Strings/secondMostChar.py
1,400
4.1875
4
''' Program to find second most frequent character Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string. Examples: Input: str = "aabababa"; Output: Second most frequent character is 'b' Input: str = "geeksforgeeks"; Output: Second most frequent character is 'g' Input: str = "geeksquiz"; Output: Second most frequent character is 'g' The output can also be any other character with count 1 like 'z', 'i'. Input: str = "abcd"; Output: No Second most frequent character A simple solution is to start from the first character, count its occurrences, then second character and so on. While counting these occurrence keep track of max and second max. Time complexity of this solution is O(n2). We can solve this problem in O(n) time using a count array with size equal to 256 (Assuming characters are stored in ASCII format). ''' def secondMostChar(input): count = [0] * 256 for i in input: count[ord(i)] += 1 max = -1 first = 0 second = 0 for i in range(256): if count[i] > count[first]: second = first first = i elif count[i] > count[second] and count[i] != count[first]: second = i for i in input: if count[ord(i)] == count[second]: print i break input = "aabababa" secondMostChar(input)
true
be9b32579e460a7b44864ba89cd6161fbf03eff5
bmosc/Mindtree_TechFest_2015
/fractals/koch snow flake curve.py
879
4.125
4
#!/usr/bin/python from turtle import * def draw_fractal(length, angle, level, initial_state, target, replacement, target2, replacement2): state = initial_state for counter in range(level): state2 = '' for character in state: if character == target: state2 += replacement elif character == target2: state2 += replacement2 else: state2 += character state = state2 # draw for character in state: if character == 'F': forward(length) elif character == '+': right(angle) elif character == '-': left(angle) speed(0) delay(0) hideturtle() # Lindenmayer Notation # Koch Flake up(); goto(-180, 60); down(); setup(1.0, 1.0) draw_fractal(1, 60, 5, 'X++X++X', 'X', 'FX-FX++XF-XF', '', '') exitonclick()
true