blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
092b2594f9159f72119349177487a3c0ffe8ebde
kronecker08/Data-Structures-and-Algorithm----Udacity
/submit/Task4.py
1,306
4.15625
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) call_outgoing = [] call_incoming = [] for i in calls: call_outgoing.append(i[0]) call_incoming.append(i[1]) call_outgoing = set(call_outgoing) call_incoming = set(call_incoming) num_texts = [] for i in texts: num_texts.append(i[0]) num_texts.append(i[1]) num_texts = set(num_texts) telemarketers = [] for i in call_outgoing: if i in call_incoming: continue elif i in num_texts: continue else: telemarketers.append(i) telemarketers = sorted(telemarketers) print("These numbers could be telemarketers: ") for i in telemarketers: print(i) """ 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
d3760baba77aa112d2860cbeed1ef56f378347be
iamrobinhood12345/economic-models
/base-model.py
2,642
4.21875
4
# Basic Flow of Money Model import sys MODEL_NUMBER = 1 INPUT_STRING = """ MAIN MENU: Input amount to loan (integer). Input 'q' to quit program. """ EXIT_STRING = """ Thank you, goodbye! By Ben Shields <https://github.com/iamrobinhood12345> copyright 2017 """ def issue_money(val, money_circulating, debt_to_central_bank, contracts): """Issue money.""" money_circulating[0] += val print("Issuing " + str(val) + " units") if val != 0: debt_to_add = val + 1 debt_to_central_bank[0] += debt_to_add print("Adding " + str(debt_to_add) + " to total debt to central bank") contract = debt_to_add contracts.append(contract) print("Creating contract for " + str(contract) + " units") else: print("No contract created, no money issued.") def remove_debt(money_circulating, debt_to_central_bank, contracts): """Remove debt.""" for i in range(len(contracts)): if money_circulating[0] >= contracts[i]: print("Paying off debt of contract of " + str(contracts[i]) + " units") money_circulating[0] -= contracts[i] print("Removing " + str(contracts[i]) + " units from money circulating") debt_to_central_bank[0] -= contracts[i] print("Removing " + str(contracts[i]) + " units from debt to central bank") print("Removing contract of " + str(contracts[i]) + " units") del contracts[i] break def main(): """Handle menus and input.""" money_circulating = [0] debt_to_central_bank = [0] contracts = [] print(""" Economic Model """ + str(MODEL_NUMBER) + """ Turn based flow of money model. Constituents: Central Bank Other (Entities that do not issue money) """) while True: loan = input(INPUT_STRING) try: loan_val = int(loan) except ValueError: if loan == 'q': print(EXIT_STRING) sys.exit() print("WARNING: Loan input must be an integer!") continue issue_money(loan_val, money_circulating, debt_to_central_bank, contracts) remove_debt(money_circulating, debt_to_central_bank, contracts) print("Money circulating: " + str(money_circulating[0])) print("Total debt to central bank: " + str(debt_to_central_bank[0])) print("Contracts: " + str(contracts)) if __name__ == "__main__": """Entry point. Calls main function.""" main()
true
a868af86d0102fe2aafd0b10782840ecad86768e
KC1988Learning/TkinterLearning
/tutorial/grid.py
2,025
4.15625
4
import tkinter as tk from tkinter import ttk from window import set_dpi_awareness def greet(): # add strip() to remove whitespace in string print(f"Hello {user_name.get().strip() or 'World'}! How are you?") set_dpi_awareness() root = tk.Tk() root.title("Greeting App") # configure row and column property of the root window # weight = 0, column/row takes up size of the content # weight is relative, if one is 0 another is 1, 1 means taking up all space # if one is 2 another 1, means the first one occupies twice as much space root.columnconfigure(index=0, weight=1) user_name = tk.StringVar() user_age = tk.IntVar() # padding = (left, top, right, bottom) entry_frame = ttk.Frame(root, padding=(20,10, 20, 0)) # grid will place the element on the first available row in the first column # sticky = EW: makes the column 'sticks' to the edge of the root window entry_frame.grid(row=0, column=0, sticky='EW') # column 0 and 1 in entry_frame as wide as needed by the content entry_frame.columnconfigure(index=0, weight=0) entry_frame.columnconfigure(index=1, weight=0) user_label = ttk.Label(entry_frame, text="Name: ") # weight=0: takes as space as needed by the content user_label.grid(row=0, column=0, sticky='EW') user_entry = ttk.Entry(entry_frame, width=15, textvariable=user_name) user_entry.grid(row=0, column=1, sticky='EW') user_entry.focus() # padding = (horizontal, vertical) btn_frame = ttk.Frame(root, padding=(20, 10)) # sticky='EW' makes the row sticks to the root window btn_frame.grid(row=1, column=0, sticky='EW') # make the first column takes up one portion of the width of btn_frame btn_frame.columnconfigure(index=0, weight=1) greet_btn = ttk.Button(btn_frame, text="Greet", command=greet) # sticky = 'EW' makes the buttom stick to the boundary of the first column greet_btn.grid(row=0, column=0, sticky='EW') btn_frame.columnconfigure(index=1, weight=1) quit_btn = ttk.Button(btn_frame, text="Quit", command=root.destroy) quit_btn.grid(row=0, column=1, sticky='EW') root.mainloop()
true
24e335ecf0a79e60026e0a3f41f5277b7ab839ef
tikitae92/Python-IS340
/Ch4/whileCheckout2.py
1,011
4.15625
4
#example of sale transaction in a store #cashier doesnt know the # of items in a cart #input price #add to total and display in the while loop #starts sale transaction and ends it when no items are left #keep track of # of items in customer shopping cart #print total # of items #stop when user enter -1 #if negative (<-1) ask user to try again price=0 total=0 i=1 #one while loop #sentinel (in this example negative number will stop loop) while price !=-1: #display item number price=float(input("Enter price for item #%d (enter -1 to stop): " %i)) #one method of ending the loop #if price<0: # print("End of sale transaction") # break if price >=0: i=i+1 total=total+price print("Total is $%.2f" %total) elif price==-1: i=i-1 print("Number of items:", i) print("Total is $%.2f" %total) break else: print("Invalid entry, please try again")
true
fbf74dfb475b7f1d3ee5e7a247c6c40b3a615d0e
camarena2/camarena2.github.io
/secretworld.py
800
4.25
4
print(" Welcome to the Secret Word Game. Guess a letter in the word, then press enter:") from random import choice word = choice(["table", "chair", "bottle", "plate", "parade", "coding", "teacher", "markers", "phone", "grill", "friends", "fourth", "party"]) guessed = [] while True: out = "" for letter in word: if letter in guessed: out = out + letter else: out = out + "_" if out == word: print("Congrats! You guessed correctly:", word) break print("Guess a letter:", out) guess = input() if guess in guessed: print("You already guessed this letter! Try again!") elif guess in word: print("Yay! Good Job!") guessed.append(guess) else: print("Try Again!") print()
true
041dbf38767b723327ebf197bba3cf02bbf10a5b
raymccarthy/codedojo
/adam/firstWork/adam.py
461
4.21875
4
calculator = "Calculator:" print(calculator) one = input("Enter a number: ") two = input("Enter another number: ") three = input("Would you like to add another number?: ") if three == "yes" or three == "Yes": thre = input("What would you like that number to be: ") answer = float(one) + float(two) + float(thre) print("The answer to you sum is" , answer,) else: answer = float(one) + float(two) print("The answer to you sum is" , answer,)
true
a7ea7d24373085e6822da0ff924304b434ed8d52
pasanchamikara/ec-pythontraining-s02
/data_structures/tuples_training.py
507
4.46875
4
# Tuples are unchangeable once created, ordered and duplicates are allowed. vegetable_tuple = ("cucumber", "pumkin", "tomato") # convert his to a set and assign to vegetable_set # get the lenght of the tuple vegetable_tuple fruit_tuple = ("annas", ) # get the result of print(type(fruit_tuple)) with and without commas # print only the last 2 values of the vegetable tuple # negative indices # change tuple values using casting to lists add new values and remove old values , convert back to lists
true
6d2b06ebe279933bfaec64883289b897948d81ee
haider10shah/python-tricks
/functions.py
1,905
4.3125
4
def yell(text): return text.upper() + '!' def greet(func): greeting = func('How are you') return greeting def whisper(text): return text.lower() + '...' def speak(text): def whisper(t): return t.lower() + '...' return whisper(text) def get_speak_func(text, volume): def whisper(): return text.lower() def yell(): return text.upper() if volume > 0.5: return yell else: return whisper def make_adder(n): def add(x): return x + n return add if __name__ == '__main__': bark = yell print(yell('hello')) print(bark('woof')) del yell print(bark('hey')) print(bark.__name__) # a variable pointing to a function and the function itself are two separate concerns # you can store functions in data structures funcs = [bark, str.lower, str.capitalize] print(funcs) print(funcs[0]('HeyHo')) print(greet(bark)) print(greet(whisper)) # functions that can accept other functions as arguments are called high order functions # e.g. python function map l = list(map(bark, ['Hey', 'what', 'why'])) print(l) # python allows nested function # functions can not only accept behaviors through arguments but can also return behaviours through functions # internal functions can capture the arguments passed to parent function. # functions that can do this are called closure # a closure remembers the value from its outer scope even if the flow is no longer in that scope print(get_speak_func('Hello', 0.6)()) # make adder is factory to create and config adder functions plus_3 = make_adder(3) plus_5 = make_adder(5) print(plus_3(4)) # not all objects are callable # if they implement __call__ they can be called # callable function can be used to check if an object has a __call__ method
false
32d6e902356eeec9d4cfcab5bd4f1c8d4398dea3
JoshuaR830/HAI
/Lab 1/Excercise 4/ex9.py
272
4.28125
4
words = ["This", "is", "a", "word", "list"] print("Sorted: " + sorted(words)) print("Original: " + words) words.sort() print("Original: " + words) # sorted(words) prints does not change the order of the original list # words.sort() changes the original order of the list
true
0fdac6ba0c12be57e9d07c067ce5be5042971876
BurlaSaiTeja/Python-Codes
/Lists/Lists05.py
342
4.21875
4
""" Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included). """ def sqval(): l=list() for i in range(1,31): l.append(i**2) print(l[:5]) print(l[-5:]) sqval() """ Output: [1, 4, 9, 16, 25] [676, 729, 784, 841, 900] """
true
e9ffcaced1121fa20de7c5f4df840bc8821a3c58
anc1revv/coding_practice
/leetcode/easy/letter_capitalize.py
490
4.375
4
''' Using the Python language, have the function LetterCapitalize(str) take the str parameter being passed and capitalize the first letter of each word. Words will be separated by only one space. ''' def letter_capitalize(input_str): list_words = input_str.split(" ") for word in list_words: for i in range(len(word)): if i == 0: return ' '.join(list_words) def main(): input_str = "hello bye" print letter_capitalize(input_str) if __name__ == "__main__": main()
true
2b3c1bc9399793ce14fd920e8dfda39062655465
Swastik-Saha/Python-Programs
/Recognize&Return_Repeated_Numbers_In_An_Array.py
472
4.1875
4
def repeated(): arr = [] length = int(raw_input("Enter the length of the array: ")) for i in range(0,length): arr.append(int(raw_input("Enter the elements of an array: "))) arr.sort() count = 0 for i in range(0,length): print "The number taken into consideration: " + str(i) print "The number of occurences of the number above: " + str(arr.count(i))
true
971881bad3c2980c5c2875ff07d1ac50d2a45299
wojtekminda/Python3_Trainings
/SMG_homework/10_2_Asking_for_an_integer_number.py
2,299
4.53125
5
''' Write input_int() function which asks the user to provide an integer number and returns it (as a number, not as a string). It accepts up to 3 arguments: 1. An optional prompt (like input() built-in function). 2. An optional minimum acceptable number (there is no minimum by default). 3. An optional maximum acceptable number (there is no maximum by default). The function keeps asking the user until she provides a well-formed integer number within range. Example usage of the function: a = input_int("Enter an integer: ") b = input_int("Enter a positive integer: ", 1) c = input_int("Enter an integer not greater than 8: ", largest=8) d = input_int("Enter an integer (4..8): ", 4, 8) print("Provide another integer (4..8):") e = input_int(smallest=4, largest=8) print("Your numbers multiplied by 2:", a * 2, b * 2, c * 2, d * 2, e * 2) Example session with the script: Enter an integer: cake Enter an integer: 3.4 Enter an integer: -5 Enter a positive integer: -10 Enter a positive integer: 0 Enter a positive integer: 1000 Enter an integer not greater than 8: 1000 Enter an integer not greater than 8: 7 Enter an integer (4..8): 1 Enter an integer (4..8): 4 Provide another integer (4..8): 9 8 Your numbers multiplied by 2: -10 2000 14 8 16 ''' def input_int(prompt='', smallest=None, largest=None): number = input(prompt) while number: try: number = int(number) if smallest == None and largest == None: return number elif largest == None: if not number < smallest: return number elif smallest == None: if not number > largest: return number else: if not (number < smallest or number > largest): return number except ValueError as exc: print(exc) number = input(prompt) a = input_int("Enter an integer: ") print(a) b = input_int("Enter a positive integer: ", 1) print(b) c = input_int("Enter an integer not greater than 8: ", largest=8) print(c) d = input_int("Enter an integer (4..8): ", 4, 8) print(d) print("Provide another integer (4..8):") e = input_int(smallest=4, largest=8) print("Your numbers multiplied by 2:", a * 2, b * 2, c * 2, d * 2, e * 2)
true
09c024e3dfde0a07e652fd8bfb02357b736bc1ac
wojtekminda/Python3_Trainings
/SMG_homework/01_3_Should_I_go_out.py
1,319
4.15625
4
''' A user is trying to decide whether to go out tonight. Write a script which asks her a few yes-no questions and decides for her according to the following scheme: [NO SCHEME] ''' raining = input("Is it raining? ") if raining == "yes": netflix = input("Is the new episode on Netflix out already? ") if netflix == "yes": print("Stay home") elif netflix == "no": umbrella = input("Damn it. Do you have an umbrella? ") if umbrella == "yes": drinking = input("Do you feel like drinking tonight? ") if drinking == "yes": print("Go, then!") elif drinking == "no": sure = input("Yeah, right. You sure? ") if sure == "yes": print("What a drag! Stay home.") elif sure == "no": print("You gotta go out.") elif umbrella == "no": sugar = input("Are you made of sugar? ") if sugar == "yes": print("Being moody? Go to sleep, honey") elif sugar == "no": print("Dress up and leave") elif raining == "no": reason = input("Do you need another reason? ") if reason == "yes": print("World sucks. Go out!") elif reason == "no": print("Are you still here?")
true
2b11221a58ddff3101a95aa892b0ed5ab4997f80
5h3rr1ll/LearnPythonTheHardWay
/ex15.py
1,076
4.375
4
#importing the method argv (argument variable) from the library sys into my code from sys import argv """now I defining which two arguments I want to have set while typing the filename. So you are forced to type: python ex15.py ArgumentVariable1 ArgumentVariable2""" script, filename = argv #since the filename is given at the comandline, open just opens the named file #and pass it to the variable txt txt = open(filename) #Just writes a line of text print "Here's your file %r:" % filename #looks like you can't just print the content from the file, you also need to #.read() to print it out print txt.read() #just writes a line of text print "Type the filename again:" #getting a input from the user and saves it into the variable "file_again" file_again = raw_input("> ") #open the file with the givin name and saves it's content into the variable #text_again txt_again = open(file_again) #prints out the content which was givin to the variable "txt_again". Spent #attation to the .read()!Won't work without it! print txt_again.read() txt.close() txt_again.close()
true
a4877ed3f2bb5586e5143b85119eeb1f75efeb6c
kmjawadurrahman/python-interactive-mini-games
/guess_the_game.py
2,176
4.40625
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random which_range = "" # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global guess_count global which_range global secret_number guess_count = 7 which_range = 0 secret_number = random.randrange(0,100) print "New game. Range is from 0 to 100" print "Number of guesses remaining is", guess_count print "" # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game global guess_count global which_range global secret_number guess_count = 9 which_range = 1 secret_number = random.randrange(0,1000) print "New game. Range is from 0 to 1000" print "Number of guesses remaining is", guess_count print "" def input_guess(guess): # main game logic goes here global guess_count guess_count -= 1 guess_ = int(guess) print "Guess was", guess_ print "Number of guesses remaining is", guess_count if guess_ < secret_number: print "Higher" print "" elif guess_ > secret_number: print "Lower" print "" else: print "Correct" print "" if which_range: range1000() else: range100() if guess_count <= 0: print "You ran out of guesses. The number was", secret_number print "" if which_range: range1000() else: range100() # create frame f = simplegui.create_frame("Guess the number", 200, 200) # register event handlers for control elements and start frame f.add_button("Range is [0, 100)", range100, 200) f.add_button("Range is [0, 1000)", range1000, 200) f.add_input("Enter a guess", input_guess, 200) # call new_game new_game() # always remember to check your completed program against the grading rubric
true
336752945fd20ad86c8fef8d7fe7c319675385bd
prakrutivaghasiya/Python-programs
/Fibo.py
266
4.125
4
def Fibonacci(n) : if n<0 : print('Incorrect Input') elif n == 1 : return 0 elif n==2 : return 1 else : return Fibonacci(n-1) + Fibonacci(n-2) print('Enter number : ') number = int(input()) print (Fibonacci(number))
false
7c0d5b6e2a34573515eeefa8451ec93e94aecded
RaviKiranDev/Python-Exercises
/LogicAndLoopsExercise/LogicAndLoopsExercise/ifelse2.py
233
4.4375
4
x=int(input("Enter a number")) if x%2==0: if x%3==0: print("even and divisible by 3") else: print("even") else: if x%3==0: print("odd and divisible by 3") else: print("odd")
false
f95c90cefc62f8a1531c8a0d32ddc4e91a3dbc86
Otumian-empire/python-oop-blaikie
/05. Advanced Features/0505.py
604
4.15625
4
# With context # open file and close it fp = open('Hello.txt', '+a') print('I am a new text file', file=fp) fp.close() # We don't have to close it with open('Hello.txt', '+a') as op: print('I am a new line in the Hello.txt file', file=op) # seems like not a valid python3 code # class MyWithClass: # def __enter__(self): # print("Entered the class") # def __exit__(self, type, value, traceback): # print("Exit the class") # def say_hello(self): # print('Hello') # with MyWithClass as cc: # c = cc() # c.say_hello() # print("After the with block")
true
566946645bd44e94bafe916c9e2f0aeadd4b1cb5
mjayfinley/Conditions_and_Functions
/EvenOdd/EvenOdd.py
220
4.3125
4
numberInput = int(input("Please enter a number: ")) if numberInput == 0: print("This number is neither odd or even.") elif numberInput %2 == 0: print("This number is even") else: print("This number is odd")
true
a73f1008e48dfa6d13e7481ebb4f795e272fa773
artliou/ucb
/cs61a/lab/lab01/lab01_extra.py
738
4.21875
4
"""Coding practice for Lab 1.""" # While Loops def factors(n): """Prints out all of the numbers that divide `n` evenly. >>> factors(20) 20 10 5 4 2 1 """ "*** YOUR CODE HERE ***" a = n while a > 0: if n % a == 0: print(a) a = a - 1 def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 """ "*** YOUR CODE HERE ***" count = 0 if k == 0: return 1 if k == 1: return n while count <= k: total = n*(n-1) count = count + 1 return total
false
4bf95784f9344a328e8032c2a9339693cb4c6ee6
Coliverfelt/Aulas_Python
/Aula007.py
810
4.15625
4
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro: ')) soma = n1 + n2 subtracao = n1 - n2 multiplicacao = n1 * n2 divisao = n1 / n2 divisaointeira = n1//n2 exponenciacao = n1**n2 resto = n1 % n2 print('A soma entre os valores {} e {} vale {}'.format(n1, n2, soma), end='. ') print('A subtração entre os valores {} e {} vale {}'.format(n1, n2, subtracao)) print('A multiplacação entre os valores {} e {} vale {}'.format(n1, n2, multiplicacao)) print('A divisão entre os valores {} e {} vale {:.3f}'.format(n1, n2, divisao)) print('A divisão inteira entre os valores {} e {} vale {}'.format(n1, n2, divisaointeira)) print('A exponeciação entre os valores {} e {} vale {}'.format(n1, n2, exponenciacao)) print('O resto da divisão entre os valores {} e {} vale {}'.format(n1, n2, resto))
false
ee6e08c183fe4ee4624cc5e68044b9b19f506c07
ShanYouGuan/python
/others/Test_Class.py
1,003
4.21875
4
class people: name = "" age = 0 __weigt = 0 def __init__(self,a, n, w): self.name = n self.age = a self.__weight = w def speak1(self): print("{}说:我今年{}岁,我{}斤".format(self.name, self.age,self.__weight)) class student(people): grade = '' def __init__(self,n, a, w, g): people.__init__(self,a, n, w) self.grade = g def speak2(self): print("{}说:我{}岁了,我在读{}年级。".format(self.name, self.age, self.grade)) class speaker: topic = '' name = '' def __init__(self,n, t): self.name = n self.topic = t def speak3(self): print("我叫{},我是演说家,我演讲的题目是{}".format(self.name, self.topic)) class sampe(student, speaker,people): def __init__(self,n, a, w, g, t): student.__init__(self,n, a, w, g) speaker.__init__(self,n, t) pass tmp = sampe('tim',10,100,8, "Lovely") tmp.speak1() tmp.speak2() tmp.speak3()
false
695355269bae1334c7370ee5b99c7d67aa1fc42b
ShanYouGuan/python
/Algorithm/bubble_sort.py
286
4.125
4
def bubble_sort(list): for i in range(0, len(list)): for j in range(len(list)-i-1): if list[j] > list[j+1]: list[j], list[j+1] = list[j+1], list[j] lista = [1, 3, 6, 5, 4, 2] bubble_sort(lista) for i in range(0, len(lista)): print(lista[i])
false
08a27190e2210d7bedda769c93c6a9d710cb474e
BarDalal/Matrices--addition-and-multiplication
/AddMinPart.py
1,148
4.125
4
# -*- coding: utf-8 -*- """ Name: Bar Dalal Class: Ya4 The program adds the common parts of two matrices. The sum's size is as the common part's size. """ import numpy as np def MinAddition(a, b): """ The function gets two matrices. The function returns the sum of the common parts of the matrices (minimum size). """ if (a.shape[0] >= b.shape[0]): x= b.shape[0] else: x= a.shape[0] # x is the minimum number of rows from the two matrices if (a.shape[1] >= b.shape[1]): y= b.shape[1] else: y= a.shape[1] # y is the minimum number of columns from the two matrices c= np.zeros([x,y], dtype = int) # the sum of the common parts of the matrices for row in range(x): for column in range (y): c[row, column]= a[row, column] + b[row, column] return c def main(): arr = np.array([[1, 2, 3, 7], [4, 5, 6, 90], [7, 8, 9, 6]]) arr2= np.array([[10, 20, 50],[30, 40, 20], [1, 2, 3], [6, 8, 0]]) result= MinAddition(arr, arr2) print (result) if __name__ == "__main__": main()
true
afa5e2e385ff2086f25c471ac148c7032980d250
nighatm/W19A
/app.py
1,004
4.1875
4
import addition import subtraction import multiplication import divide print("Please choose an operation") print("1: Addition") print("2: Subtraction") print("3: Multiplication") print("4: Division") try: userChoice = int(input ("Enter Choice 1 or 2 or 3 or 4 : ")) except: print ('You have entered an invalid option.') else: if userChoice in ('1', '2', '3', '4' ): number1 = int(input("Enter first number: ")) number2 = int(input ("Enter second number: ")) if (userChoice == '1'): print( "Result is: " str(addition.add(number1, number2))) elif (userChoice == '2'): print("Result is: " str(subtraction.subtract(number1, number2))) elif (userChoice == '3'): print ("Result is: " str(multiplication.multiply(number1, number2))) elif (userChoice == '4'): print("Result is: " str(divide.division(number1,number2))) else: print("Invalid user input")
true
51cc0c2b610846a0f4fcc8b0e4e2eb57d15d683a
DikranHachikyan/python-20201012
/ex58.py
1,068
4.25
4
# клас class Point(): #Променлива на класа (статична променлива) label = 'A' # Конструктор на класа - инициализация на данните на класа def __init__(self, x = 0, y = 0, *args, **kwargs): print('object constructor') # данни на класа self._x = x self._y = y # Метод на класа def draw(self): print(f'draw point at:({self._x}, {self._y})') def move_to(self, dx, dy): self._x += dx self._y += dy if __name__ == '__main__': # p1 - обект, представител на класа p1 = Point() p2 = Point(12,45) p1.z = 200 print(f'p1.z = {p1.z}') # AttributeError - p1.z е динамично закачен за обекта # print(f'p2.z = {p2.z}') print(f'Point Label:{Point.label}, p1.label:{p1.label}, p2.label:{p2.label}') Point.label = 'Start' print(f'Point Label:{Point.label}, p1.label:{p1.label}, p2.label:{p2.label}')
false
cfd8276cedbf35d4542948135e6c68c986d00c89
Coadiey/Python-Projects
/Python programs/PA7.py
2,214
4.15625
4
# Author: Coadiey Bryan # CLID: C00039405 # Course/Section: CMPS 150 – Section 003 # Assignment: PA7 # Date Assigned: Friday, November 17, 2017 # Date/Time Due: Wednesday, November 22, 2017 –- 11:55 pm #Description: This program is just a simple class setup that changes the output into a string based on the input using dictionaries # # Certification of Authenticity: # I certify that this assignment is entirely my own work. import random class Card(): def __init__(self,suit,rank): self.__rank = rank self.__suit = suit def getModSuit(self): suit = self.__suit dictionary = {0:"Hearts",1:"Spades",2:"Diamonds",3:"Clubs"} if suit in dictionary: return dictionary[suit] else: return "ERROR" def getModRank(self): rank = self.__rank dictionary = {1:"Ace",2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'10',11:'Jack',12:'Queen',13:'King'} if rank in dictionary: return dictionary[rank] else: return "ERROR" def getSuit(self): return self.__suit def getRank(self): return self.__rank def setSuit(self,suit): self.__suit = suit def setRank(self,rank): self.__rank = rank def main(): card1 = Card(2,12) # this will create a card that is a Queen of Diamonds rank = str(card1.getModRank()) suit = str(card1.getModSuit()) print("Card #1: %s of %s" % (rank,suit)) suitgiver = random.randint(0,3) # these 3 lines will create a “random” card from the deck rankgiver = random.randint(1,13) card2 = Card(suitgiver,rankgiver) rank2 = card2.getModRank() suit2 = card2.getModSuit() print("Card #2: %s of %s" % (rank2, suit2)) suitgiver2 = random.randint(0,3) # these 3 lines will create a “random” card from the deck rankgiver2 = random.randint(1,13) card3 = Card(suitgiver2,rankgiver2) rank3 = card3.getModRank() suit3 = card3.getModSuit() print("Card #2: %s of %s" % (rank3, suit3)) if __name__ =='__main__': main()
true
7713164280f6733d072ad02e09bc19aa450e361c
SP18-Introduction-Computer-Science/map-and-lists-biren3008
/Assignment2.py
546
4.375
4
# List and Map Biren 3008 # Create a List number = [] number.append([1,2,3,'List','Map']) n = number[0] print("List : ") print(n) print("List Elements are") for listElem in n : print(listElem) # Create a Map myMap = {0 : "List", 1 : "Map", 2 : "Biren_3008"} print("Map Dictionary with Value : ") print(myMap) print("Keys in the Map : ") for dictVar in myMap : print(dictVar) print("Values in Map : ") for dictVar in myMap : print(myMap[dictVar]) print("key" + str(dictVar)+ "value"+ str(myMap))
false
96672006f4ee0b8ce9cb023f0f14c9a5eb385b71
EmreTekinalp/PythonLibrary
/src/design_pattern/factory_pattern.py
1,791
4.1875
4
""" @author: Emre Tekinalp @contact: e.tekinalp@icloud.com @since: May 28th 2016 @brief: Example of the factory pattern. Unit tests to be found under: test/unit/test_factory_pattern.py """ from abc import abstractmethod class Connection(object): """Connection class.""" @abstractmethod def description(self): """description function which needs to be overriden by the subclass.""" pass # end def description # end class Connection class OracleConnection(Connection): """OracleConnection class.""" def description(self): """description function.""" return 'Oracle' # end def description # end class OracleConnection class SqlServerConnection(Connection): """SqlServerConnection class.""" def description(self): """description function.""" return 'SQL Server' # end def description # end class SqlServerConnection class MySqlConnection(Connection): """MySqlConnection class.""" def description(self): """description function.""" return "MySQL" # end def description # end class MySqlConnection class Factory(object): """Factory base class.""" def __init__(self, object_type): """Initialize Computer class.""" self._object_type = object_type # end def __init__ def create_connection(self): """create connection function.""" if self._object_type == 'Oracle': return OracleConnection() elif self._object_type == 'SQL Server': return SqlServerConnection() elif self._object_type == 'MySQL': return MySqlConnection() else: return Connection() # end if return connection objects # end def create_connection # end class Computer
true
368b33debeaf5fbfec24a6504b4eba9531403030
Bongio03/TPSIT
/Code/Code1.py
1,184
4.3125
4
''' Implementare i metodi enqueue() e dequeue()  e creare un programma che permetta all’utente di riempire una coda di numeri interi di lunghezza arbitraria. Successivamente testare la funzione dequeue per svuotare la coda. ''' def dequeue(queue): #Funzione per svuotare la coda return queue.pop(0) def enqueue(queue, element): #Funzione per caricare la coda queue.append(element) def main(): coda=[] #In python la coda è semplicemente una lista num=int(input("Inserire un numero: ")) #Input del primo elemento. In seguito, in base alle scelte dell'utente, verrano aggiunti altri elementi o meno enqueue(coda,num) #Viene inserito l'elemento nella coda while input("Vuoi continuare (Inserire n per terminare l'input): ")!='n': num=int(input("Inserire un numero: ")) enqueue(coda,num) for _ in range(len(coda)): #Ciclo for utilizzato per stamapre tutti gli eleemnti che vengono tolti dalla lista coda print(dequeue(coda)) if __name__ =="__main__": main()
false
f9ff6527ee3c680cefc70bb37a49ba2465005b51
kirushpeter/flask-udemy-tut
/python-level1/pypy.py
2,426
4.25
4
""" #numbers print("hello world") print(1/2) print(2**7) my_dogs = 2 a = 10 print(a) a = a + a print(a) puppies = 6 weight = 2 total = puppies * weight print(total) #strings print(len("hello")) #indexing mystring = "abcdefghij" print(mystring[-1]) print(mystring[0:7:2])#start is included start stop and step print(mystring[::3]) """ """ mystring = "hello world" print(mystring.split()) """ """ username = "sammy" color = "blue" print("the {} favourite is {}".format(username,color)) print(f"The {username} chose {color}" ) #lists #they ordered sequences that can hold a number of objects myList = [1,2,3] print(len(myList)) mylist = ['w','e','f','g'] mylist.append('k') print(mylist) #dictionaries d = {'key1':'value1','key2':'value2'} print(d) print(d['key1']) salaries = {'john':20,'sally':30,'sammy':15} print(salaries['sally']) #tuples - immutable (1,2,3) t = (1,2,3) print(t[0]) #sets -unordered collections of unique elements x = set() print(x) x.add(1) x.add(8) print(x) s = "flask" print(s[0]) print(s[2:]) print(s[1:4]) print(s[-1]) print(s[::-1]) l = [3,7,[1,4,'hello']] l[2][2] = "goodbye" print(l) mylistt = [1,1,1,1,1,2,2,2,2,3,3,3,3] print(set(mylistt)) age = 4 name = "sammy" print(f"hello my dog's name is {name} and he is {age} years old") """ """ #logical comparisons username = "admin" check = "admin" if username == check and 1==1: print(access granted) else: print("all above conditions were not true") """ """ username = "dhdjjd" permission = False if username == "admin" and permission: print("full access granted") elif username == "admin" and permission == False: print("admin access only,no full permission") else: print("no access") """ #loops """ my_iterable = [1,2,3,3,4,5,6] for items in my_iterable: print(items ** 3) """ """ salaries = {"john": 50,"kamau":60,"peter": 80} for employee in salaries: print(employee) print("has salary of: ") print(salaries[employee]) print(' ') """ """ mypairs = [('a',1),('b',3),('c',4)] for (item1,item2) in mypairs: print(item1) print(item2) """ i = 1 while i < 5: print(f"i is currently : {i}") i = i + 1 for x in range (0,11,2): print(x) #functions def report_person(name): print("reporting person " + name) report_person("cindy") def add_num(num1,num2): return num1 + num2 result = add_num(2,4) print(result)
true
45510428c4984ac3ff42c204393bce6e7372ea90
farahnazihah/DDP1-2019
/Lab1/challenge1.py
800
4.15625
4
import turtle turtle.speed(20) #drawing a circle turtle.color('yellow') turtle.begin_fill() turtle.circle(100) turtle.end_fill() turtle.penup() turtle.forward(40) turtle.left(90) turtle.forward(120) turtle.right(90) #drawing two eyes turtle.color('black') turtle.begin_fill() turtle.circle(10) turtle.end_fill() turtle.left(180) turtle.forward(80) turtle.left(180) turtle.color('black') turtle.begin_fill() turtle.circle(10) turtle.end_fill() #moving the pen turtle.right(90) turtle.forward(50) turtle.left(90) turtle.forward(18) turtle.right(90) #drawing a smile #source: 'How to Draw a Semicircle', stackoverflow.com turtle.pensize(2) turtle.pencolor('black') turtle.pendown() for x in range(90): turtle.forward(0.8) turtle.left(2)
false
eeb0f0366684a36245718065c8858f43f70736f7
danielstaal/project
/code/chips_exe.py
2,117
4.15625
4
''' Executable file Chips & Circuits Date: 26/05/2016 Daniel Staal This program allows the user to choose a print, netlist, search methods and a filename to output the result To execute this program: python chips_exe.py ''' import astar3D import netlists import time import sys if __name__ == "__main__": print "" print "Welcome to Chips & Circuits! Please give the starting variables:" print "" measures = [] netlist = None # choose print printNo = int(raw_input("print(1 or 2): ")) if printNo == 1: # dimentions of the grid # print #1 measures.append(18) measures.append(13) measures.append(7) elif printNo == 2: # print #2 measures.append(18) measures.append(17) measures.append(7) else: measures.append(6) measures.append(6) measures.append(6) # choose netlist netlistNo = int(raw_input("netlist(1, 2 or 3): ")) if netlistNo == 1: netlists = netlists.getNetlist1() elif netlistNo == 2: netlists = netlists.getNetlist2() elif netlistNo == 3: netlists = netlists.getNetlist3() else: netlists = netlists.getNetlistTest() netlist = netlists[0] gates = netlists[1] # choose iterations iterations = int(raw_input("number of iterations: ")) # choose deletion method randomOrNeighbour = "n" #raw_input("random or neighbour deletion(r or n): ") # hill climber or not reMaking = "y"#raw_input("Remaking(y or n): ") # if reMaking == "y": # reMaking = True # else: # reMaking = False # sort from shortest to longest before connecting? shortFirst = "y"# raw_input("Shortfirst(y or n): ") # if shortFirst == "y": # shortFirst = True # else: # shortFirst = False # provide a .csv file name fileName = raw_input("csv file name: ") # execute the algorithm with the given parameters astar3D.executeAlgorithm(measures, netlist, gates, iterations, fileName, randomOrNeighbour, reMaking, shortFirst)
true
1f32a7062a40bc6e14c6c0f7ba17d065746feb7c
josh-perry/ProjectEuler
/problem 1.py
439
4.21875
4
# Problem 1: Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. def euler_1(): total = 0 for i in range(1, 1000): if i % 3 == 0 or i % 5 == 0: total += i print("The answer should be: " + str(total)) if __name__ == "__main__": euler_1()
true
5f046618b7c307efab1b8c6ccbafe06a4afc4e93
khoipn1504/Practices
/Data Structures/Sorting and Selection/MergeSort.py
678
4.125
4
def merge(S1, S2, S): # merge 2 sorted lists S1 and S2 into properly list S i = j = 0 while i+j < len(S): if j == len(S2) or (i < len(S1) and S1[i] < S2[j]): S[i+j] = S1[i] # copy ith element of S1 as next item of S i += 1 else: S[i+j] = S2[j] # copy jth element of S1 as next item of S j += 1 def mergeSort(S): n = len(S) if n < 2: return # divide mid = n//2 S1 = S[:mid] S2 = S[mid:] # conquer (with recursion) mergeSort(S1) mergeSort(S2) # merge results merge(S1, S2, S) a=[2,34,43,3,345,52,6,2,34,3] mergeSort(a) print(a)
false
a185c1f5b1101ae320e5781d1a73548e270a6f57
Zahidsqldba07/code-signal-solutions-GCA
/GCA/2mostFrequentDigits.py
1,053
4.125
4
def mostFrequentDigits(a): #Tests # a: [25, 2, 3, 57, 38, 41] ==> [2, 3, 5] # a: [90, 81, 22, 36, 41, 57, 58, 97, 40, 36] ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # a: [28, 12, 48, 23, 76, 64, 65, 50, 54, 98] ==> [2, 4, 5, 6, 8] """ Given an array of integers a, your task is to calculate the digits that occur the most number of times in the array. Return the array of these digits in ascending order. Example For a = [25, 2, 3, 57, 38, 41], the output should be mostFrequentDigits(a) = [2, 3, 5]. Here are the number of times each digit appears in the array: 0 -> 0 1 -> 1 2 -> 2 3 -> 2 4 -> 1 5 -> 2 6 -> 0 7 -> 1 8 -> 1 The most number of times any number occurs in the array is 2, and the digits which appear 2 times are 2, 3 and 5. So the answer is [2, 3, 5]. Input/Output [execution time limit] 4 seconds (py3) [input] array.integer a An array of positive integers. Guaranteed constraints: 1 ≤ a.length ≤ 103, 1 ≤ a[i] < 100. [output] array.integer The array of most frequently occurring digits, sorted in ascending order. """
true
da574aa59126be1b3964190559c478a296f5b4a9
Zahidsqldba07/code-signal-solutions-GCA
/arcade/intro/026-evenDigitsOnly.py
515
4.1875
4
def evenDigitsOnly(n): n = [int(i) for i in str(n)] for d in n: if d%2 != 0: return False return True """ Check if all digits of the given integer are even. Example For n = 248622, the output should be evenDigitsOnly(n) = true; For n = 642386, the output should be evenDigitsOnly(n) = false. Input/Output [execution time limit] 4 seconds (py3) [input] integer n Guaranteed constraints: 1 ≤ n ≤ 109. [output] boolean true if all digits of n are even, false otherwise. """
true
8d9c2d0492cfb620649087e4e007031357eee827
Zahidsqldba07/code-signal-solutions-GCA
/GCA/2countWaysToSplit.py
1,719
4.1875
4
def countWaysToSplit(s): listS= list(s) # print (listS) lenS = len(listS) count = 0 for i in range(1,lenS): for j in range(i+1, lenS): ab = s[0:j] bc = s[i:lenS] ca = s[j:lenS] + s[0:i] # print("AB is :",ab,"BC is:",bc,"CA is:",ca) if ab != bc and bc != ca and ca != ab : count += 1 # print(count) return count """ You are given a string s. Your task is to count the number of ways of splitting s into three non-empty parts a, b and c (s = a + b + c) in such a way that a + b, b + c and c + a are all different strings. NOTE: + refers to string concatenation. Example For s = "xzxzx", the output should be countWaysToSplit(s) = 5. Consider all the ways to split s into three non-empty parts: If a = "x", b = "z" and c = "xzx", then all a + b = "xz", b + c = "zxzx" and c + a = xzxx are different. If a = "x", b = "zx" and c = "zx", then all a + b = "xzx", b + c = "zxzx" and c + a = zxx are different. If a = "x", b = "zxz" and c = "x", then all a + b = "xzxz", b + c = "zxzx" and c + a = xx are different. If a = "xz", b = "x" and c = "zx", then a + b = b + c = "xzx". Hence, this split is not counted. If a = "xz", b = "xz" and c = "x", then all a + b = "xzxz", b + c = "xzx" and c + a = xxz are different. If a = "xzx", b = "z" and c = "x", then all a + b = "xzxz", b + c = "zx" and c + a = xxzx are different. Since there are five valid ways to split s, the answer is 5. Input/Output [execution time limit] 4 seconds (py3) [input] string s A string to split. Guaranteed constraints: 3 ≤ s.length ≤ 100. [output] integer The number of ways to split the given string. """
true
b5224f264e6e51d57eacf32a54564688eed5c143
Zahidsqldba07/code-signal-solutions-GCA
/arcade/intro/09-allLongestStrings.py
1,206
4.125
4
""" Given an array of strings, return another array containing all of its longest strings. Example For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be allLongestStrings(inputArray) = ["aba", "vcd", "aba"]. Input/Output [execution time limit] 4 seconds (py3) [input] array.string inputArray A non-empty array. Guaranteed constraints: 1 ≤ inputArray.length ≤ 10, 1 ≤ inputArray[i].length ≤ 10. [output] array.string Array of the longest strings, stored in the same order as in the inputArray. """ """ Understand: given an array of strings, return new array with values of the longest strings Plan: create empty list create longest variable set to 1 loop through finding length of each string if string length > longest longest = string length loop through again append strings with length value longest to new array """ def allLongestStrings(inputArray): new = [] longest = 0 for i in range(len(inputArray)): if len(inputArray[i]) > longest: longest = len(inputArray[i]) for j in range(len(inputArray)): if len(inputArray[j]) == longest: new.append(inputArray[j]) return new
true
ac6519b87bdd7461be54798c7a74088110759986
kampetyson/python-for-everybody
/8-Chapter/Exercise6.py
829
4.3125
4
''' Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes. Enter a number: 6 Enter a number: 2 Enter a number: 9 Enter a number: 3 Enter a number: 5 Enter a number: done Maximum: 9.0 Minimum: 2.0 ''' numbers = None number_list = list() while True: numbers = input('Enter number: ') if(numbers == 'done'): break try: float(numbers) except: print('Bad Input') quit() number_list.append(numbers) print('Minimum:',min(number_list)) print('Maximum:',max(number_list))
true
b3bc71dff70c5bf4e21e0bc4e2af3f826c41406d
kampetyson/python-for-everybody
/2-Chapter/Exercise3.py
212
4.15625
4
# Write a program to prompt the user for hours and rate perhour to compute gross pay. hours = int(input('Enter Hours: ')) rate = float(input('Enter Rate: ')) gross_pay = hours * rate print('Pay:',gross_pay)
true
789ffe90d787d656159bbefc7dfeafb7bd02a287
kampetyson/python-for-everybody
/7-Chapter/Exercise2.py
1,108
4.15625
4
# Write a program to prompt for a file name, and then read # through the file and look for lines of the form: X-DSPAM-Confidence: 0.8475 # When you encounter a line that starts with “X-DSPAM-Confidence:” # pull apart the line to extract the floating-point number on the line. # Count these lines and then compute the total of the spam confidence # values from these lines. When you reach the end of the file, print out # the average spam confidence. # Enter the file name: mbox.txt # Average spam confidence: 0.894128046745 # Enter the file name: mbox-short.txt # Average spam confidence: 0.750718518519 try: fname = input('Enter a file name: ') fhandle = open(fname) except: print('File not found') exit() total = 0 average = 0 count = 0 for line in fhandle: line = line.strip() if line.startswith('X-DSPAM-Confidence:'): colon_pos = line.find(':') extracted_num = float(line[colon_pos+1:]) total += extracted_num count += 1 average = total/count print('Average spam confidence:',round(average,4))
true
9b3edb65b838b153430aa177b1609260908e98b4
kampetyson/python-for-everybody
/7-Chapter/Exercise1.py
614
4.40625
4
# Write a program to read through a file and print the contents # of the file (line by line) all in upper case. Executing the program will # look as follows: # python shout.py # Enter a file name: mbox-short.txt # FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008 # RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPROJECT.ORG> # RECEIVED: FROM MURDER (MAIL.UMICH.EDU [141.211.14.90]) # BY FRANKENSTEIN.MAIL.UMICH.EDU (CYRUS V2.3.8) WITH LMTPA; # SAT, 05 JAN 2008 09:14:16 -0500 try: fname = input('Enter a file name: ') fhandle = open(fname) except: print('File not found') exit() for line in fhandle: print(line.upper())
true
21045c28a2f3a5e004a2b42b3d6f7d04aa122e8a
usmansabir98/AI-Semester-101
/PCC Chapter 5/5-5.py
779
4.125
4
# 5-5. Alien Colors #3: Turn your if-else chain from Exercise 5-4 into an if-elifelse # chain. # • If the alien is green, print a message that the player earned 5 points. # • If the alien is yellow, print a message that the player earned 10 points. # • If the alien is red, print a message that the player earned 15 points. # • Write three versions of this program, making sure each message is printed # for the appropriate color alien. def test_color(color): if color=='green': print("You earned 5 points") elif color=='yellow': print("You earned 10 points") else: print("You earned 15 points") alien_color= 'green' test_color(alien_color) alien_color = 'yellow' test_color(alien_color) alien_color = 'red' test_color(alien_color)
true
8f6f7f0c6308b83fa51fbdf2f2e00717f736b63e
CISVVC/test-ZackaryBair
/dice_roll/main.py
2,080
4.28125
4
""" Assignment: Challenge Problem 5.13 File: main.py Purpose: Rolls dice x amount of times, and prints out a histogram for the number of times that each number was landed on Instructions: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Analyzing dice rolls is a common example in understanding probability and statistics. The following program calculates the number of times the sum of two dice (randomly rolled) is equal to six or seven. import random num_sixes = 0 num_sevens = 0 num_rolls = int(input('Enter number of rolls:\n')) if num_rolls >= 1: for i in range(num_rolls): die1 = random.randint(1,6) die2 = random.randint(1,6) roll_total = die1 + die2 #Count number of sixes and sevens if roll_total == 6: num_sixes = num_sixes + 1 if roll_total == 7: num_sevens = num_sevens + 1 print('Roll %d is %d (%d + %d)' % (i, roll_total, die1, die2)) print('\nDice roll statistics:') print('6s:', num_sixes) print('7s:', num_sevens) else: print('Invalid number of rolls. Try again.') --------- Create a different version of the program that: Prints a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character, such as *, that number of times. The following provides an example: """ import random rollResults = [] numberRoles = 0 sidesOnDice = 6 #set the number of sides on a dice, also used for a counter print('Rolls a given number of dice and prints out the results') print() #get number of roles while numberRoles <= 0: numberRoles = int(input('How many roles would you like to do?: ')) #roll dice, store results for roll in range(numberRoles): rollResults.append(random.randint(1, sidesOnDice)) #print histogram while sidesOnDice > 0: print(sidesOnDice, end = ': ') for result in rollResults: if result == sidesOnDice: print('*', end = '') sidesOnDice -= 1 print()
true
bb3e967a7776b571cca10fdb988cb09b8980cf63
gptix/cs-module-project-algorithms2
/moving_zeroes/moving_zeroes.py
458
4.28125
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): # Your code here original_length = len(arr) out = [element for element in arr if element is not 0] out = out + [0]*original_length return out[:original_length] if __name__ == '__main__': # Use the main function here to test out your implementation arr = [0, 3, 1, 0, -2] print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
true
db13074a2c8dca8e5d1708a80760d6626f3b0b9b
AdyGCode/Python-Basics-2021S1
/Week-7-1/functions-4.py
1,251
4.34375
4
""" File: Week-7-1/functions-4.py Author: Adrian Gould Purpose: Demonstrate taking code and making it a function Move the get integer code to a function (see functions-3 for the previous code) Design: Define get_integer function Define number to be None While number is none Try the following Ask user for an integer Break from While loop If an exception given: Display "Ooops! Not an integer" return number Define main function Define number1 as the result from "get integer" Display the number If main is being executed: Call main function Test: Run code and enter the following value: 123 Run code and enter the following value: 12.5 Run code and enter the following value: abc """ def get_integer(): number = None while number is None: try: number = int(input("Enter an integer: ")) break # cheat - let's get outta the loop NOW! except ValueError: print("OOPS! not an integer value") return number def main(): number1 = get_integer() print(number1) if __name__ == "__main__": main()
true
425571e8bb0512c2a92f9068883189291acb771b
AdyGCode/Python-Basics-2021S1
/Week-13-1/gui-7-exercise.py
1,242
4.1875
4
# -------------------------------------------------------------- # File: Week-13-1/gui-7-exercise.py # Project: Python-Class-Demos # Author: Adrian Gould <Adrian.Gould@nmtafe.wa.edu.au> # Created: 11/05/2021 # Purpose: Practice using GUI # # Problem: Create a GUI that asks a user for their name and # the year of their birth. When a button is pressed # it presents a greeting of the form # "Welcome NAME, you are XX this year." # # The GUI should look something like this: # Name: __________________ label/text input # Birth Year: __________________ label/number input # __________________________________ label # [How Old?] button # -------------------------------------------------------------- from breezypythongui import EasyFrame class AgeApplication(EasyFrame): def __init__(self): """Sets up the window, labels, and button.""" EasyFrame.__init__(self) self.setSize(600, 300) self.setTitle("How old am I?") # Methods to handle user events. def main(): """Entry point for the application.""" AgeApplication().mainloop() if __name__ == "__main__": main()
true
b306448e151d13b2caeb8cfced3a9650affc29ba
jfbeyond/Coding-Practice-Python
/101_symmetric_tree.py
1,026
4.15625
4
# 101 Symmetric Tree # Recursively def isSymmetric(root): # current node left child is equal to current node right child if not root: return False return checkSymmetry(root, root): def checkSymmetry(node1, node2): if not node1 and not node2: return True if node1 and node2 and node1.val == node2.val: return checkSymmetry(node1.left, node2.right) and checkSymmetry(node1.right, node2.left) return False # O(n) and O(1) # Iteratively def isSymmetric(root): # BFS -- Queue stackl = [root] stackr = [root] while stackl and stackr: nl = stackl.pop(0) nr = stackr.pop(0) # if both nodes are none just go to next iteration if not nl and not nr: continue # This means only one is None, then it's False if not nl or not nr: return False if nl.val != n2.val: return False stackl.append(nl.left) stackl.append(nl.right) stackr.append(nr.right) stackr.append(nr.left) return True # O(n) and O(n)
true
1cca5cc40e84e7e4b314ded2f82786d5e845b0f2
rocooper7/5.Webscraping
/3.Curso_Scrapy/1.Gen_Iter/15.iteradores.py
284
4.3125
4
my_list = [1, 2, 3, 4, 5] #Iterable, como funciona for my_iter = iter(my_list) #Se convierte en iterador print(type(my_iter)) # Extraer los elementos print(next(my_iter)) print(next(my_iter)) print(next(my_iter)) print(next(my_iter)) print(next(my_iter)) print(next(my_iter))
false
1353ee42c247cd5d9a30cb3bd9fc5f33639d181a
F4Francisco/Algorithms_Notes_For_PRofessionals
/Section1.2_FizzBuzzV2.py
777
4.125
4
''' Optimizing the orginal FizzBuzz: if divisable by 3 sub with Fizz if divisable by 5 sub with Buzz if divisable by 15 sub with FizzBuzz ''' # Create an array with numbers 1-5 number = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] #iterate through the array and check which numbers are fizz and which are Buzz for num in number : if num % 15 == 0: print(num) , ("FizzBuzz") elif num % 5 == 0: print (num) , ("Buzz") elif num % 3 == 0: print (num) , ("Fizz") else: print (num) '''The runtime for the orginal algorithm has been improved by dividing by 15: we do not have to check for both 3 and 5 again instead we check one time Check for numbers divisable by 3 (Fizz) Check for numbers divisable by 5 (Buzz) and Check for numbers divisable by 15 (FizzBuzz) '''
true
e5e7ef14baa4d4b7b3596bb4adf7cadaddea2e07
SimaFish/python_practice
/class_practice/auto.py
2,571
4.40625
4
# Zen of Python import this # The definition of a class happens with the `class` statement. # Defining the class `Auto`. # class Auto(object): is also an allowable definition class Auto(): # ToDo class attributes vs. instance attributes # https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide # The __init__() function is called automatically every time the class is being used to create a new object. # Use the __init__() function to assign values to object properties, or other operations # that are necessary to do when the object is being created. Notice two leading and trailing underscores. # The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. # It does not have to be named `self`, you can call it whatever you like, but it has to be the first parameter of any function in the class. def __init__(self, brand, model, year=None): self.brand = brand self.model = model self.year = year # __hash__() should return the same value for objects that are equal. # It also shouldn't change over the lifetime of the object. # Generally you only implement it for immutable objects. def __hash__(self): return 1357 # `equal` def __eq__(self, other): return not other # not `equal` def __ne__(self, other): return not self.__eq__(other) # A method is basically a function that belongs to a class. def get_year(self): if self.year is None: return 'Undefined' else: return str(self.year) def desc_auto(self): print('\nObject:', id(self)) print('Auto:', self.brand + ' ' + self.model) print('Manufactured:', self.get_year()) # Create an instance (object) of `Auto` class. renault_logan = Auto('Renault', 'Logan', 2011) # Invoke method `desc_auto`. renault_logan.desc_auto() # `__sizeof__()` method returns the size of object in bytes print('\nObject size (bytes):', renault_logan.__sizeof__()) # Delete the year property from the renault_logan object: del renault_logan.year print('\nAfter deletion of `year` attribute:') try: print(renault_logan.year, '\n') except AttributeError: print('`renault_logan` object no longer has attribute `year`') # Delete the `renault_logan` object: del renault_logan print('\nAfter deletion of `renault_logan` object:') try: print(id(renault_logan), '\n') except NameError: print('`renault_logan` object is not exists', '\n')
true
43594d3f6b04fcee5ff2285226da49fd96471d89
SimaFish/python_practice
/modules/mod_string.py
1,027
4.25
4
import string # String constants (output type: str). # The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. print('1: ' + string.ascii_lowercase) # The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. print('2: ' + string.ascii_uppercase) # The concatenation of the ascii_lowercase and ascii_uppercase constants described above. print('3: ' + string.ascii_letters) # The string '0123456789'. print('4: ' + string.digits) # The string '0123456789abcdefABCDEF'. print('5: ' + string.hexdigits) # String of ASCII characters which are considered punctuation characters in the C locale: # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~. print('6: ' + string.punctuation) # A string containing all ASCII characters that are considered whitespace. # This includes the characters space, tab, linefeed, return, formfeed, and vertical tab. print('7: ' + string.whitespace) # String of ASCII characters which are considered printable. # This is a combination of digits, ascii_letters, punctuation, and whitespace. print('8: ' + string.printable)
true
6896682b041713dff84ab145274b7858f3f3c7bc
seo0/MLstudy
/adsa_2016/module13_graphs01/part02_basics02/graphs_etc.py
1,760
4.3125
4
import networkx as nx import matplotlib.pyplot as plt from module13_graphs01.part01_basics.graphs_basics import print_graph, display_and_save def modulo_digraph(N,M): """ This function returns a directed graph DiGraph) with the following properties (see also cheatsheet at: http://screencast.com/t/oF8Nr1TdYDbl): - The graph has N nodes, labelled using numbers from 1 to N-1 - All nodes in the same M-modulo class are on the same path (the path from the node with lower value to highest value) - All nodes that are multiple of M-1 (or, in other words, for which node % (M-1) == 0) are on the same path (that gos from lower to higher values) Hint: - Initialise the DiGraph, for each node you can store two properties (value of % M, value of % (M-1)) - Scan the created graph to create paths based on similar values of the two properties - Create edges in the graph using the values of the lists of nodes that you created at the previous step More about DiGraphs at: https://networkx.github.io/documentation/development/reference/classes.digraph.html """ pass def longest_shortest_path(G): """ Given a graph G, this functions prints on screen the longest among the shortest paths between two nodes in G. note that you can check whether a path exists between two nodes using nx.has_path(G, node1, node2) If there are more than 1 longest shortest path, then it doesn't matter which one is chosen """ pass if __name__ == '__main__': G = modulo_digraph(6,3) print_graph(G) longest_shortest_path(G) G = modulo_digraph(7, 2) print_graph(G) G = modulo_digraph(10, 5) print_graph(G) longest_shortest_path(G)
true
1895a345a9021d25dcdc91982ff00b6f3090474a
luckydimdim/grokking
/tree_breadth_first_search/minimum_depth_of_a_binary_tree/main.py
1,086
4.1875
4
from collections import deque class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None def find_minimum_depth(root): ''' Find the minimum depth of a binary tree. The minimum depth is the number of nodes along the shortest path from the root node to the nearest leaf node. ''' if root is None: return -1 queue = deque() queue.append(root) level = 0 while queue: level += 1 level_size = len(queue) for _ in range(level_size): curr = queue.popleft() if not curr.left and not curr.right: return level if curr.left: queue.append(curr.left) if curr.right: queue.append(curr.right) return -1 def main(): root = TreeNode(12) root.left = TreeNode(7) root.right = TreeNode(1) root.right.left = TreeNode(10) root.right.right = TreeNode(5) print("Tree Minimum Depth: " + str(find_minimum_depth(root))) root.left.left = TreeNode(9) root.right.left.left = TreeNode(11) print("Tree Minimum Depth: " + str(find_minimum_depth(root))) main()
true
48f1fa5d3668a54ec73e49e377c610b3bfdba024
luckydimdim/grokking
/modified_binary_search/search_bitonic_array/main.py
1,139
4.15625
4
def search_bitonic_array(arr, key): ''' Given a Bitonic array, find if a given ‘key’ is present in it. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1]. Write a function to return the index of the ‘key’. If the ‘key’ is not present, return -1. ''' start, end = 0, len(arr) - 1 while start <= end: mid = start + (end - start) // 2 is_asc = mid + 1 < len(arr) and arr[mid] < arr[mid + 1] if arr[mid] == key: return mid if is_asc: if arr[mid] < key: start = mid + 1 else: end = mid - 1 else: if arr[mid] < key: end = mid - 1 else: start = mid + 1 return -1 def main(): print(search_bitonic_array([1, 3, 8, 4, 3], 4)) print(search_bitonic_array([3, 8, 3, 1], 8)) print(search_bitonic_array([1, 3, 8, 12], 12)) print(search_bitonic_array([10, 9, 8], 10)) main()
true
9e429a3d67b58bd3e34e0868fa203e80c8215925
luckydimdim/grokking
/modified_binary_search/next_letter/main.py
1,092
4.125
4
import string def search_next_letter(letters, key): ''' Given an array of lowercase letters sorted in ascending order, find the smallest letter in the given array greater than a given ‘key’. Assume the given array is a circular list, which means that the last letter is assumed to be connected with the first letter. This also means that the smallest letter in the given array is greater than the last letter of the array and is also the first letter of the array. Write a function to return the next letter of the given ‘key’. ''' n = len(letters) if key < letters[0] or key > letters[n - 1]: return letters[0] start, end = 0, n - 1 while start <= end: mid = start + (end - start) // 2 if letters[mid] <= key: start = mid + 1 else: end = mid - 1 return letters[start % n] def main(): print(search_next_letter(['a', 'c', 'f', 'h'], 'f')) print(search_next_letter(['a', 'c', 'f', 'h'], 'b')) print(search_next_letter(['a', 'c', 'f', 'h'], 'm')) main()
true
5921d9a5ee2ca9e587ea6d8a54cdaf6126ffd510
luckydimdim/grokking
/subsets/permutations_recursive/main.py
535
4.1875
4
from collections import deque def find_permutations(nums): ''' Given a set of distinct numbers, find all of its permutations. ''' result = [] permutate(nums, 0, [], result) return result def permutate(nums, i, current, result): if i == len(nums): result.append(current) return for l in range(len(current) + 1): next = list(current) next.insert(l, nums[i]) permutate(nums, i + 1, next, result) def main(): print("Here are all the permutations: " + str(find_permutations([1, 3, 5]))) main()
true
57bf01794444f9e3fc31973d50f33a3cdbd9639b
luckydimdim/grokking
/tree_breadth_first_search/zigzag_traversal/main.py
1,289
4.15625
4
from collections import deque class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None def traverse(root): ''' Given a binary tree, populate an array to represent its zigzag level order traversal. You should populate the values of all nodes of the first level from left to right, then right to left for the next level and keep alternating in the same manner for the following levels. ''' result = [] if root is None: return result queue = deque() queue.append(root) zigzag = True while queue: level_size = len(queue) level = deque() zigzag = not zigzag for _ in range(level_size): curr = queue.popleft() if zigzag == True: level.appendleft(curr.val) else: level.append(curr.val) if curr.left: queue.append(curr.left) if curr.right: queue.append(curr.right) result.append(list(level)) return result def main(): root = TreeNode(12) root.left = TreeNode(7) root.right = TreeNode(1) root.left.left = TreeNode(9) root.right.left = TreeNode(10) root.right.right = TreeNode(5) root.right.left.left = TreeNode(20) root.right.left.right = TreeNode(17) print("Zigzag traversal: " + str(traverse(root))) main()
true
667a2a4a9b01eb0f6705f6846263c634ee9405f2
luckydimdim/grokking
/two_heaps/find_the_median_of_a_number_stream/main.py
1,373
4.25
4
from heapq import * class MedianOfAStream: ''' Design a class to calculate the median of a number stream. The class should have the following two methods: insertNum(int num): stores the number in the class findMedian(): returns the median of all numbers inserted in the class If the count of numbers inserted in the class is even, the median will be the average of the middle two numbers. ''' min_heap = [] max_heap = [] def insert_num(self, num): if not self.max_heap or -self.max_heap[0] >= num: heappush(self.max_heap, -num) else: heappush(self.min_heap, num) if len(self.max_heap) > len(self.min_heap) + 1: heappush(self.min_heap, -heappop(self.max_heap)) elif len(self.max_heap) < len(self.min_heap): heappush(self.max_heap, -heappop(self.min_heap)) def find_median(self): if len(self.min_heap) == len(self.max_heap): return -self.max_heap[0] / 2.0 + self.min_heap[0] / 2.0 return -self.max_heap[0] / 1.0 def main(): medianOfAStream = MedianOfAStream() medianOfAStream.insert_num(3) medianOfAStream.insert_num(1) print("The median is: " + str(medianOfAStream.find_median())) medianOfAStream.insert_num(5) print("The median is: " + str(medianOfAStream.find_median())) medianOfAStream.insert_num(4) print("The median is: " + str(medianOfAStream.find_median())) main()
false
0c0d6e43383e97d87fdc6afb562af33a00152f8c
MariaGabrielaReis/Python-for-Zombies
/List-02/L2-ex005.py
576
4.125
4
#Exercise 05 - List 02 #Faça um Programa que leia três números e mostre o maior e o menor deles. print('O maior e o menor nº dentre 3') #entrada de dados a = int(input("a:")) b = int(input("b:")) c = int(input("c:")) # JEITO DO PROFESSOR # se o a for o maior if a>=b and a>=c: print('Maior: ', a) # se o b for o maior elif b>=a and b>=c: print('Maior: ', b) # se o c for o maior else: print('Maior: ', c) # se o a for o menor if a<=b and a<=c: print('Menor: ', a) # se o b for o menor elif b<=a and b<=c: print('Menor: ', b) # se o c for o menor else: print('Menor: ', c)
false
03e7a2218937f12112e322ac88ce065cceb7b23f
darshanchandran/PythonProject
/PythonProject/Classes and Modules/Classes/Compositions.py
336
4.28125
4
#This program shows how compositions work with out inheriting the parent class class Parent(object): def boss(self): print("I'm the boss") class Child(object): def __init__(self): self.child = Parent() def boss(self): print("Child is the boss") self.child.boss() son = Child() son.boss()
true
49fe5540582f959dbff34fa2a46ff80abdeac2ac
Diatemba99/Notebook
/list.py
650
4.125
4
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saterday", "Sunday"] print(week[3]) week[1]="Lundi" print(len(week)) print((week)) print("----------------------------------") mylist=[1, 56, "hello", [7, 20], True] print(len(mylist[3])) mylist.append("Toyota") print(mylist) mylist.insert(2, "Ziar") print(mylist) #Delete operation with list print("***********************************") mylist.remove("hello") print(mylist) print("***********************************") del mylist[3] print(mylist) print("++++++++++++++++++++++++++++++++++++++") mylist2=[1, 56, "hello", [7, 20], True] del mylist2[3][1] print(mylist2)
false
c0c7027ee70e6be6a0f9b067fc0f1df9b6276bc0
EmissaryEntertainment/3D-Scripting
/Week_2/McSpadden_Exercise_2.3.py
699
4.21875
4
#Use each form of calculation besides modulus print("2 + 5 = " + str(2+5)) print("2 - 5 = " + str(2-5)) print("2 * 5 = " + str(2*5)) print("2 / 5 = " + str(2/5)) print("2 ** 5 = " + str(2**5)) #Calculation whos resluts depend on order of operations print("160 + 5 * 7 = " + str(160 + 5 * 7)) #Force change order of operations by using parenthesis print("(160 + 5) * 7 = " + str((160 + 5) * 7)) #Long decimal result is not what is expected print("0.1 + 0.2 = " + str(0.1+0.2)) #Find another calculation that results in a long decimal print("3 * 0.1 = " + str(3*0.1)) #Using integer division to decide which version of python I am using print("4 / 2 = " + str(4/2) + " Which means I have Python 3")
true
ac951d9f278b6ec976a41e167ba50b6388432c96
EmissaryEntertainment/3D-Scripting
/Week_3/McSpadden_Exercise_3.5_PEP8.py
522
4.15625
4
# ALPHABET SLICE alphabet = ["a","b","c","d","e","f","g","h","i","j"] slice = alphabet[0:3] for letter in slice: print("First slice: " + letter) slice = alphabet[4:8] for letter in slice: print("Second slice: " + letter) slice = alphabet[2:] for letter in slice: print("Third slice: " + letter) # PROTECTED LIST list = ["Jim", "Bob", "Joe"] list_copy = list[:] list_copy.insert(0,"Quincy") for name in list: print("Original list names: " + name) for name in list_copy: print("listCopy names: " + name)
false
2c709c8d07c8a738177250eb5b4d029c3945dd7b
EmissaryEntertainment/3D-Scripting
/Week_4/McSpadden_Exercise_4.3.py
897
4.25
4
#THREE IS A CROWD print("-------THREE IS A CROWD-------") names = ["Jose", "Jim","Larry","Bran"] def check_list(list): if len(list) > 3: print("This list is to crowded.") check_list(names) del names[0] check_list(names) #THREE IS A CROWD - PART 2 print("-------THREE IS A CROWD - PART 2-------") def check_list_pt2(list): if len(list) > 3: print("This list is to crowded.") else: print("This list is a great size.") check_list_pt2(names) #SIX IS A MOB print("-------SIX IS A MOB-------") names.append("Steve") names.append("Quincy") def six_is_a_mob(list): if len(list) > 5: print("There is a mob in the room.") elif len(list) >= 3 and len(list) <= 5: print("This room is crowded.") elif len(list) == 1 or len(list) == 2: print("This room is not crowded.") else: print("The room is empty.") six_is_a_mob(names)
true
567addd4e775a0a80665b75a1666cbf1fdda28e9
KumarjitDas/Algorithms
/Algorithms/Recursion/Python/countdown.py
911
4.5
4
def countdown(value: int): """ Print the countdown values. countdown ========= The `countdown` function takes an integer value and decreases it. It prints the value each time it. It uses 'recursion' to do this. Parameters ---------- value: int an integer value Returns ------- None """ if value <= 0: # The base case: if the value is zero print("Stop!") # then stop countdown return print(value, end=' ') countdown(value - 1) # The recursive case: call countdown # (itself) with value decreased by 1 if __name__ == '__main__': print('Countdown start:', end=' ') countdown(10)
true
110c972931fe16b1d605396a7d2813388ebf3282
HossamSalaheldeen/Python_lab1
/prob3.py
915
4.1875
4
# Problem 3 #------------- # Consider dividing a string into two halves. # Case 1: # The length is even, the front and back halves are the same length. # Case 2: # The length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b, return a string of the form : # (a-front + b-front) + (a-back + b-back) def combine_strs(a,b): print(len(a)) a_front = a[0:len(a)//2 if len(a)%2 == 0 else ((len(a)//2)+1)] print(a_front) a_back = a[((len(a)//2)) if len(a)%2 == 0 else ((len(a)//2)+1):len(a)] print(a_back) print(len(b)) b_front = b[0:len(b)//2 if len(b)%2 == 0 else ((len(b)//2)+1)] print(b_front) b_back = b[((len(b)//2)) if len(b)%2 == 0 else ((len(b)//2)+1):len(b)] print(b_back) ab = (a_front + b_front) + (a_back + b_back) return ab print(combine_strs("abcd","abcd"))
true
2a7963e01f163f9b2c85e8d64de66630914f7328
JemrickD-01/Python-Activity
/WhichWord.py
617
4.21875
4
def stringLength(fname,lname): if len(fname)>len(lname): print(fname,"is longer than",lname) elif len(fname)<len(lname): print(lname,"is longer than",fname) else: print(fname,"and",lname,"have the same size") choices = ["y","n"] ans="y" while ans=="y": x=input("enter your first word: ") y=input("enter your second word: ") stringLength(x,y) ans=input("would you like to continue?(y/n): ") if ans not in choices: print("Enter y or n only") ans=input("would you like to continue? y/n") else: print("Done")
true
af1ecc1dfb000a8dd0aab062123a29c489a7f426
Raj-kar/PyRaj-codes
/password.py
1,300
4.28125
4
''' Homework 1 - WAP to genarate a secure password. - 1. password must contains minimim 8 char. - 2. both upper and lower case. - 3. must contains two number and one special char. bonus - shuffle the password, for better security. Homework 2 - Optimize the below Code. ''' # Wap to check a password is secure or not ? from string import ascii_lowercase, ascii_uppercase, digits, punctuation password = input("Enter your password :: ") if len(password) < 8: print("Password must contains minimim 8 char.") else: lowerCase = False for letter in password: if letter in ascii_lowercase: lowerCase = True break if lowerCase == True: upperCase = False for letter in password: if letter in ascii_uppercase: upperCase = True break if upperCase == True: count = 0 for letter in password: if letter in digits: count += 1 if count >= 2: special_char = False for letter in password: if letter in punctuation: special_char = True break if special_char == True: print("Password VALID !!!! :) ") else: print("minimim one special char required") else: print("Minimum 2 digits required !") else: print("Minimum 1 upperCase letter required") else: print("Minimum 1 lowerCase letter required !")
true
82fc2124669344ca0291a5d9bef9d8f70b01e7b9
avantikabagri/lecture8
/3/gradepredict_stubs.py
2,028
4.21875
4
# reads a CSV from a file, and creates a dictionary of this form: # grade_dict['homeworks'] = [20, 20, 20, ...] # grade_dict['lectures'] = [5, 5, 5, ...] # ... # params: none # returns: a dictionary as specified above def get_data(): return {} # param: list of lecture excercise scores # return: total scores for lecture exercises, after dropping lowest 4 def calculate_lecture_exercise_score(lecture_scores): return 0 # param: list of discussion scores # return: total scores for discussions, dropping lowest 2 def calculate_discussion_score(discussion_scores): return 0 # param: list of homework scores # return: total points for homeworks, after dropping lowest 2 def calculate_homework_score(homework_scores): return 0 # param: list of midterm scores # return: total points for midterm category def calculate_midterm_score(midterm_scores): return 0 # param: list of project scores # return: total points for project category def calculate_project_score(project_scores): return 0 # given the total points earned, converts to the final letter grade # param: total_score # return: string representing a letter grade def convert_to_letter_grade(total_score): return 'X' def test(): #test for calculate_homework_score homeworks = [20,20,20,20,20,20,20,20,20,20,20,20,20,20] expected_output = 20*12 homeworks2 = [10,10,12,12,14,14,16,16,18,18,20,20,22,22] expected_output2 = 12+12+14+14+16+16+18+18+20+20+22+22 if calculate_homework_score(homeworks) == expected_output: print("pass 1") else: print("fail 1") if calculate_homework_score(homeworks2) == expected_output2: print("pass 2") else: print("fail 2") test() grade_dict = get_data() total_score = 0 if 'homeworks' in grade_dict: total_score += calculate_homework_score(grade_dict['homeworks']) # same for the other categories letter_grade = convert_to_letter_grade(total_score) print('You will get a', letter_grade, 'with', total_score, 'points') # write some tests here
true
42ea0a6fe036ea1fbb3059a715461680a0e13146
saubhik/catalog
/src/catalog/tries/add-and-search-word-data-structure-design.py
2,412
4.3125
4
# Add and Search Word - Data structure design # # https://leetcode.com/problems/add-and-search-word-data-structure-design/ # import unittest from typing import Dict class TrieNode: def __init__(self): self.children: Dict[str, TrieNode] = dict() self.end: bool = False class WordDictionary: def __init__(self): """ Initialize data structure """ self.root = TrieNode() def add_word(self, word: str) -> None: """ Adds a word into the data structure. :param word: the word to add. :return: None """ current_node = self.root for letter in word: if letter not in current_node.children: current_node.children[letter] = TrieNode() current_node = current_node.children[letter] current_node.end = True def search(self, word: str, current_node: TrieNode = None) -> bool: """ Returns if the word is in the data structure. A word could contain the dot character "." to represent any one letter. :param word: the word to search for. :param current_node: current node the trie we start searching from. :return: True or False. """ if not current_node: current_node = self.root if not word: return current_node.end if word[0] in current_node.children: return self.search(word[1:], current_node.children[word[0]]) if word[0] != ".": return False for key in current_node.children: if self.search(word[1:], current_node.children[key]): return True return False class Test(unittest.TestCase): def test_add_word(self): word_dict = WordDictionary() word_dict.add_word("dog") self.assertEqual(True, word_dict.search("dog")) self.assertEqual(False, word_dict.search("dogs")) def test_search(self): word_dict = WordDictionary() word_dict.add_word("dog") word_dict.add_word("mad") self.assertEqual(True, word_dict.search("dog")) self.assertEqual(False, word_dict.search("..e")) self.assertEqual(True, word_dict.search("..d")) self.assertEqual(True, word_dict.search(".a.")) self.assertEqual(False, word_dict.search(".p.")) if __name__ == "__main__": unittest.main()
true
58d34d94f58f56f4c1e8dbf9d3b8a97d23ed8e0e
Ry09/Python-projects
/Random Stuff/collatz.py
1,142
4.65625
5
# This is a program to run the Collatz Sequence. It will # take a number from the user and then divide it by 2 if # it is even, or multiply by 3 and add 1 if it is odd. It # will loop through this until it reaches the value of 1. def collatz(num): try: num = int(num) print(num) if num == 1: print("Cannot begin with 0 or 1.") return 0 while(num != 1): if num == 0: print("Cannot begin with 0 or 1.") return 0 elif num % 2 == 0: num = num / 2 print(num) continue else: num = num * 3 + 1 print(num) continue return num except ValueError: print("Incorrect value entered. Please input a number.") return 0 while True: x = input("Please enter a number to begin the Collatz Sequnce. Also note that it cannot begin with 0 or 1: ") if collatz(x) == 1: print("And there you have the Collatz Sequence!") break else: continue input("\n\n\nPress enter to exit.")
true
c5184214e0daa2623467ba19929296893138d682
denis-meshcheryakov/Learn_python_lesson_1
/dicts.py
308
4.1875
4
dict1 = {"city": "Москва", "temperature": "20"} print(dict1['city']) dict1['temperature'] = int(dict1['temperature']) - 5 print(dict1) if 'country' not in dict1: print('country is not in keys') print(dict1.get('country', 'Россия')) dict1['date'] = '27.05.2019' print(len(dict1)) print(dict1)
false
7c369fcf4710b134b7437724685698895b2f50aa
ProgFuncionalReactivaoct19-feb20/clase03-Jdesparza
/Ejercicio3.py
624
4.125
4
""" Ejemplo 7 Jdesparza Funcional - Aplicando función filter Dadas las siguiente ciudades, filtrar aquellas que tienen un número par como longitud en sus caracteres. Loja, Pichincha, Guayaquil, Zamora, Ibarra, Manabi, Machala, Portoviejo, Macas """ # se crea una lista con las ciudades ciudades = ["Loja", "Pichincha", "Guayaquil", "Zamora", "Ibarra", "Manabi", "Machala", "Portoviejo", "Macas"] # variable que filtra mediante el uso de lambda aquellas ciudades que tienen un caracter par resultado = filter(lambda x: len(x) % 2 == 0, ciudades) # se imprime los resultados print(resultado) print(list(resultado))
false
927170aae55b2529e503f3e1836cd0ac6d18516b
rayadamas/pythonmasterclassSequence
/coding exercise 14.py
662
4.21875
4
# Write a program which prompts the user to enter three integers separated by "," # user input is: a, b, c; where those are numbers # The following calculation should be displayed: a + b - c # 10, 11, 10 = 11 # 7, 5, -1 = 13 # Take input from the user user_input = input("Please enter three numbers: ") # Split the given input string into 3 parts number_split = user_input.split(',') # Convert the tokens into integers number_tuple = [] for st in number_split: number_tuple.append(int(st)) # Calculate the result: a + b - c result = number_tuple[0] + number_tuple[1] - number_tuple[2] # Output the result print(result)
true
a6c5cc0f90f540202efa1c8f6b1098d99c3c4397
surprise777/StrategyGame2017
/Game/current_state.py
1,959
4.3125
4
"""module: current_state (SuperClass) """ from typing import Any class State: """a class represent the state of class. current_player - the player name who is permitted to play this turn. current_condition - the current condition of the state of the game """ current_player: str current_condition: str def __init__(self) -> None: """initialize the class. >>> st1 = State() """ self.current_player = '' self.current_condition = '' def __str__(self) -> str: """return the string represention of the class. """ raise NotImplementedError("Must implement a subclass!") def __eq__(self, other: "State") -> bool: """compare if self is equivalent to the other. """ return type(self) == type(other) and \ self.current_condition == other.current_condition and \ self.current_player == other.current_player def get_possible_moves(self) -> list: """get a list of all possible moves of self game which are valid. """ raise NotImplementedError("Must implement a subclass!") def is_valid_move(self, move: Any) -> bool: """return True if the move from the str_to_move is valid. """ raise NotImplementedError("Must implement a subclass!") def make_move(self, move_to_make: Any) -> "State": """return new current state class after changing the move of the game. """ raise NotImplementedError("Must implement a subclass!") def get_current_player_name(self) -> str: """return the current player's name of the self game. >>> st1 = State() >>> st1.current_player ='a' >>> st1.get_current_player_name() 'a' """ return self.current_player if __name__ == "__main__": from doctest import testmod testmod() import python_ta python_ta.check_all(config="a1_pyta.txt")
true
a23930569e83eb420cc1f2290f35bb43853be0c2
caboosecodes/Python_Projects
/python_If.py
297
4.25
4
height = 200 if height > 150: if height > 195: print('you are too tall ride the roller coaster') else: print('you can ride the roller coaster') elif height >= 125: print('you need a booster seat to ride the roller coaster') else: print('where are your parents?')
true
2590e80758fe499b1d133a86ac83a60b5185c350
matbc92/learning-python
/Data Structures/ds_seq.py
1,372
4.5
4
# listas strings e tuples, são sequencias, uma vez que sequencias sao conjuntos ordenados # uma vez que eles sao ordenados pode se utilizar uma operação chamada slicing, # ou seja selecionar apenas alguns itens desta sequencia, para tanto é necessario dizer # a posição do primeiro e do ultimo item que se quer slecionar e por fim, opcionalmente o step, # ou seja de quantos em quantos itens serao selecionados shoplist = ['apple', 'mango', 'carrot', 'banana'] name = 'swaroop' # Indexing or 'Subscription' operation # print('Item 0 is', shoplist[0]) print('Item 1 is', shoplist[1]) print('Item 2 is', shoplist[2]) print('Item 3 is', shoplist[3]) print('Item -1 is', shoplist[-1]) print('Item -2 is', shoplist[-2]) print('Character 0 is', name[0]) # Slicing on a list # print('Item 1 to 3 is', shoplist[1:3]) print('Item 2 to end is', shoplist[2:]) print('Item 1 to -1 is', shoplist[1:-1]) print('Item start to end is', shoplist[:]) # Slicing on a string # print('characters 1 to 3 is', name[1:3]) print('characters 2 to end is', name[2:]) print('characters 1 to -1 is', name[1:-1]) print('characters start to end is', name[:],'\n') print('shoplist com step 1, ou seja padrão',shoplist[::1],'\n') print('shoplist com step 2',shoplist[::2],'\n') print('shoplist com step 3',shoplist[::3], '\n') print('shoplist com step -1 ou seja em reverso',shoplist[::-1])
false
8305a8bfae9ee64d3f446e485c8c602e50e6abb5
matbc92/learning-python
/flow control/if_e_while.py
1,619
4.25
4
#if condiciona o programa a executar um bloco de instruções se certas condições forem atendidas # e outro(s) se condições diferentes ocorrerem, as condições diferentes podem ser especificadas # por meio do comando elif, que efetivamente cria um outro nó de if, ou simplesmente permanecerem # como qualquer coisa diferente da condição determinada por if ######################################################################## #já o comando while, separa um bloco de texto que será repetido enquanto o parametro determinado, # seja verdadeiro, ou que um comando de break aconteça, uma vez que o parametro se torna falso, # o programa retorna ao bloco de texto no qual o while está inserido(isto também é valido para o if), # a não ser que o comando else seja utilizado, sendo assim as instruções dentro deste comando seram executadas # antes do programa retornar ao bloco de codigo anterior. numero = 30 running = True while running: chute = int(input('Tente adivinhar o número secreto: ')) if chute == 1: print('Um? Não acha meio obvio? Tente um número um pouco maior') elif chute == 2: print('Dois? mas dois é tão obvio, tente um número maior') elif chute == 3: print('três, mas que numero mais bobo tente um pouquinho maior') elif chute < numero: print('hmmm... não é esse, tente um numero maior') elif chute > numero: print('voce passou, tente um numero um pouco menor') else: print('parabens voce acertou, aqui está seu vale biscoito imaginário') running = False else: print('o jogo terminou')
false
4ef85b3373806e1e5b05cbfd22e85abff40b12fe
matbc92/learning-python
/input_output/io_input.py
686
4.4375
4
# programa simples com duas funções definidas, # uma que inverte uma string de texto, usando um operador sobre sequencias # que inverte a ordem, e uma função que utiliza esta função de # reversão para testar se a string é palindromica ao comparar # com o resultado da função que inverte o texto def reverse(text): return text[::-1] def is_palindrome(text=str): import string text = text.replace(' ', '').lower().translate(str.maketrans({key: None for key in string.punctuation})) return text == reverse(text) something = input("Enter text: ") if is_palindrome(something): print("Yes, it is a palindrome") else: print("No, it is not a palindrome")
false
c901a714e56f22c3f31fef767205df16ab561035
ScottSko/Python---Pearson---Third-Edition---Chapter-5
/Chapter 5 - Maximum of Two Values.py
379
4.21875
4
def main(): num1 = int(input("Please enter a value: ")) num2 = int(input("Please enter another value: ")) greater_value = maximum(num1, num2) print("The greater value is", greater_value) def maximum(num1,num2): if num1 > num2: return num1 elif num1 == num2: print("The values are equal.") else: return num2 main()
true
a8a822c69bad9199cdbc345d6fc0ed7ed905162a
srikanthanagaraja/Python_Examples
/Scripts/List/List.py
647
4.15625
4
my_list = ['p','r','o','b','e'] # Output: p print(my_list[0]) # Output: o print(my_list[2]) # Output: e print(my_list[4]) # Error! Only integer can be used for indexing # my_list[4.0] # Nested List n_list = ["Happy", [2,0,1,5]] # Nested indexing # Output: a print(n_list[0][1]) print("The index of Happy is ",n_list.index("Happy")) # Output: 5 print(n_list[1][3]) print(n_list[0]) print(n_list[1]) n_list_new = [["Happy", [2,0,1,5]],"Welcome"] print(n_list_new[0][1]) print(n_list_new[0][1][0]) print(n_list_new[-1]) print(n_list_new[0][-1][-1]) #numbers={1,5,1,52,6} #count=numbers.count(1) #print("The value of count is ",count)
false
3ce6d57c9a06622e7cae3f1bc2fa2baa1946be36
Nikhil-Xavier-DS/Sort-Search-Algorithms
/bubble_sort.py
467
4.28125
4
""" Implementation of Bubble Sort. """ # Author: Nikhil Xavier <nikhilxavier@yahoo.com> # License: BSD 3 clause def Bubble_sort(arr): """Function to perform Bubble sort in ascending order. TIME COMPLEXITY: Best:O(n), Average:O(n^2), Worst:O(n^2) SPACE COMPLEXITY: Worst: O(1) """ for outer in range(len(arr)-1, 0, -1): for inner in range(outer): if arr[inner] > arr[inner+1]: arr[inner], arr[inner+1] = arr[inner+1], arr[inner]
true
b8d279107217bfbf7174bb4dd054b254a5e90a7c
SreeramSP/Python-Programs-S1
/factorial.py
235
4.1875
4
n=int(input("Enter the number=")) factorial=1 if n<0: print("No negative Numbers") elif n==0: print("The factorial of 0 is 1") else: for i in range(1,n+1): factorial=factorial*i print("Factorial=",factorial)
true
19d17745e0d2aee9ab3b65763076772ba449c6f9
richartzCoffee/aulasUdemy
/templates2/sorted.py
359
4.125
4
""" sorted com qualquer interavel """ numero = [1,2,3,56,41,5] print(numero) print(tuple(sorted(numero))) print(sorted(numero,reverse=True)) usuarios =[ {"usarname":"daniel","tw":["oi"]}, {"usarname": "daaniaaaaaaael", "tw": [],"cor":"amarelo"}, {"usarname":"daniaael","tw":["oi"]} ] print(sorted(usuarios,key=lambda usuario: len(usuario["tw"])))
false
283112adcd03688236d72a9748711469976a4976
standrewscollege2018/2021-year-11-classwork-SamEdwards2006
/Paracetamol.py
662
4.125
4
#sets the constants AGE_LIMIT = 12 WEIGHT_LIMIT = 0 on = 1 #finds the users age while(on > 0): age = int(input("How old are you: ")) #tests if the age is more than 12, #if not, it will go to the else. if age >= AGE_LIMIT: print("Recommend two 500 mg paracetamol tablets") elif age >= 0: #takes the users weight, and if it is more than 0 # it will multiply the weight by 10 weight = float(input("How much do you weigh: ")) if weight > WEIGHT_LIMIT: print("Your recommended dose is", weight * 10,"mg") else: print("invalid weight") else: print("invalid age")
true
78a556658eea5d03ebbdd76ecf3e7d2888f3860c
rafa761/leetcode-coding-challenges
/2020 - august/008 - non-overlapping intervals.py
1,500
4.40625
4
""" Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Example 1: Input: [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of intervals are non-overlapping. Example 2: Input: [[1,2],[1,2],[1,2]] Output: 2 Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping. Example 3: Input: [[1,2],[2,3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping. Note: You may assume the interval's end point is always bigger than its start point. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. """ from typing import List class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if len(intervals) < 2: return 0 intervals.sort() count, last_included = 0, 0 for i in range(1, len(intervals)): if intervals[i][0] < intervals[last_included][1]: count += 1 if intervals[i][1] < intervals[last_included][1]: last_included = i else: last_included = i return count if __name__ == '__main__': S = Solution() print('-> 1: ', S.eraseOverlapIntervals([[1, 2], [2, 3], [3, 4], [1, 3]])) print('-> 2: ', S.eraseOverlapIntervals([[1, 2], [1, 2], [1, 2]])) print('-> 0: ', S.eraseOverlapIntervals([[1, 2], [2, 3]])) print('-> 2: ', S.eraseOverlapIntervals([[1, 100], [11, 22], [1, 11], [2, 12]]))
true
d434bdf3a1a81c9a1742259d0c683d373bdba1a4
Shinji94/python_programming_coursework
/slides/Week 7/Point.py
545
4.28125
4
class Point: """ Point class represents and manipulates x,y coords. """ def __init__(self, x=0, y=0): """ Create a new point at x, y """ self.x = x self.y = y def distance_from_origin(self): """ Compute my distance from the origin """ return ((self.x ** 2) + (self.y ** 2)) ** 0.5 def copy(self): newPoint = Point(self.x, self.y) return newPoint a = Point(5,4) b = Point(3,2) b = a.copy() b.x = 7 print(str(a.x) + ", " + str(a.y)) print(str(b.x) + ", " + str(b.y))
false
0c4e754032669f8fc75184a5cdfe9ae0e23bf904
vismayatk002/PythonAssignment
/Algorithm Programs/BubbleSort.py
592
4.3125
4
""" @Author : Vismaya @Date : 2021-10-20 07:36 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 07:47 @Title : Bubble Sort """ arr = [] def bubble_sort(): n = len(arr) for i in range(n - 1): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] print("Sorted array : ", arr) num = int(input("Enter the number of elements to be insert : ")) print("Enter the elements : ") for j in range(num): arr.append(input()) print("Unsorted Array : ", arr) bubble_sort()
false
2442c3261cc4d4280d0a46878a3e10d250298b4a
vismayatk002/PythonAssignment
/BasicCorePrograms/PrimeFactors.py
542
4.3125
4
""" @Author : Vismaya @Date : 2021-10-18 11:39 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 12:52 @Title : Prime factors of a number """ def is_prime(num): flag = 0 for j in range(2, num): if num % j == 0: flag = 1 break j += 1 return flag; number = int(input("Enter the Number : ")) i = 2 print("Prime factors : ") while i <= number: if number % i == 0: result = is_prime(i) if result == 0: print(i) i += 1
true
d2e113be4619cdd2b389dd8066e067c2ee1f1440
gsmcclellan/sorting_algorithms
/merge.py
749
4.34375
4
""" A merge sort recursively splits a list into smaller lists until they have a len of one or zero, then combine each list into a single sorted list """ def merge_sort(nums): if len(nums) > 1: first_half = nums[:len(nums)//2] second_half = nums[len(nums)//2:] first_half = merge_sort(first_half) second_half = merge_sort(second_half) i = j = k = 0 while i < len(first_half) and j < len(second_half): if first_half[i] < second_half[j]: nums[k] = first_half[i] i += 1 else: nums[k] = second_half[j] j += 1 k += 1 while i < len(first_half): nums[k] = first_half[i] k += 1 i += 1 while j < len(second_half): nums[k] = second_half[j] k += 1 j += 1 return nums else: return nums
false
33579d9a2d351a6a33f82b708c68be6233c45afb
DrSneus/cse-20289-sp21-examples
/lecture09/is_anagram.py
2,111
4.1875
4
#!/usr/bin/env python3 import os import sys # Functions def usage(status=0): print(f'''Usage: {os.path.basename(sys.argv[0])} [flags] -i Ignore case distinctions This program reads in two words per line and determines if they are anagrams. ''') sys.exit(status) def count_letters(string): ''' Returns a dictionary containing counts of each letter in string >>> count_letters('aaa bb c') {'a': 3, 'b': 2, 'c': 1} ''' counts = {} # Discuss: counting pattern for letter in string: if not letter.isspace(): counts[letter] = counts.get(letter, 0) + 1 # Discuss: get dictionary method return counts def is_anagram(word1, word2): ''' Returns whether or not word1 and word 2 are anagrams >>> is_anagram('dormitory', 'dirty room') True >>> is_anagram('asdf', 'asdfg') False ''' counts1 = count_letters(word1) counts2 = count_letters(word2) for key in counts1: # Discuss: iterating through dictionary if counts1[key] != counts2.get(key, 0): return False for key in counts2: if counts2[key] != counts1.get(key, 0): return False return True def main(): # Parse command-line options arguments = sys.argv[1:] # Review: command line arguments ignorecase = False while arguments and arguments[0].startswith('-'): argument = arguments.pop(0) # Discuss: popping from queue if argument == '-i': ignorecase = True elif argument == '-h': usage(0) else: usage(1) # Process standard input for line in sys.stdin: if ignorecase: line = line.lower() word1, word2 = line.split(' ', 2) # Discuss: splitting string if is_anagram(word1, word2): print('ANAGRAM!') else: print('NOT ANAGRAM!') # Main Execution if __name__ == '__main__': main()
true
0b777077897ac2ae8fc9bea47dae6853cafd31fd
jemarsha/leetcode_shenanigans
/Random_problems/Merged_k_linked_lists.py
1,138
4.375
4
#from typing import List class Node: def __init__(self,value): self.value = value self.next = None def merge_lists(lists): """ This function merges sorted linked lists- Reads the values in one at a time into a list O(kn). Then sorts them O(nlogn). Then puts them into a linked list (O(n). Overall complexity is O(kn). This can be improved @param lists: list of sorted linked lists @return: a sorted linked list """ nodes = [] head = point= Node(0) for val in lists: while val: nodes.append(val.value) val= val.next nodes = sorted(nodes) for val2 in nodes: point.next = Node(val2) print(point.next.value, end = '->') point= point.next #return(nodes) print('\n') return head.next.value if __name__ == "__main__": list_1 = Node(1) list_1.next = Node(4) list_1.next.next = Node(5) list_2 = Node(1) list_2.next = Node(3) list_2.next.next = Node(4) list_3 = Node(2) list_3.next = Node(6) k_lists = [list_1, list_2, list_3] print((merge_lists(k_lists)))
true
81ade07d0881570c4d1ddc424c107c9e2e51dfef
nicecoolwinter/note
/python/data/python_book_slides/code_5/Person_2.py
756
4.1875
4
class Person(): HI_STR = 'Hi, I am ' def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print('Hello, I am ' + self.name) def say_hi(self): print(Person.HI_STR + self.name) def __str__(self): return '<Person> %s, age %d' % (self.name, self.age) def __repr__(self): return "Person('%s', %d)" % (self.name, self.age) p1 = Person('Amy', 25) p2 = Person('Bob', 38) p1.say_hello() Person.say_hello(p1) p2.say_hello() p1.say_hi() p2.say_hi() print(p1) print(str(p2), p2.__str__()) print(repr(p1), p1.__repr__()) print() exec('p3 = ' + repr(p2)) print(p3) print(p3.name, p3.age)
false
70826eefc7345f3d96c93173f0b17a4b5c1123e5
Sumanpal3108/21-days-of-programming-Solutions
/Day14.py
371
4.625
5
str1 = input("Enter any String: ") str2 = input("Enter the substring you want to replace: ") str3 = input("Enter the string you want to replace it with: ") s = str1.replace(str2,str3) print("The original string is: ",str1) print("The substring you want to replace: ",str2) print("The string you want to use instead: ",str3) print(s) input("Enter any key to exit")
true
35d63b5e2f65b675c138fcc477b9a4d0185f33c7
Sumanpal3108/21-days-of-programming-Solutions
/21daysprogrammingDay1.py
683
4.15625
4
import math a = float(input("Enter the coefficient a: ")) b = float(input("Enter the coefficient b: ")) c = float(input("Enter the coefficient c: ")) print("The quadratic equation is: {}X2 + {}X + {} = 0".format(a,b,c)) d = b**2 - 4*a*c print('The value of d is: ',d) if d>0: r1 = (-b + math.sqrt(d))/(2 * a) r2 = (-b - math.sqrt(d))/(2 * a) print("Roots are real and unequal ",r1,r2) elif d==0: r1 = -b/(2*a) print("Roots are real and same ",r1) else: A = (-b/(2*a)) s = (4*a*c - b**2) B = (math.sqrt(s))/(2 * a) print("Roots are complex and imaginary {} + {}i and {} - {}i".format(A,B,A,B))
false
fe511ba08d1ba756f4a7b7122ccee3b331bdf1a3
Yasir77788/Shopping-Cart
/shoppingCart.py
1,959
4.21875
4
# shopping cart to perform adding, removing, # clearing, and showing the items within the cart # import functions from IPython.display import clear_output # global list variable cart = [] # create function to add items to cart def addItem(item): clear_output() cart.append(item) print("{} has been added.".format(item)) # create function to remove item from cart def removeItem(item): clear_output() try: cart.remove(item) print("{} has been removed.".format(item)) except ValueError as e: print("Sorry we could not remove that item.") print(e) # create fucntio to show items int cart def showCart(): clear_output() if cart: print("Here is your cart:") for item in cart: print("- {}".format(item)) else: print("Your cart is empty.") # create function to clear itmes from the cart def clearCart(): clear_output() cart.clear() print("Your cart is empty") # creat main function that loops until the user quit def main(): done = False while not done: print("\nPlease, select one option from the following:") ans = input("\nquit/add/remove/show/clear: ").lower() if ans == "quit": print("Thanks for using...") showCart() done = True elif ans == "add": item = input("What would you like to add? ").title() addItem(item) elif ans == "remove": showCart() item = input("What item would u like to remove? ").title() removeItem(item) elif ans == "show": showCart() elif ans == "clear": clearCart() print("Cart has been cleared.") else: print("Sorry that was not an option.") # run the programm if __name__ == "__main__": main()
true
6f4cfa2188d0845d9ad888f1540edd6f74c83b87
Kevinloritsch/Buffet-Dr.-Neato
/Python Warmup/Warmup #3 - #2 was Disneyland/run3.py
766
4.125
4
import math shape = input("What shape do you want the area of? Choose a rectangle, triangle, or circle ;) ") if shape=='rectangle': rone = input("What is the length of the first side? ") rtwo = input("What is the length of the second side? ") answer = int(rone)*int(rtwo) print(answer) elif shape=='triangle': tone = input("What is the length of the base? ") ttwo = input("What is the length of the height? ") answer = int(tone)*int(ttwo) answer = int(answer)/2 print(answer) elif shape=='circle': cone = input("What is the length of the radius? ") answer = int(cone)*int(cone) answer = int(answer)*math.pi print("Your answer is approximatly", answer, end='\n') else: print("Loser--not a valid shape...")
true