blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3da236e3ada6bafbcef1cfe174dc337ee879fbd4
ncaleanu/allthingspython
/advanced_func/collections-exercises.py
2,617
4.5
4
from collections import defaultdict, OrderedDict, namedtuple, deque # PRACTISING WITH SOME DATA STRUCTURES FROM COLLECTIONS def task1() -> defaultdict: """ - create a `defaultdict` object, and its default value would be set to the string `Unknown`. - Add an entry with key name `Alan` and its value being `Manchester`. - Return the `defaultdict` object you created. """ # you code starts here: task1 = defaultdict(lambda: 'Unknown') task1.update({'Alan': 'Manchester'}) return task1 print(task1()) def task2(arg_od: OrderedDict): """ - takes in an OrderedDict `arg_od` - Remove the first and last entry in `arg_od`. - Move the entry with key name `Bob` to the end of `arg_od`. - Move the entry with key name `Dan` to the start of `arg_od`. - You may assume that `arg_od` would always contain the keys `Bob` and `Dan`, and they won't be the first or last entry initially. """ # you code starts here: arg_od.popitem(last=False) # removes first item arg_od.popitem() # removes last item arg_od.move_to_end('Bob') # moves Bob to end arg_od.move_to_end('Dan', last=False) # moves Dan to front print(arg_od) o = OrderedDict([ ('Alan', 'Manchester'), ('Bob', 'London'), ('Chris', 'Lisbon'), ('Dan', 'Paris'), ('Eden', 'Liverpool'), ('Frank', 'Newcastle') ]) print(o) task2(o) def task3(name: str, club: str) -> namedtuple: """ - create a `namedtuple` with type `Player`, and it will have two fields, `name` and `club`. - create a `Player` `namedtuple` instance that has the `name` and `club` field set by the given arguments. - return the `Player` `namedtuple` instance you created. """ # you code starts here: Player = namedtuple('Player', ['name', 'club']) player = Player(name, club) return player print(task3('Noah', 'BadGirlsClub')) arg_deque = deque() arg_deque.append("Noah") arg_deque.append("Jop") arg_deque.append("Hop") arg_deque.append("Red") arg_deque.append("Goop") def task4(arg_deque: deque): """ - Manipulate the `arg_deque` in any order you preferred to achieve the following effect: -- remove last element in `deque` -- move the fist (left most) element to the end (right most) -- add an element `Zack`, a string, to the start (left) """ # your code goes here arg_deque.pop() # remove last item arg_deque.rotate(-1) # move the first item to end arg_deque.appendleft('Zack') task4(arg_deque)
true
768599312e43354921ef68be9e2ac25d98f03b69
MaxOvcharov/stepic_courses
/parser_csv_rss/login_validator.py
1,045
4.21875
4
""" Login validator """ import re def check_login(login): """ This function checks an login on the following conditions: 1) Check login using a regular expression; 2) Check len of login < 1 and login < 21; 3) Check the prohibited symbol in login; 4) Check login ends on latin letter or number; """ # Check len of login < 1 or login < 21 if (len(login) < 1) or (len(login) > 20): raise ValueError('Login len out of range (1-20)') # Check login using a regular expression res = re.match(r'^([a-zA-z0-9.-]+)$', login) if not res: raise ValueError("Bad syntax of entered login") # Check login ends on latin letter or number if login.endswith(".") or login.endswith("-"): raise ValueError("Login can not ends on '.' or '-'") return True if __name__ == '__main__': # Enter your login put_login = raw_input('Enter login here -> ') # Start checking login if check_login(put_login): print "This is correct login: ", put_login
true
a21d872ddaa4c65c18600112e2dfefe5f611a375
7558/GeekBrains
/time.py
460
4.3125
4
# 2. Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. seconds = int(input("Введите кол-во секунд: ")) minutes = seconds // 60 hours = minutes // 60 print("Время: %02d:%02d:%02d" % (hours, minutes % 60, seconds % 60))
false
ed4f48871da3f8540991cd346414a40950ea76a3
MohammedAbuMeizer/DI_Bootcamp
/Week_6/Day_4/Exercises XP/Exercise 12 Cinemax/Exercise 12 Cinemax.py
898
4.15625
4
age = input("enter your age please or exit: ") age = int(age) total = 0 while age != -1 : if age < 3 : total = total + 0 age = input("enter your age please or exit: ") age = int(age) elif age >= 3 and age <= 12 : total = total + 10 age = input("enter your age please or exit: ") age = int(age) elif age > 12 : total = total + 15 age = input("enter your age please or exit: ") age = int(age) print(total) age = input("enter your age please or -1: ") age = int(age) teen = [] while age != -1 : if age >=16 and age<=21 : print("you can see the movie") age = input("enter your age please or -1: ") age = int(age) teen .append(age) else : print("you cant see the movie") age = input("enter your age please or -1: ") age = int(age) print(teen)
false
5cb487213c686fb99dafa28ba059dfa438b79183
MohammedAbuMeizer/DI_Bootcamp
/Week_7/Day_2/Exercises XP #1/Exercise 2 What’s Your Favorite Book/Exercise 2 What’s Your Favorite Book .py
284
4.125
4
title = input("Enter a title of your favorite Book : ") def favorite_book(title="Alice in Wonderland"): print(f"One of my favorite books is {title}") while title == "" or title ==" ": print("You didnt type any title we will put our default") title = "Alice in Wonderland" favorite_book(title)
true
1c4d365c66a38cb35a2fee5fe6656d829888bc03
mwilso17/python_work
/files and exceptions/reading_file.py
508
4.34375
4
# Mike Wilson 22 June 2021 # This program reads the file learning_python.txt contained in this folder. filename = 'txt_files\learning_python.txt' print("--- Reading in the entire file:") with open(filename) as f: contents = f.read() print(contents) print("\n--- Looping over the lines in the file.") with open(filename) as f: for line in f: print(line.rstrip()) print("\n--- Storing the lines in a list:") with open(filename) as f: lines = f.readlines() for line in lines: print(line.rstrip())
true
77c0c93b87eacd40750c50ff1b4044ed9db38b6d
mwilso17/python_work
/OOP and classes/dice.py
1,093
4.46875
4
# Mike Wilson 22 June 2021 # This program simulates dice rolls and usues classes and methods from the # Python standard library from random import randint class Die: """Represents a die that can be rolled.""" def __init__(self, sides=6): """Initialize the die. 6 by default.""" self.sides = sides def roll_die(self): """Return a number between 1 and the number of sides.""" return randint(1, self.sides) # Make a 6 sided die and roll it 10 times. d6 = Die() results = [] for roll_num in range(10): result = d6.roll_die() results.append(result) print("\nThe 10 rolls of a 6 sided dice came up: ") print(results) # Make a 10 sided die and roll it 10 times. d10 = Die(sides=10) results = [] for roll_num in range(10): result = d10.roll_die() results.append(result) print("\nThe 10 rolls of a 10 sided dice came up: ") print(results) # Make a 20 sided die and roll it 10 times. d20 = Die(sides=20) results = [] for roll_num in range(10): result = d20.roll_die() results.append(result) print("\nThe 20 rolls of a 6 sided dice came up: ") print(results)
true
3bd1bc2752c36de661bea0628e1e544fa030d403
mwilso17/python_work
/functions/cars.py
412
4.25
4
# Mike Wilson 20 June 2021 # This program stores info about a car in a dictionary. def make_car(make, model, **other): """makes a dictionary for a car""" car_dictionary = { 'make': make.title(), 'model': model.title(), } for other, value in other.items(): car_dictionary[other] = value return car_dictionary my_car = make_car('honda', 'civic', color='grey', repairs='engine') print(my_car)
true
0e0f98ebf7b50fa048c7d6f384cf7a297ac897a9
mwilso17/python_work
/lists/lists_loops/slices/our_pizzas.py
871
4.46875
4
# Mike Wilson 8 June 2021 # This program slices from one list and adds it to another, while keeping # two seperate lists that operate independantly of one another. my_favorite_pizzas = ['pepperoni', 'deep dish', 'mushroom'] your_favorite_pizzas = my_favorite_pizzas[:] print("My favorite pizzas are: ") print(my_favorite_pizzas) print("\nYou like many of the same pizzas I do!") print("\nYour favorite pizzas are: ") print(your_favorite_pizzas) print("\n Let's add some more pizzas to our favorites.") my_favorite_pizzas.append('extra cheese') my_favorite_pizzas.append('salami') your_favorite_pizzas.append('Detroit style') your_favorite_pizzas.append('veggie') print(my_favorite_pizzas) print(your_favorite_pizzas) for pizza in my_favorite_pizzas: print(f"I really like {pizza} pizza!") for pizza in your_favorite_pizzas: print(f"You really like {pizza} pizza!")
true
2d452ea8ecfeedd2a5c64bf6c75ffc230358f58b
mwilso17/python_work
/user input and while loops/movie_tickets.py
590
4.15625
4
# Mike Wilson 15 June 2021 # This program takes user input for age then returns the price of their movie # ticket to them. prompt = "\nWhat is your age? " prompt += "\nEnter 'quit' when you are finished." while True: age = input(prompt) if age == 'quit': break age = int(age) if age < 3: print("Your ticket is free.") elif age < 12: print("Your ticket is $10.") elif age < 65: print("Your ticket is $15.") elif age < 400: print("You get a senior discount. Your ticket is $12.") elif age >= 400: print("Sorry, we don't let vampires into this theater.")
true
142c6b7728d282d6d2e1e60eddb6d50cb4193f12
mwilso17/python_work
/functions/messages.py
648
4.28125
4
# Mike Wilson 20 June 2021 # This program has a list of short messages and displays them. def show_messages(messages): """print messages in list""" for message in messages: print(message) def send_messages(messages, sent_messages): """print each message and move it to sent messages""" print("\nSending all messages") while messages: current_messages = messages.pop() print(current_messages) sent_messages.append(current_messages) messages = ['hey!', 'What\'s up?', ':)'] show_messages(messages) sent_messages = [] send_messages(messages[:], sent_messages) print("\nFinal lists:") print(messages) print(sent_messages)
true
a558286ad23fad033b1a2d61fd7d3e959723c13f
mwilso17/python_work
/user input and while loops/deli.py
841
4.5
4
# Mike Wilson 17 June 2021 # This program simulates a sandwich shop that takes sandwich orders # and moves them to a list of finished sandwiches. # list for sandwich orders sandwich_orders = ['club', 'ham and swiss', 'pastrami', 'turkey', 'veggie'] # empty list for finished sandwiches finished_sandwiches = [] # the following code lets customers know we are out of pastrami today # and removes those orders from the list. print("Sorry, but we are out of pastrami right now.") while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') # code to 'make' sandwiches. while sandwich_orders: current_sandwich = sandwich_orders.pop() print(f"I am making your {current_sandwich} sandwich now.") finished_sandwiches.append(current_sandwich) for sandwich in finished_sandwiches: print(f"Here is your {sandwich} sandwich.")
true
5fdff9be03e18e4ff1c7cc64cd210e32a82e3acf
mwilso17/python_work
/user input and while loops/dream_vacation.py
674
4.34375
4
# Mike Wilson 17 June 2021 # The following program polls users about their dream vacations. # 3 prompts to be used name_prompt = "\nWhat is your name? " vacation_prompt = "If you could vacation anywhere in the world, where would you go? " next_prompt = "\nWould someone else like to take the poll? (yes/no): " # empty dictionary to store responses in responses = {} while True: name = input(name_prompt) vacation = input(vacation_prompt) responses[name] = vacation repeat = input(next_prompt) if repeat != 'yes': break print("\n-------Results-------") for name, place in responses.items(): print(f"{name.title()} would like to vacation to {place.title()}.")
true
17537c25a434845c6e187f034b266b03648dacc4
Trice254/alx-higher_level_programming
/0x06-python-classes/5-square.py
1,413
4.53125
5
#!/usr/bin/python3 """ Module 5-square Defines class Square with private size and public area Can access and update size Can print to stdout the square using #'s """ class Square: """ class Square definition Args: size (int): size of a side in square Functions: __init__(self, size) size(self) size(self, value) area(self) print(self) """ def __init__(self, size=0): """ Initializes square Attributes: size (int): defaults to 0 if none; don't use __size to call setter """ self.size = size @property def size(self): """" Getter Return: size """ return self.__size @size.setter def size(self, value): """ Setter Args: value: sets size to value if int and >= 0 """ if type(value) is not int: raise TypeError("size must be an integer") elif value < 0: raise ValueError("size must be >= 0") else: self.__size = value def area(self): """ Calculates area of square Returns: area """ return (self.__size)**2 def my_print(self): """ Prints square with #'s """ print("\n".join(["#" * self.__size for rows in range(self.__size)]))
true
429d7655eb45e48f079bdbda71dc8226a0dba108
Trice254/alx-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
555
4.21875
4
#!/usr/bin/python3 """ Text Indention module """ def text_indentation(text): """ print text 2 new lines after each of these characters: ., ? and : Args: text (str): text Raise TypeError: when text is not str """ if type(text) is not str: raise TypeError("text must be a string") a = 0 while a < len(text): if text[a] in [':', '.', '?']: print(text[a]) print() a += 1 else: print(text[a], end='') a += 1
true
495df61d0c1e33a0a9f167d501c471fdad9e8a83
Trice254/alx-higher_level_programming
/0x06-python-classes/4-square.py
1,192
4.625
5
#!/usr/bin/python3 """ Module 4-square Defines class Square with private size and public area Can access and update size """ class Square: """ class Square definition Args: size (int): size of a side in square Functions: __init__(self, size) size(self) size(self, value) area(self) """ def __init__(self, size=0): """ Initializes square Attributes: size (int): defaults to 0 if none; don't use __size to call setter """ self.size = size @property def size(self): """" Getter Return: size """ return self.__size @size.setter def size(self, value): """ Setter Args: value: sets size to value, if int and >= 0 """ if type(value) is not int: raise TypeError("size must be an integer") elif value < 0: raise ValueError("size must be >= 0") else: self.__size = value def area(self): """ Calculates area of square Returns: area """ return (self.__size)**2
true
12852a2bc16c9fc29f21c49f2fee14258cd2dcc2
Trice254/alx-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
654
4.5
4
#!/usr/bin/python3 """ Square Printer Module """ def print_square(size): """ Print square using # Args: size (int) : Size of Square Raise TypeError: if size is not int ValueError: if size is less than 0 TypeError: if size is float and less than 0 Return: Printed Square """ if type(size) is float and size < 0: raise TypeError("size must be an integer") if type(size) is not int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") for x in range(size): print("#" * size)
true
9ec77aa854fa81a09b3007e3c8662f8c22c72cbe
ajjaysingh/Projects
/mybin/pre_versions/addword_v1.0.py
2,663
4.46875
4
#!/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 # File Name : addword.py # Description : It adds the provided word to my custom dictionary. The new words that I learn. # Author : Ajay # Date : 2016-05-03 # Python Version : 3 #================================================== import os import sys def instructions(): print("\n\t***Please Follow the prompts, If you want to enter multiple meanings seperate them using simicolon(;).") print("\n\t***You can add any additional information you want to add ") # move to directory containg the dictionary # IMPORTANT - while handling files always do this => first make a temp copy of file then proceed if try fails the you should restore the file os.chdir("/Users/chaser/Projects/") # print(os.system("ls")) try: temp_name = ".myDict_temp" #name of the temporary duplicate file os.system("cp "+ "myDict "+ temp_name) print(instructions()) # print("copied") # os.system("ls " + "-la") with open("myDict", 'a') as dictionary: #always use this because if opening of file fails the file will not get overwritten new_word = str(sys.argv[1]) meaning = input("\nEnter the meaning for the word " + new_word + ": ") #raw_input renamed to input, take input the m example = input("\nEnter some example for the word: ") count = 0 # count the total no of words already present with open("myDict", 'r') as read_file: # open the file just for reading the number of words already present, we can not read a file in append mode for line in read_file : if line[0:3] == ">>>" : # [0:3] is like [) count = count + 1 # the line is read as an array, [0:3] means 0,1,2 here 3 is not include if (len(line) > 4) and new_word.upper() == line[3:-1]: print("Word already present") exit(1) # on exit 1 it will go to except # print(count) dictionary.write(">>>\n") dictionary.write(str(count + 1) + ". " + new_word.upper() + "\n") dictionary.write("Meaning: " + meaning + '\n') dictionary.write("Example: " + example + '\n' + '\n') # os.system("rm "+ temp_name) #we need to remove the temp file whether try suceeds or fails except: files = os.listdir() if temp_name in files: os.system("cp " + temp_name + " myDict") print("try agian!") finally: # always executed whether try suceeds or not files = os.listdir() if temp_name in files: os.system("rm " + temp_name)
true
caec37b13d91ee25e2a4c8322d1d1f9035277521
Morgenrode/MIT_OCW
/ex3.py
213
4.125
4
'''Given a string containing comma-separated decimal numbers, print the sum of the numbers contained in the string.''' s = input('Enter numbers, separated by commas: ') print(sum(float(x) for x in s.split(',')))
true
fbbb1c4ec214fb01e299d4bbd3f44de9100966d6
oswalgarima/leetcode-daily
/arrays/max_prod_two_elements.py
1,334
4.21875
4
""" 1464. Maximum Product of Two Elements in an Array https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/ Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). Example: Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. """ # Runtime: 44ms class Solution: def maxProduct(self, nums: List[int]) -> int: # Thought proces: # We need to take note of the index that generated that highest maximum product of two elements in an array # max_prod = 0 # # Given that we must start from 0 # for i in range(0, len(nums) - 1): # for j in range(i + 1, len(nums)): # temp_prod = (nums[i] - 1) * (nums[j] - 1) # if temp_prod > max_prod: # max_prod = temp_prod # else: # continue # Given a more efficient way – the last two number will of a sorted array will always give the bigger prod nums.sort() return (nums[-1] - 1) * (nums[-2] - 1)
true
f0d0be61871f9357033bc8148e11e83edcfc28d0
oswalgarima/leetcode-daily
/arrays/max_prod_three_nums.py
681
4.125
4
""" 628. Maximum Product of Three Numbers https://leetcode.com/problems/maximum-product-of-three-numbers/ Given an integer array nums, find three numbers whose product is maximum and return the maximum product. Example: Input: nums = [1,2,3] Output: 6 Input: nums = [1,2,3,4] Output: 24 """ # Runtime: 252ms (73.64%) class Solution: def maximumProduct(self, nums: List[int]) -> int: nums.sort() incld_neg = 1 excld_neg = 1 w_neg_val = nums[:2] + [nums[-1]] pos_val = nums[-3:] for i in w_neg_val: incld_neg *= i for j in pos_val: excld_neg *= j return max(incld_neg, excld_neg)
true
914f699c06f95507eba2da62deaa44aaf25519ef
limbryan/sudoku_solver
/solver.py
2,292
4.1875
4
import numpy as np import matplotlib.pyplot as plt # Takes in a position in the board and outputs if it is possible or not to put the number n inside def possible(board,x,y,n): # checks the row for i in range(len(board[0])): # exits the function straightaway if the number n already exists in the row if board[x][i] == n: return False # checks the column for j in range(len(board[0])): if board[j][y] == n: return False # first determine which of the 9 major boxes the x-y position is in # it doest not matter where in box it is, becasue we haev to check the whole box # so we just have to determine which of the box it is in x_b = (x//3)*3 y_b = (y//3)*3 # check the same box for ib in range(3): for jb in range(3): # checking the entire box the x-y is in if board[x_b+ib][y_b+jb] == n: return False # if it passes all the rules return True return True def solve(board): for x in range(9): for y in range(9): if board[x][y] == 0: for n in range(1,10): res = possible(board,x,y,n) if res ==True: board[x][y] = n # further solve again - recursion # the recursion just means going deepre into a tree/node solve(board) # this leaves the option that going deeper into the tree did not work so it remains empty as the previous branch was a wrong move board[x][y] = 0 #NEEDED return board print("Solved") print(np.matrix(board)) #input("More") #initalise the sudoku board as a list board = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] print(board) #just for viewing purposes - we are doing this sovler with lists only though we can do it with numpy arrays as well board_np = np.matrix(board) print(board_np) # this is the main function solve(board)
true
e2c613f1f0b1a69a554fb52d7f63b7a36a395439
DavidErroll/Euler-Problems
/Problem_14.py
1,570
4.1875
4
# The following iterative sequence is defined for the set of positive integers: # n → n/2 (n is even) # n → 3n + 1 (n is odd) # Using the rule above and starting with 13, we generate the following sequence: # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # Which starting number, under one million, produces the longest chain? # NOTE: Once the chain starts the terms are allowed to go above one million. def collatz_chain_length(start_point): if start_point < 2: x = 2 else: x = start_point chain_length = 1 limit = 0 while x != 1 and limit < 1000000: if x % 2: x = 3 * x + 1 chain_length += 1 limit += 1 else: x = x / 2 chain_length += 1 limit += 1 return(chain_length) def max_length(max_value): current_max_length = 1 max_iteration = 1 for i in range(max_value + 1): test_iteration_length = collatz_chain_length(i) if test_iteration_length >= current_max_length: max_iteration = i current_max_length = test_iteration_length else: pass return(max_iteration, current_max_length) def interface(): max_val = int(input("Maximum Collatz chain value = ")) print(max_length(max_val)) def main(): interface() main()
true
de6fa700d107e662dc8fcf8b99e11cd94df60e80
CODEVELOPER1/PYTHON-FOLDER
/SECRECT_WORD_GAME.py
566
4.28125
4
#Secert Word Game with loops secert_word = "giraffe" #secert word guess = "" #stores user response guess_count = 0 guess_limit = 3 out_of_guesses = False while guess != secert_word and not(out_of_guesses): if guess_count < guess_limit: guess = input("Enter Secert Word Guess. You Only have 3 tries, Choose Wisely: ") guess_count += 1 else: out_of_guesses = True if out_of_guesses: print('Nice Try, but you didn\'t succeed, you ran out of guesses. Thanks for Playing! Good-Bye') else: print("You got the Secert Word")
true
4ed6dd63fd3eccf0ffebcc101885dce17354a61c
mmrubayet/python_scripts
/codecademy_problems/Wilderness_Escape.py
2,805
4.3125
4
print("Once upon a time . . .") ###### # TREENODE CLASS ###### class TreeNode: def __init__(self, story_piece): self.story_piece = story_piece self.choices = [] def add_child(self, node): self.choices.append(node) def traverse(self): story_node = self # assign story_node to self print(story_node.story_piece) # print out story_node's story_piece while story_node.choices != []: # while story_node has choices: choice = int(input("Enter 1 or 2 to continue the story: ")) # get the user's choice using input() if not choice in [1, 2]: # if the choice is invalid print("Invalid Choice! Please enter 1 or 2: ") # tell the user else: # if the choice is valid chosen_index = choice - 1 chosen_child = story_node.choices[chosen_index] print(chosen_child.story_piece) story_node = chosen_child # set choice as the new story_node ###### # VARIABLES FOR TREE ###### story = \ """ You are in a forest clearing. There is a path to the left. A bear emerges from the trees and roars! Do you: 1 ) Roar back! 2 ) Run to the left... """ story_root = TreeNode(story) story_a = \ """ The bear is startled and runs away. Do you: 1 ) Shout 'Sorry bear!' 2 ) Yell 'Hooray!' """ choice_a = TreeNode(story_a) story_b = \ """ You come across a clearing full of flowers. The bear follows you and asks 'what gives?' Do you: 1 ) Gasp 'A talking bear!' 2 ) Explain that the bear scared you. """ choice_b = TreeNode(story_b) story_a_1 = \ """ The bear returns and tells you it's been a rough week. After making peace with a talking bear, he shows you the way out of the forest. YOU HAVE ESCAPED THE WILDERNESS. """ choice_a_1 = TreeNode(story_a_1) story_a_2 = \ """ The bear returns and tells you that bullying is not okay before leaving you alone in the wilderness. YOU REMAIN LOST. """ choice_a_2 = TreeNode(story_a_2) story_b_1 = \ """ The bear is unamused. After smelling the flowers, it turns around and leaves you alone. YOU REMAIN LOST. """ choice_b_1 = TreeNode(story_b_1) story_b_2 = \ """ The bear understands and apologizes for startling you. Your new friend shows you a path leading out of the forest. YOU HAVE ESCAPED THE WILDERNESS. """ choice_b_2 = TreeNode(story_b_2) story_root.add_child(choice_a) story_root.add_child(choice_b) choice_a.add_child(choice_a_1) choice_a.add_child(choice_a_2) choice_b.add_child(choice_b_1) choice_b.add_child(choice_b_2) user_choice = input("What is your name? \n_> ") print(f"\nWelcome {user_choice}!") ###### # TESTING AREA ###### story_root.traverse()
true
9417c401c7b1c7d47b79b381d0aaf82162266b18
mmrubayet/python_scripts
/codecademy_problems/Sorting Algorithms with python/bubble_sort.py
310
4.15625
4
from swap import * def bubble_sort(arr): for el in arr: for index in range(len(arr)-1): if arr[index] > arr[index + 1]: swap(arr, index, index + 1) ##### test statements nums = [5, 2, 9, 1, 5, 6] print("Pre-Sort: {0}".format(nums)) bubble_sort(nums) print("Post-Sort: {0}".format(nums))
true
3d39fe527f861f009c8d8817d5355c12014555df
uniinu1/python_study
/python_ch2.py
586
4.125
4
# 출력하기 print("- 출력하기") print(10) print(20, 10) # c언어와는 다른 숫자 출력(숫자 형식 생각하지 않아도 됨) print("- 다른 자료형의 숫자 출력하기") a = 10 b = 10.5 print(a, b) # 다양한 자료형 출력 print("- 다양한 자료형 출력") a = "Hello" b = "Goorm!" c = "10" # 문자열 d = 10 # 숫자 e = b result = a + b d = 5 # result = a + d 불가능 print(a, b, c, d, e, result) # 덧셈실습 정답 print("- 덧셈") num1, num2 = 3, 10 result = num1 + num2 print(num1, "+", num2, "=", result)
false
45905e00ddeb09731899b3fb4482103e66e695d4
blakeskrable/First-Project
/First.Project.py
248
4.21875
4
number=int(input("Guess a number between 1-10: ")) while number != 10: print("Wrong! Guess Again!") number=int(input("Enter a new number: ")) if number == 10: print("Congratulations! Good Guess! You Have Completed The Program!")
true
82b96585eba498023c2b5c9bda0017f475f3fee6
kaloyandenev/Python-learning
/Shopping List.py
828
4.15625
4
initial_list = input().split("!") command = input() while not command == "Go Shopping!": command = command.split() action = command[0] product_one = command[1] if action == "Urgent": if product_one not in initial_list: initial_list.insert(0, product_one) elif action == "Unnecessary": if product_one in initial_list: initial_list.remove(product_one) elif action == "Correct": product_two = command[2] if product_one in initial_list: index = initial_list.index(product_one) initial_list[index] = product_two elif action == "Rearrange": if product_one in initial_list: initial_list.remove(product_one) initial_list.append(product_one) command = input() print(", ".join(initial_list))
false
491bbdf5f6977a3b4878d965382d242ec432059f
kaloyandenev/Python-learning
/Smallest of Three Numbers.py
257
4.125
4
def find_smallest_number(n1, n2, n3): list_of_numbers = [n1, n2, n3] min_num = min(list_of_numbers) return min_num num_one = int(input()) num_two = int(input()) num_three = int(input()) print(find_smallest_number(num_one, num_two, num_three))
false
0102e2f8ebaab1d92f6a5fa7c2ffc2d134fd96f1
ashilp/Pleth_Test
/pleth_2.py
1,082
4.125
4
import os def read_path(path): ''' Function to list out directories, subdirectories, files with proper indentation ''' #indent according to the level of the directory level = path.count("\\") print("\n************Output************\n") if not os.path.exists(path): print("Error: Path does not exist") return for root, dirs, files in os.walk(path): #for indentation of directory, sub-directory, files space = " "*(root.count("\\")-level) if (os.path.isdir(root)): print(space+"/"+os.path.basename(root)) for f in files: print (space+" "+f) print("\n******************************\n") if __name__=="__main__": path = input("\nEnter full path of the directory: ") read_path(path) ''' Test Cases Verified: - Tested invalid or non existent paths - Tested for valid paths with recursive sub directories and files - Tests for empty directory - Tested for directory names containing spaces - Tested for soft-links or shortcuts '''
true
75cb6dc8589bfb41f161f89bbd4d3849d2ecdc3d
jcohenp/DI_Exercises
/W4/D2/normal/ex_6.py
1,739
4.5625
5
# A movie theater charges different ticket prices depending on a person’s age. # if a person is under the age of 3, the ticket is free # if they are between 3 and 12, the ticket is $10 # and if they are over age 12, the ticket is $15 . # Apply it to a family, ask every member of the family their age, and at the end of the loop, tell them the cost of the tickets for the whole family. # #get number of group members: size_group = int(input("How many tickets would you like to purchase\n")) group_member_age = [] # group_member_age_input = "" total_cost = 0 while size_group > 0: if size_group == None: continue else: group_member_age_input = int(input("What is your age?\n")) if group_member_age_input == "": error = -1 error_msg = "no input" print(f"Error {error}, {error_msg}\n") continue else: group_member_age.append(group_member_age_input) size_group -=1 if group_member_age_input >= 3 and group_member_age_input <= 12: total_cost += 10 elif group_member_age_input > 12: total_cost += 15 print (f"Total cost: {total_cost}\n\n") # A group of teenagers is coming to your movie theater and want to see a movie that is restricted for people between 16 and 21 years old. # Write a program that ask every user their age, and then tell them which one can see the movie. # Tip: Try to add the allowed ones to a list. for group_member in group_member_age: if group_member > 21: print(f"{group_member},years old you can watch the movie") else: print(f"{group_member},years old sorry kid - too young!")
true
69a0eadad9f12debc8722949571a4ec9adca922f
jcohenp/DI_Exercises
/W4/D2/normal/ex_3 2.py
695
4.40625
4
# Recap – What is a float? What is the difference between an integer and a float? # Earlier, we tried to create a sequence of floats. Did it work? # Can you think of another way of generating a sequence of floats? # Create a list containing the sequence 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 without hard-coding the sequence. # An integer is a natural number, a float is a decimal # yes you can create a sequence of floats in a list for example list_of_floats = [1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5] print(list_of_floats) # Create a list containing the sequence 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 without hard-coding the sequence. set_of_floats = {1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5} print(set_of_floats)
true
4d7f787e45e409ae15a01e88740f8acba4d43c45
jcohenp/DI_Exercises
/W4/D1/ninja/ex_1/ex_2.py
205
4.25
4
# Given two variables a and b that you need to define, make a program that print Hello World only if a is greater than b. a = 4 b = 6 if a > b: print("Hello World") else: print("a is too small")
true
a44bfcc01ea351adf209f4642c6dd8510410f435
ramyasinduri5110/Python
/strings.py
942
4.34375
4
#Strings in python #how we can write strings in python str1_singlequote='Hello World!' str2_doublequotes="The string declaration in double quotes" str_block=''' this is the biggest block of code with multiple lines of text ''' #type gives you the information about the data type print(type(" Hey! there I am using python :D")) print('The string written with single quotes : '+str1_singlequote) print('The string written with double quotes : '+str2_doublequotes) print('The string block : '+str_block) #string concatenation #string concatenation only works with strings first_name='ramya' last_name='kondepudy' full_name=first_name+''+last_name print('full name after concatenation: '+full_name) #Type Conversion print('converting an integer value to a string ') print(type(str(100))) b=str(100) c=int(b) d=type(c) print(d) #Escape Sequences #t adds the tab #n adds the new line weather="it's \"kind of\" sunny" print(weather)
true
562b8a5b2b3d0b2dfedc2ba890c3adbd22a57bf1
neelpopat242/audio_and_image_compression
/app/utils/images/linalg/utils.py
2,937
4.375
4
import math def print_matrix(matrix): """ Function to print a matrix """ for row in matrix: for col in row: print("%.3f" % col, end=" ") print() def rows(matrix): """ Returns the no. of rows of a matrix """ if type(matrix) != list: return 1 return len(matrix) def cols(matrix): """ Returns the no. of columns of a matrix """ if type(matrix[0]) != list: return 1 return len(matrix[0]) def eye(size): """ Returns an identity matrix """ mat = list() for r in range(size): row = list() for c in range(size): if r == c: row.append(1) else: row.append(0) mat.append(row) return mat def pivot_index(row): """ Returns the index of pivot in a row """ counter = 0 for element in row: if element != float(0): return counter counter += 1 return counter def pivot_value(row): """ Returns the value of pivot in a row """ for element in row: if element > math.exp(-8): return element return 0 def swap(matrix, index_1, index_2): """ Function to swap two rows """ x = matrix[index_1] matrix[index_1] = matrix[index_2] matrix[index_2] = x def transpose(matrix): """ Returns the transpose of a matrix """ transpose_matrix = list() for i in range(cols(matrix)): row = list() for j in range(rows(matrix)): row.append(matrix[j][i]) transpose_matrix.append(row) return transpose_matrix def mat_multiply(a, b): """ Function to multiply two matrices """ c = [[0 for i in range(cols(b))] for j in range(rows(a))] for i in range(rows(a)): for j in range(cols(b)): for k in range(rows(b)): c[i][j] += a[i][k] * b[k][j] return c def mat_splice(matrix, r, c): """ Function which returns a matrix with the first r rows and first c columns of the original matrix """ result = list() for i in range(r): row = matrix[i] result.append(row[:c]) return result def to_int(matrix): """ Funciton to convert the eact element of the matrix to int """ for row in range(rows(matrix)): for col in range(cols(matrix)): for j in range(3): matrix[row][col][j] = int(matrix[row][col][j]) return matrix def clip(matrix): """ Function to clip each element to the range float[0, 1] """ for row in range(rows(matrix)): for col in range(cols(matrix)): for j in range(3): if matrix[row][col][j] > 1: matrix[row][col][j] = 1 if matrix[row][col][j] < 0: matrix[row][col][j] = 0 return matrix
true
b6667c81ac17100692ae20ee76abe20ac9bc9d29
NaveenLDeevi/Coursera-Python-Data-Structures
/Week#3_ProgrammingAssg_part#1.py
463
4.71875
5
# Coursera- Data structures course - Week#3. #7.1 Write a program that prompts for a file name, then opens that file and reads #through the file, and print the contents of the file in upper case. Use the file #words.txt to produce the output below.You can download the sample data at #http://www.pythonlearn.com/code/words.txt #!/usr/bin/env python input = raw_input('Enter the file name:') int = open(input,'r') for line in int: print (line.upper()).strip()
true
d4eb39c121483d83e135c3469c31c57ce457a239
tanmay2298/The-Python-Mega-Course-Udemy
/Tkinter GUI/script1.py
746
4.4375
4
from tkinter import * # Imports everything fromt the tkinter library # Tkinter program is mainly made of two things -- Window and Widgets window = Tk() # Creates an empty window def km_to_miles(): print(e1_value.get()) miles = float(e1_value.get())*1.6 t1.insert(END, miles) b1 = Button(window, text = "Execute", command = km_to_miles) # NOT km_to_miles() b1.grid(row = 0, column = 0) e1_value = StringVar() e1 = Entry(window, textvariable = e1_value) e1.grid(row = 0, column = 1) t1 = Text(window, height = 1, width = 20) t1.grid(row = 0, column = 2) window.mainloop() # Everything between the window = tk() line and this goes in the main window # Also this line allows us to use the 'cross' or 'X' button to close the window
true
4b62175aefa73723e3b4a17ec1783c938df829fd
mishuvalova/Paradigm-homework
/string_task.py
1,450
4.375
4
# Given a string, if its length is at least 3, # add 'ing' to its end. # Unless it already ends in 'ing', in which case # add 'ly' instead. # If the string length is less than 3, leave it unchanged. # Return the resulting string. # # Example input: 'read' # Example output: 'reading' def verbing(s): length = len(s) if length >= 3: if s[-3:] == 'ing': return s +'ly' else: return s + 'ing' # Given a string, find the first appearance of the # substring 'not' and 'bad'. If the 'bad' follows # the 'not', replace the whole 'not'...'bad' substring # with 'good'. # Return the resulting string. # # Example input: 'This dinner is not that bad!' # Example output: 'This dinner is good!' def not_bad(s): nn = s.find('not') nb = s.find('bad') if nn != -1 and nb != -1 and nb > nn: s = s[:nn] + 'good' + s[nb +3:] return s # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If 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 # # Example input: 'abcd', 'xy' # Example output: 'abxcdy' def front_back(a, b): l1 = len(a) l2 = len(b) i1 = l1//2 - l1%2 i2 = l2//2 - l2%2 a1 = a[0:i1] a2 = a[i1:] b1 = b[0:i2] b2 = b[i2:] return a1 + b1 + a2 + b2
true
a689db24d6b8dd07f061f89f3d729792dfce3096
HumpbackWhaIe/python_programming
/mycode/3_string/yesterday_count.py
592
4.125
4
# yesterday.txt 파일을 열기 """ open mode r : read, w : write rb : read binary, wb : write binary """ def file_read(file_name): with open(file_name, "r") as file: lyric = file.read() return lyric read = file_read("yesterday.txt") print(read) num_of_yesterday = read.upper().count("YESTERDAY") print(f'Number of a word "YESTERDAY" {num_of_yesterday}') num_of_yesterday = read.count("Yesterday") print(f'Number of a word "Yesterday" {num_of_yesterday}') num_of_yesterday = read.lower().count("yesterday") print(f'Number of a word "yesterday" {num_of_yesterday}')
false
df9a29f6a9e12dffe386f1bd306fd0a23aad1e56
elentz/1st-Semester-AP
/dictproblems1.py
1,074
4.5625
5
1. Write a Python script to add key to a dictionary. Sample Dictionary : {0: 10, 1: 20} Expected Result : {0: 10, 1: 20, 2: 30} 2. Write a Python script to concatenate following dictionaries to create a new one. Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} 3. Write a Python script to check if a given key already exists in a dictionary. 4. Write a Python program to iterate over dictionaries using for loops. 5. Write a Python script to sort (ascending and descending) a dictionary by value. 6. Write a Python script to generate and print a dictionary that contains number (between 1 and n) in the form (x, x*x). Sample Dictionary ( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 7. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. Sample Dictionary {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
true
305e920c490417d773339b1f73aae7f640d31d07
SiegfredLorelle/pld-assignment2
/Assignment2_Program1.py
402
4.46875
4
"""Create a program that will ask for name, age and address. Display those details in the following format. Hi, my name is _____. I am ____ years old and I live in _____ . """ name = input("Please enter your name: ") age = int(input("Please enter your age: ")) address = input("Please enter you address: ") print (f"Hi, my name is {name}. I am {age} years old and I live in {address}. ")
true
6e04f1bead3cb9a26e25b4b5739db6a66631fa90
spoorthi198/Python_QA
/practicing.py
1,139
4.15625
4
'''print("*" * 10) birth_year = int(input("enter the birth year")) age = 2020 - birth_year print(age) ''' #logical operator '''has_high_income = True has_high_credit = False if (has_high_income and has_high_credit): print("Eligible for loan") else: print("not eligible for true")''' ''' temerature = 45 if temerature > 30: print("It's a hot day") print("drink plenty of water") elif temerature > 20 and temerature <30: print("its a nice day") elif temerature < 10: print("its a cold day") else: print("Good day") ''' # calculating weight in kg and lbs ''' weight = int(input("enter the weight: ->")) unit = input("(K)g and (l)bs").upper() if unit == "K": converted = weight/0.45 print("weight in kg is" + str(converted)) elif unit == "L": converted = weight * 0.45 print("weight in lbs is" + str(converted)) ''' # while example ''' i = 1 while(i<=10): print(i * '*') i +=1 ''' # list ''' names = ["jhon","spoorthi","red","jnana","Raj"] print(names[0:4]) names.append("keerti") names.insert(3,"test") print("Raj" in names) ''' number = range(5,10,2) for i in number: print(i)
false
cd773903e3d604d872f5b50d0bbbbe0c6e273a43
MuddCreates/FlexTracker
/flexBackend.py
488
4.125
4
import math def getPriceD(fileName): """ The function reads a text file of the price and name of each possible thing to buy. It stores each thing as in a dictionary win form {price:name of thing} It then returns the dictionary """ priceD = {} file = open(fileName,"r") for line in file: data = line.split() priceD[float(data[0])] = data[1] return priceD def sortPrices(priceD): ''' This function '''
true
8111d916e77179b6a49bc9b9cc137b86fb56446d
ravihansa/sorting-algorithms-python
/Sorting Codes/bubble sort.py
566
4.125
4
# Sorts a sequence in ascending order using the bubble sort algorithm. def bubbleSort( theSeq ): n = len( theSeq ) # Perform n-1 bubble operations on the sequence for i in range( 1,n ) : #print(i) # Bubble the largest item to the end. for j in range(0, n-i) : if theSeq[j] > theSeq[j + 1] : tmp = theSeq[j] theSeq[j] = theSeq[j + 1] theSeq[j + 1] = tmp #print(theSeq) print(theSeq) a=[1,5,4,8,0,12,35,43,67,9,81,11] bubbleSort( a )
false
e7f3cb0d77610d3e477e83080408db869b6769e6
jannekai/project-euler
/037.py
1,750
4.125
4
import time import math start = time.time() def primes(): primes = [] n = 2 yield n n = 3 while True: # Return the found prime and append it to the primes list primes.append(n) yield n # Find the next natural number which is not divisible by any of # the previously found prime. while True: # The next number after prime is always even, so we can # optimize by not checking the even values. n += 2 h = int(math.sqrt(n)) + 1 isPrime = True for i in primes: if n % i == 0: isPrime = False break if i > h: break # If the value was not divisible by any of the previously # found primes, break the inner loop if isPrime: break def isTruncatable(x): global p t = [x] c = 0 n = x / 10 while n > 0: if n not in p: return False t.append(n) n = n / 10 c += 1 c = 10**c n = x - (x/c*c) while c > 1: if n not in p: return False t.append(n) c = c / 10 n = n - (n/c*c) print t return True gen = primes() s = 0 c = 0 p = set() while c < 11: x = gen.next() p.add(x) if x > 7 and isTruncatable(x): print "Found %d" % x c += 1 s += x print "Sum is %d, total of %d primes were calculated" % (s, len(p)) end = time.time() - start print "Total time was " + str(end)+ " seconds"
true
f66e58e76e650ee975c0aad92815373cc6a33274
DenisRomashov/Stepic
/Python/Programming in Python(Introduction) /PyCharm/3.6/TASKS/Counter.py
1,231
4.15625
4
#Подсчет количества строк, слов и букв в текстовом файле ''' Для того, чтобы определить количество слов используется следующий алгоритм: 1)Устанавливаем флаг в позицию "вне слова". 2)Как только очередной символ не пробел и флаг имеет значение "вне слова", значит мы вошли в новое слово. Увеличиваем счетчик слов. 3)Если символ не пробел, но флаг в значении "внутри слова", то счетчик увеличивать не надо. 4)Как только встречается пробел переставляем флаг на "вне слова". ''' import sys fname = sys.argv[1] lines = 0 words = 0 letters = 0 for line in open(fname): lines += 1 letters += len(line) pos = 'out' for letter in line: if letter != ' ' and pos == 'out': words += 1 pos = 'in' elif letter == ' ': pos = 'out' print("Lines:", lines) print("Words:", words) print("Letters:", letters)
false
9218ed1c4e3314d3838e36f5516e5880d3e81b5b
vernikagupta/Opencv-code
/Rotation.py
1,023
4.28125
4
'''Rotation of an image means rotating through an angle and we normally rotate the image by keeping the center. so, first we will calculate center of an image and then we will rotate through given angle. We can rotate by taking any point on image, more preferably center''' from __future__ import print_function import cv2 import argparse def show_img(img): cv2.imshow("canvas",img) cv2.waitKey(0) return ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "path to image") args = vars(ap.parse_args()) print(args) load_image = cv2.imread(args["image"]) #show_img(load_image) h,w = load_image.shape[:2] print(h,w) Center = (h//2,w//2) print(Center) M = cv2.getRotationMatrix2D(Center, 45, 1.0) rotated = cv2.warpAffine(load_image, M, (w,h)) show_img(rotated) '''45 degree is the angle we are rotating the image and 1.0 is the scale 1.0 means same size of original. 2.0 means double the size, 0.5 means half the soze of image'''
true
ec98c1efd4562a910b4b98129e5cf9aad5b8d7d6
ksharma377/machine-learning
/univariate-linear-regression/src/main.py
1,714
4.15625
4
""" This is the main file which builds the univariate linear regression model. Data filename: "data.csv" Data path: "../data/" The model trains on the above data and outputs the parameters and the accuracy. The number of training cycles is controlled by the variable "epochs". Input: x Parameters: w0, w1 Output: y Heuristic: h(x) = w0 + (w1 * x) Number of training examples: m Batch size: b Learning rate: r Cost function = MSE (Mean squared error) C(w0, w1) = (1 / 2m) sigma((h(x) - y)^2) Optimizer algorithm: Batch Gradient Descent """ import random import numpy as np import pandas as pd from sklearn.model_selection import train_test_split """ Initializes the parameters """ def initialize_parameters(): global w0, w1, r, epochs w0 = random.random() w1 = random.random() r = 0.1 epochs = 100 """ Reads the data in csv format and splits into training and testing data (80-20) """ def read_data(): df = pd.read_csv('../data/data.csv') global train_data, test_data train_data, test_data = train_test_split(df, test_size = 0.2) def calculate_mse(batch): m = len(batch) error = 0 for row in batch.itertuples(): x, y = row.x, row.y h = w0 + (w1 * x) error += (h - y) ** 2 return error / (2 * m) """ Trains the linear regression model. 1. Sample a batch of fixed size. 2. Calculate the error for this batch. 3. Update the parameters using Gradient Descent. 4. Repeat for epochs. """ def train_model(): batch_size = 1000 for epoch in range(epochs): batch = train_data.sample(n = batch_size) error = calculate_mse(batch) print("Epoch: {}, Error: {}".format(epoch, error)) if __name__ == "__main__": read_data() initialize_parameters() train_model()
true
99181758a8f51a4ae6fc12805cd465feb1a611f6
gaoruiqing123/proj12
/zhoukao01/five.py
1,322
4.1875
4
# 5.实现以下功能:(30分) # s='The column above illustrates apparently' \ # ' the polularity of people ' \ # 'doing exercise in a certain year ' \ # 'from 2013 to 2018.Based upon the data,' \ # 'we can see that python is wonderful. ' \ # 'python is wonderful. Python ' \ # 对这段文字中的单词进行数字统计,并且进行个数升序 # (能够生成字典8分,字典中统计数正确7分,进行排序8分,最后实现结果7分) import random s='The column above illustrates apparently' \ ' the polularity of people ' \ 'doing exercise in a certain year ' \ 'from 2013 to 2018.Based upon the data,' \ 'we can see that python is wonderful. ' \ 'python is wonderful. Python' #输出元字符串 print("原来字符串:",s) #切割 s = s.split(" ") print("切割后的字符串:",s) #定义空字典 dic = {} for i in s: key = dic.get(i) #判断数量 if(key==None): dic[i]=1 else: dic[i]+=1 #打印字典 print("统计完之后的:",dic) #定义一个排序的空字典 dic1 = {} #单词个数排序 sv = list(dic.values()) sv.sort() print("值:",sv) #去除相同次数 sv = set(sv) sv = list(sv) #实现升序 for i in sv: for j in dic: if(dic[j]==i): dic1[j]=i #排序完成 print("排序后的:",dic1)
false
e293adefe3f2b90d6e447422070832b53d34685d
nishapagare97/pythone-ideal-programs
/temperature program.py
653
4.28125
4
# question no 2 # author - nisha pagare #date - 10-0-2021 # program should convert the temperature to the other unit. The conversions are # f= (9/5c+32) # c= (5/9f-32) temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ") degree = int(temp[:-1]) i_convention = temp[-1] if i_convention.upper() == "C": result = int(round((9 * degree) / 5 + 32)) o_convention = "Fahrenheit" elif i_convention.upper() == "F": result = int(round((degree - 32) * 5 / 9)) o_convention = "Celsius" else: print("Input proper convention.") quit() print("The temperature in", o_convention, "is", result, "degrees.")
true
19da3645aa84ba2c7cd66dda81d5dad120253115
stanmark2088/allmypythonfiles
/fahrenheit_to_c.py
954
4.59375
5
# Write a Python program to convert a temperature given in degrees Fahrenheit # to its equivalent in degrees Celsius. You can assume that T_c = (5/9) x (T_f - 32), # where T_c is the temperature in °C and T_f is the temperature in °F. Your program # should ask the user for an input value, and print the output. The input and output # values should be floating-point numbers. # my version print("\nWelcome to the fahrenheit to celsius calculator!\n") name = input("Please tell us your name: ") print("\nHello " + str(name) + "!") fahrenheit_temperature = float( input("\nPlease enter Fahrenheit temperature: ")) print("\nThe temperature in Celsius is:") celsius_temperature = (5 / 9) * (fahrenheit_temperature - 32) print(celsius_temperature) print(("\nThank you for using our calculator ") + str(name) + "!") # their version T_f = float(input("Please enter a temperature in °F: ")) T_c = (5/9) * (T_f - 32) print("%g°F = %g°C" % (T_f, T_c))
true
932d7741c60da5351cdb12f7ac0ce554232d9490
CptnReef/Frequency-Counting-with-a-Hash-Table
/HashTable.py
2,690
4.375
4
from LinkedList import LinkedList class HashTable: def __init__(self, size): self.size = size self.arr = self.create_arr(size) # 1️⃣ TODO: Complete the create_arr method. # Each element of the hash table (arr) is a linked list. # This method creates an array (list) of a given size and populates each of its elements with a LinkedList object. def create_arr(self, size): # creates array for linked list arr = [] # I need every linked list to append to the array for i in range(size): #creating new linked list new_link = LinkedList() #adding it to the array arr.append(new_link) return arr # 2️⃣ TODO: Create your own hash function. # Hash functions are a function that turns each of these keys into an index value that we can use to decide where in our list each key:value pair should be stored. def hash_func(self, key): # 1. Get the first letter of the key and lower case it first_letter = key[0].lower() #"[a]pple" # 2. Calculate the distance from letter a distance_from_a = ord(first_letter) - ord('a') # 3. Mod it to make sure it is in range index = distance_from_a % self.size # returns index return index # 3️⃣ TODO: Complete the insert method. # Should insert a key value pair into the hash table, where the key is the word and the value is a counter for the number of times the word appeared. When inserting a new word in the hash table, be sure to check if there is a Node with the same key in the table already. def insert(self, key, value): # Check link_list is empty or not. index = self.hash_func(key) self.linked_ls = self.arr[index] current = self.linked_ls.head # Going through the Hash Table for an empty node to assign key/value while current != None: # add if current node and key is True if current.data[0] == key: current.data[1] += value return # goes to the next node current = current.next # After Checking through Hash Table and linked list is empty self.linked_ls.append([key, value]) # 4️⃣ TODO: Complete the print_key_values method. # Traverse through the every Linked List in the table and print the key value pairs. # For example: # a: 1 # again: 1 # and: 1 # blooms: 1 # erase: 2 def print_key_values(self): #Check all linked lists in the hashtable for self.linked_ls in self.arr: current = self.linked_ls.head while current != None: if current.data: print(f'({current.data[0]}: {current.data[1]}') current = current.next
true
97c0335ee71a8d46a3dbbb5ddbd2e3b36bbada6b
colingillette/number-string-puzzles
/interface.py
2,960
4.15625
4
# List Reader # Input: List # Output: none, but will print list to console one line at a time def list_reader(x): for i in range(len(x)): print(x[i]) # Fibonacci Sequence # Input: Number in return series # Output: List in series def fib(x): if x < 1: return False elif x == 1: return [0] elif x == 2: return [0, 1] seq = [0, 1] for i in range(2, x): seq.append(seq[i-1] + seq[i-2]) return seq # FizzBuzz # Input: Number to generate fizzbuzz to # Output: None. Prints to console directly def fizz_buzz(x): fb = lambda n, m : n % m for i in range(x + 1): if fb(i, 15) == 0: print("FizzBuzz") elif fb(i, 5) == 0: print("Buzz") elif fb(i, 3) == 0: print("Fizz") else: print(i) # Palendrome # Input: A single word as string # Output: Boolean representing whether or not the word is a palendrome def palendrome(word): reverse = word[::-1] if reverse == word: return True else: return False # Word Count # Input: a string # Output: Number of words in string def word_count(text): count = 1 for c in text: if c == ' ': count += 1 return count # INPUT FUNCTIONS # Get Help # Lists all commands that are available for the user def get_help(): commands = { 'fizzbuzz' : 'Initiate the fizz buzz module', 'fizz' : 'Initiate the fizz buzz module. Alias for fizzbuzz', 'help' : 'Print off a list of commands', 'h' : 'Print off a list of commands. Alias for help', 'quit' : 'Terminates the program', 'q' : 'Terminates the program. Alias for quit', 'fibonacci' : 'Initate the fibonacci sequence module', 'fib' : 'Initate the fibonacci sequence module. Alias for fibonacci' } print() for key in commands: print(key + ': ' + commands[key]) print() # Process Input # Input: string from user # Output: Boolean. Will always be true unless user types 'quit' or 'q' def process_input(text): status = True text = text.lower() if text == 'quit' or text == 'q': print('Exiting program...') status = False elif text =='fizz' or text == 'fizzbuzz': fizz_buzz(int(input('Enter the number you would like to go to: '))) elif text == 'help': get_help() elif text == 'fib' or text == 'fibonacci': list_reader(fib(int(input('How many numbers would you like to generate: ')))) else: print('Please input a valid command. Type \"help\" if you need a list of commands.') return status # Computer # A function that handles input from the user def computer(): print() print("For a list of commands, please type \"help\"") print() live = True while (live): task = str(input('Please enter a command: ')) live = process_input(task) # MAIN BODY computer()
true
e29ef9d89303a36e43c0853591d8e596a1321984
rcadia/notesPython
/More Fuctions.py
457
4.21875
4
# # Tutorial - 15 # More Functions # # Ross Alejandro A. Bendal # Tuesday June 18 2013 - 5:18PM # # say = ['hey','now','brown'] print say.index('brown') # Search for index that will match in the text parameter say.insert(2,'show') # Inserts a new value. (Index.'string') print say say.pop(2) # Removes a value in index. Returns the value print say say.remove('brown') # Removes the string on an index completely. print say say.reverse() # Reverse the indexes. print say
true
ab4b30dcc2f00fdd64e320336bf731680fc8a646
Kenn3Th/DATA3750
/Kinematics/test.py
1,251
4.25
4
""" Handles user input from the terminal and test if it can connect with the Kinematics_class.py Also tests for forward and inverse kinematics """ import numpy as np import Kinematics_class as Kc inner_length = float(input("Length of the inner arm?\n")) outer_length = float(input("Length of the outer arm?\n")) answer = input("Inverse og Forward?\n") robotic_arm = Kc.Kinematics(inner_length,outer_length) if answer.lower()== "inverse": print("Need two coordinates for where to go\nand I will provide the angles for the arm") x = float(input("What is the X coordinate?\n")) y = float(input("What is the Y coordinate?\n")) [q1,q2] = robotic_arm.inverse(x,y) print(f"The first angle is {q1:.2f} degrees and \nthe second angel is {q2:.2f} degrees") elif answer.lower() == "forward": print("Need two angles for how the arm should strech and I'll give you the X and Y coordinates") first_angle = float(input("What is the fisrt angle?\n")) second_angle = float(input("What is the second angle?\n")) [x,y] = robotic_arm.forward(first_angle,second_angle) print(f"The x, y coordinate is = [{x:.2f},{y:.2f}]") else: print("Error!") print("I asked for forward or inverse kinematics") print("Godbye!")
true
2a1d0766db2123cb8120b5eb9ce958c168340edc
frizzby/coyote-leg
/week2/ex4_done.py
1,470
4.25
4
# 4. Implement a class User with attributes name, age. The instances of this class should be sortable by age by default. So sorted([User(name='Eric', age=34), User(name='Alice', age=22)]) will return a list of sorted users by their age (ASC). How would you sort those objects by name? Don't forget to Implement __str__ method to help testing and visualize the object. # Hint for the default sorting: __cmp__, functools.total_ordering. # from functools import total_ordering @total_ordering class User: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return "%s %s" % (self.name, self.age) def __eq__(self, other): return (self.name, self.age) == (other.name, other.age) def __ne__(self, other): return not (self == other) def __lt__(self, other): return self.age < other.age @staticmethod def cmp(x, y): return (x > y) - (x < y) def __cmp__(self, other): return User.cmp(self.age, other.age) def main(): users = [User("mikhail", 57), User("marina", 55), User("alexandra", 19), User("mikhail", 31)] print(users) sorted_users_by_age = sorted(users) print(sorted_users_by_age) #additional sorting by age sorted_users_by_name = sorted(sorted_users_by_age, key=lambda u: u.name) print(sorted_users_by_name) print(User("mikhail", 57) == User("mikhail", 57)) if __name__ == '__main__': main()
true
55bd778ebeb9465d1be9d73d3fe65b6250125ad9
mm1618bu/Assignment1
/HW1_2.6.py
216
4.1875
4
# Ask user for a number enterNumber = input("Enter a number: ") # set inital variable to zero totalnum = 0 # for each integer, add 1 for integer in str(enterNumber): totalnum += int(integer) print(totalnum)
true
e1063970a9018300bc0d195b71ee5ae8e33b0fd5
MiguelFirmino/Login-System
/Login System.py
2,245
4.125
4
data_text = [] first_names = [] last_names = [] emails = [] passwords = [] def user_choice(): print('Hello user, create an account or login to an existing one.') choice = input('Insert "1" if you wish to create an account or "2" if you wish to login: ') print('\r') if choice == '1': create_account() user_choice() else: login_account() user_choice() def register_info(): with open('Login_Data.txt', 'r') as login_data: global data_text, first_names, last_names, emails, passwords data_text = login_data.readlines() for i in data_text: data_text[data_text.index(i)] = i.strip() emails = (data_text[2::4]) def create_account(): with open('Login_Data.txt', 'a') as login_data: first_name = input('First name: ') last_name = input('Last name: ') email = input('Insert your Email adress: ') while email in emails: print('That email is already registered') email = input('Insert another Email adress: ') password = input('Create a password: ') passwordc = input('Confirm your password: ') info = [first_name, last_name, email, password] while passwordc != password: print('The passwords do not match.') passwordc = input('Reinsert your password: ') for i in info: login_data.write(i) login_data.write('\n') print('Nice! Your account was registered.') print('\r') register_info() def login_account(): register_info() with open('Login_Data.txt', 'r'): login_email = input('Email: ') while login_email not in emails: print('Invalid Email') login_email = input('Reinsert your Email: ') login_password = input('Password: ') while login_password != data_text[data_text.index(login_email) + 1]: print('Invalid password') login_password = input('Reinsert your password: ') print('Hello {} {}, welcome back!'.format(data_text[data_text.index(login_email) - 2], data_text[data_text.index(login_email) - 1])) print('\r') user_choice()
true
b26949e87237076f51997342f975fb3ba56ee4d6
mfahn/Python
/primeFinder.py
721
4.28125
4
#get starting value user_start = input("Enter a starting value ") #get ending value user_end = input("Enter an ending value ") increment = user_start count = 2 prime = 1 #find if each value in the range is prime or not #increment is every number between the user_start and user_end for increment in range(user_end): #count is every number between 1 and increment for count in range (increment): #if increment is evenly divided by count, then it cannot be prime #prime == 1 means the value is prime, prime == 0 means it is not prime if(increment % count == 0): prime = 0 if(prime == 1): print(increment+" is prime") else: print(increment+" is not prime")
true
4b7a16a68dcf73d62cda7e6e8b46b5c0516eef98
amariwan/csv-to-db
/csv2sql.py
1,558
4.28125
4
# Import required modules import csv import sqlite3 # Connecting to the geeks database connection = sqlite3.connect('user.db') # Creating a cursor object to execute # SQL queries on a database table cursor = connection.cursor() # Table Definition create_table = '''CREATE TABLE IF NOT EXISTS user( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, email TEXT NOT NULL, firstname TEXT NOT NULL, lastname TEXT NOT NULL, department TEXT NOT NULL, location TEXT NOT NULL); ''' # Creating the table into our # database cursor.execute(create_table) # Opening the person-records.csv file file = open('user.csv') # Reading the contents of the # person-records.csv file contents = csv.reader(file, delimiter=',') # for row in csv_reader_object: # print(row) # SQL query to insert data into the # person table insert_records = "INSERT INTO user (id, username, email, firstname, lastname, department, location) VALUES(?, ?, ?, ?, ?, ?, ?)" # Importing the contents of the file # into our person table cursor.executemany(insert_records, contents) # SQL query to retrieve all data from # the person table To verify that the # data of the csv file has been successfully # inserted into the table select_all = "SELECT * FROM user" rows = cursor.execute(select_all).fetchall() # Output to the console screen for r in rows: print(r) # Commiting the changes connection.commit() # closing the database connection
true
6a01ba97a6b5558756cf078be161936733a0b406
SahilTara/ITI1120
/LABS/lab3-students/q3a.py
324
4.21875
4
################Question 3a#################### def is_divisible(n, m): '''(int, int) -> bool Return if n is divisible by m. ''' return n % m == 0 x = int(input("Enter 1st integer:\n")) y = int(input("Enter 2nd integer:\n")) print(x, "is" + " not" *( not(is_divisible(x,y)) ), "divisible by", y)
false
dd0337366b869db97bb9dbedfcd41a2ecb606028
SahilTara/ITI1120
/LABS/lab8-students/NyBestSellers.py
1,403
4.34375
4
def create_books_2Dlist(file_name): """(str) -> list of list of str Returns a 2D list containing books and their information from a file. The list will contain the information in the format: Publication date(YYYY-MM-DD), Title, Author, Publisher, Genre. Preconditions: each line in the file specified contains information about a book. In the format Title, Author, Publisher, Publication date(DD/MM/YY), Genre. """ file = open(file_name).read().splitlines() books = [] for book in file: book = book.split("\t") tmp = book[3] tmp = tmp.split("/") year = tmp[2] tmp[2] = tmp[0].zfill(2) tmp[0] = year tmp = "-".join(tmp) book.remove(book[3]) book.insert(0, tmp) books.append(book) return books def search_by_year(books, year1, year2): """(list of list of str, int, int) Prints a list of books in the list books published between year1 and year2. Precondition: books is a list created from create_books2Dlist """ print("All titles between", year1, "and", year2) for book in range(len(books)): this_book = books[book] date = this_book[0] year = int(date.split('-')[0]) title = this_book[1] author = this_book[2] if year1 <= year <= year2: print(title,", by", author,"(" + date + ")")
true
a97f46d90601ccf4cdae1a5b46862bba1be0a730
SahilTara/ITI1120
/LABS/lab3-students/q3b.py
622
4.28125
4
################Question 3b#################### def is_divisible23n8(n): '''(int) -> str Return yes if n is divisible by 2 or 3 and not 8 otherwise no. ''' if (is_divisible(n, 2) or is_divisible(n, 3)) and (not(is_divisible(n,8))): return "yes" else: return "no" def is_divisible(n, m): '''(int, int) -> bool Return if n is divisible by m. ''' return n % m == 0 x = int(input("Enter an integer: ")) if is_divisible23n8(x) == "yes": print(x, "is divisible by 2 or 3 but not 8") else: print("It is not true that", x, "is divisible by 2 or 3 but not 8")
false
2fc4a1c279b066bcf01b10b5db8cf014c6e6c394
SahilTara/ITI1120
/Datastructures/unbalancedbst.py
2,328
4.125
4
#Binary Search Tree in Python class Node: def __init__(self, val): self.value = val self.leftChild = None self.rightChild = None def insert(self, data): if self.value == data: return False elif self.value > data: if self.leftChild: return self.leftChild.insert(data) else: self.leftChild = Node(data) return True else: if self.rightChild: return self.rightChild.insert(data) else: self.rightChild = Node(data) return True def find(self, data): if self.value == data: return True elif self.value > data: if self.leftChild: return self.leftChild.find(data) else: return False else: if self.rightChild: return self.rightChild.find(data) else: return False def pre_order(self): if self: print(self.value) if self.leftChild: self.leftChild.pre_order() if self.rightChild: self.rightChild.pre_order() def post_order(self): if self: if self.leftChild: self.leftChild.post_order() if self.rightChild: self.rightChild.post_order() print(self.value) def in_order(self): if self: if self.leftChild: self.leftChild.in_order() print(self.value) if self.rightChild: self.rightChild.in_order() class Tree: def __init__(self): self.root = None def insert(self, data): if self.root: return self.root.insert(data) else: self.root = Node(data) return True def find(self, data): if self.root: return self.root.find(data) else: return False def pre_order(self): print("PreOrder") self.root.pre_order() def post_order(self): print("PostOrder") self.root.post_order() def in_order(self): print("InOrder") self.root.in_order()
false
33d62035bdab6e284039773e0707cc017ed3b12a
Dmitry-White/CodeWars
/Python/6kyu/even_odd.py
251
4.1875
4
""" Created on Wed Aug 23 2e:28:33 2017 @author: Dmitry White """ # TODO: Create a function that takes an integer as an argument and # returns "Even" for even numbers or "Odd" for odd numbers. def even_or_odd(n): return "Even" if n%2 == 0 else "Odd"
true
bcd5e6cb8f0a48c7f61a2d4ddfddba5bf5579a03
Dmitry-White/CodeWars
/Python/6kyu/expanded_form.py
551
4.125
4
""" Created on Wed Aug 30 23:34:23 2017 @author: Dmitry White """ # TODO: You will be given a number and you will need to return it as a string in Expanded Form. # For example: # expanded_form(42), should return '40 + 2' # expanded_form(70304), should return '70000 + 300 + 4' def expanded_form(num): l = len(str(num)) nulls = 10**(l-1) if l == 1: return str(num) num_new = (num//nulls)*nulls num_rest = num - num_new if num_rest == 0: return str(num_new) return str(num_new) + ' + ' + expanded_form(num_rest)
true
3ab257aa3e0c99c106f8ae516675cd74f5253c1b
MoAbd/codedoor3.0
/templating_engine.py
1,615
4.4375
4
''' It's required to make a templating engine that takes a template and substitute the variables in it. The variables are present in the templates in the form {{some_variable}}. The variables can be nested, so for {{some_{{second_variable}}}} second_variable will be evaluated first and then the other one will be evaluated. Input Format N(number of variables) M(Numbers of lines for a template) variable 1 (in the form of `variable_name=value`) variable 2 (in the form of `variable_name=value`) ... variable N Template consisting of M lines Constraints 0 <= N, M < 1000 1 <= length of a line, variable definition < 1000 Output Format the parsed template ''' # Enter your code here. Read input from STDIN. Print output to STDOUT n, m = raw_input().split() n = int(n) m = int(m) temp = [] var = [] if n == 0: print raw_input() else: for i in range(n): var.append(raw_input()) var = dict(i.split('=') for i in var) for i in range(m): temp.append(raw_input()) x = temp[i] counter = x.count('}}') for i in range(counter): end = x.find('}}') begin = x.find('{{') if end + 2 == len(x): begin = x.rfind('{{') x = x[:begin] + var[x[begin+2 : end]] + x[end+2:] elif x[end+2] == '{': begin = x.find('{{') x = x[:begin] + var[x[begin+2 : end]] + x[end+2:] else : begin = x.rfind('{{') x = x[:begin] + var[x[begin+2 : end]] + x[end+2:] print x
true
ef53c04c4f7085a85906fd95c862136f40f3e1e4
dzvigelsky/Anti_Mode
/AntiMode.py
2,203
4.25
4
import time start_time = time.clock() # The clock function def main(): frequencies = {} text_file = input("What is the name of the text file you want to read? ") File_object = open(text_file, 'r') # You can put in the name of the file here lines = (File_object).readlines() # Read the file and sort it into a list File_object.close() for i in lines: # Adds the numbers from the text file to the dictionary if float(i) in frequencies: frequencies[int(i)] += 1 else: frequencies[int(i)] = 1 def minimums(dictionary): min_value = float("inf") # first lowest number must be the greatest possible entity to compare to for k, v in dictionary.items(): if v < min_value: # If smallest value is less than the previous min_value = v # Now you replace the smallest value nums = '' # Create this string in order to store the smallest value(s) for k, v in dictionary.items(): # Adds the smallest number(s) to a string if v == min_value: nums += str(k) + ', ' print("The number(s) that appeared the least amount of times is/are: " + nums.rstrip( ', ') + " with a frequency of: " + str(min_value)) # The final print statement minimums(frequencies) main() # Call the main function print("the code runs for: " + str((time.clock() - start_time) * 1000) + " milliseconds") # Final statement printed out # Advantages: # On average, ran file1 and file2 faster compared to the other program # Dictionaries are literally the ideal data structure in this case because you only need to deal with keys and values # They don't require indexes unlike the other program # This is why the program runs faster when dealing with larger text files # Disadvatages: # Requires more memory due to hashing process compared to the other program # Essentially, all of the numbers in the text file are the "keys" and the amounts of time they appear are the hashes # The hash function attributes all of the keys to their appropriate value # When dealing with smaller text files, the hashing processes will cause this program to run slower
true
b80f78ad9e4e5771e748dbe9b4dac54e39f1f044
fanj1/RobotTeamProject
/sandbox_motors_new/person3_motors.py
2,677
4.625
5
""" Functions for TURNING the robot LEFT and RIGHT. Authors: David Fisher, David Mutchler and Jun Fan. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. # DONE: 2. Implment turn_left_seconds, then the relevant part of the test function. # Test and correct as needed. # Then repeat for turn_left_by_time. # Then repeat for turn_left_by_encoders. # Then repeat for the turn_right functions. import ev3dev.ev3 as ev3 import time def test_turn_left_turn_right(): """ Tests the turn_left and turn_right functions, as follows: 1. Repeatedly: -- Prompts for and gets input from the console for: -- Seconds to travel -- If this is 0, BREAK out of the loop. -- Speed at which to travel (-100 to 100) -- Stop action ("brake", "coast" or "hold") -- Makes the robot run per the above. 2. Same as #1, but gets degrees and runs turn_left_by_time. 3. Same as #2, but runs turn_left_by_encoders. 4. Same as #1, 2, 3, but tests the turn_right functions. """ def turn_left_seconds(seconds, speed, stop_action): """ Makes the robot turn in place left for the given number of seconds at the given speed, where speed is between -100 (full speed turn_right) and 100 (full speed turn_left). Uses the given stop_action. """ def turn_left_by_time(degrees, speed, stop_action): """ Makes the robot turn in place left the given number of degrees at the given speed, where speed is between -100 (full speed turn_right) and 100 (full speed turn_left). Uses the algorithm: 0. Compute the number of seconds to move to achieve the desired distance. 1. Start moving. 2. Sleep for the computed number of seconds. 3. Stop moving. """ def turn_left_by_encoders(degrees, speed, stop_action): """ Makes the robot turn in place left the given number of degrees at the given speed, where speed is between -100 (full speed turn_right) and 100 (full speed turn_left). Uses the algorithm: 1. Compute the number of degrees the wheels should turn to achieve the desired distance. 2. Move until the computed number of degrees is reached. """ def turn_right_seconds(seconds, speed, stop_action): """ Calls turn_left_seconds with negative speeds to achieve turn_right motion. """ def turn_right_by_time(degrees, speed, stop_action): """ Calls turn_left_by_time with negative speeds to achieve turn_right motion. """ def turn_right_by_encoders(degrees, speed, stop_action): """ Calls turn_left_by_encoders with negative speeds to achieve turn_right motion. """ test_turn_left_turn_right()
true
c7ea01d08f8b054e1570ca82272c5731780fe9f9
NV230/Stock-Market
/search.py
1,012
4.125
4
# Stock Market """ @authors: Keenan, Nibodh, Shahil @Date: Feb 2021 @Version: 2.2 This program is designed to return the prices of stocks Allows the user to input the number stocks they want to compare and asks for the ticker for each stock. """ # Calculate daily change from close - previous close # yahoo finance library is where we get stock market information. import yfinance as yf # Creates an array to hold the inputted tickers stocks = [] #Asks the user the amount of stocks they want to compare numOfStocks = int(input("How many stocks do you want to compare? \n")) #Loop that iterates for the number of stocks that the user wants to compare for i in range(numOfStocks): print("List the stock ticker (ex: WMT) and then the name (ex: Walmart)") firstOne = input("Ticker: ") secondOne = input("Name: ") ticker = firstOne table = yf.download(ticker) print("") print("") print("") print("") print("Daily Change for " + secondOne) print("") print(table) print(stocks)
true
fdd002aae55435a9ebd099484d57e9746d93b927
heysushil/full-python-course-2020
/9.for_loop.py
1,803
4.28125
4
# मेरे Youtube चैनल को सबस्क्राइब करना ना भूलो ताकि आपको कोड का पूरा फ़्लो समझमे आए - https://www.youtube.com/channel/UCphs2JfmIClR62wbyf76HDg # कोई भी सवाल है उसको मेरे यूट्यूब चैनल के कमेन्ट या डिस्कशन सेक्शन मे पूछ सकते हो - https://www.youtube.com/channel/UCphs2JfmIClR62wbyf76HDg/discussion # और हाँ GitHub पर मुझे फॉलो करना ना भूलो ताकि सारे अपडेट एण्ड वर्क आपको मिलता रहे। # for loop ''' while loop intilaize while(condtion): while body incre/ decre ''' students = ['ram','shyam','seeta','geeta'] # s is varaible which stores values of list one by one for s in students: print('Hello ',s,' welcome in python class.') # stirng name = 'megha' print('\nName: ',name[0]) for n in name: print(n) # dict print('\n\nDict output') students = {'name':'megha','email':'megha@g.com'} for s in students: print(s,' : ',students[s]) # range print('\n\nRang \n') # in range if we give only one number it will start form 0 and end at n-1 posstion # range(start,end,diff) for r in range(0): print(r) else: print('\n2s table ended.') ''' while for do while ''' # nested loop name = ['megha','ayman','ram','shyam'] course = ['python','timing 10 - 11'] print('\n\nNested loop\n') for n in name: print('Hello ',n,'\n') # create loop in n loop print(''' -------------------- Your Detsils is --------------------\n ''') for c in course: print(c) print('\n')
false
826d54cefd72c56d387dfec63190cc88b7baeac6
heysushil/full-python-course-2020
/2.1.datatypes-in-python.py
2,845
4.125
4
# मेरे Youtube चैनल को सबस्क्राइब करना ना भूलो ताकि आपको कोड का पूरा फ़्लो समझमे आए - https://www.youtube.com/channel/UCphs2JfmIClR62wbyf76HDg # कोई भी सवाल है उसको मेरे यूट्यूब चैनल के कमेन्ट या डिस्कशन सेक्शन मे पूछ सकते हो - https://www.youtube.com/channel/UCphs2JfmIClR62wbyf76HDg/discussion # और हाँ GitHub पर मुझे फॉलो करना ना भूलो ताकि सारे अपडेट एण्ड वर्क आपको मिलता रहे। ''' Discussion topiscs: What is predefined keywords. Behaviour of predefined keywords. How many predefined keywords in python. Example keyword: if, else, for, while, try, except, in, is Function / Method 1. pre-defined / 2. user-define print() ''' # Topics of DataTypes ''' Built-in Data Types In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: 1. Text Type: str 2. Numeric Types: int, float, complex 3. Sequence Types: list, tuple, range 4. Mapping Type: dict 5. Set Types: set, frozenset 6. Boolean Type: bool 7. Binary Types: bytes, bytearray, memoryview Extra: 1. c / c++ / php etc me char keyword milta hai ''' # code area name = 'Mr. Python' print(type(name)) print('Name: ',name) # int value wo normal number hote hain. Matlab possitive and negative intnum = 878787 # accept possitive & negatives numbers print('\n\nIntnum: ',type(intnum)) floatnum = 878768.987987 # float = decimal number ye bhi +/- print('FLoatnum: ',type(floatnum)) # complex number: use j after int or float +/- complexnum = 9898j print('complexnum: ',type(complexnum)) # sequence datatypes # list: [] - big bracket # index array => array(1,2,3,4,5); listval = [1,2,3,4,5,'hello'] print('Listval: ',type(listval)) # tuple: () # tupleval = (1,2,3,4,5,'hello') tupleval = ('Hello',) print('Tupleval: ',type(tupleval)) # range rangval = range(6) print('Rangval: ',type(rangval)) # dict = dictonary => key and value ki mapping {} # associative array => array('name'=>'shubham') dictval = {'name':'Python'} print('Dictval: ',type(dictval)) # set: union / intersection => {} setval = {1,23,4,5} print('Setval: ',type(setval)) # boolean = binary => yes/no or 0/1 booleanval = bool(767) print('Boolval: ',type(booleanval)) ''' Qestiong: 1. python data-types ye kitne bit ya byte store lete hain. 2. index array kya hota hai? 3. diffrence b/w list and tuple 4. what is associative array 5. what is set in python 6. diff b/w dict and set '''
false
1c09b4fdc8672eb7ffae8542592059d1dc5d44d0
PierceSoul/pythonStudy
/study_基础/面向对象.py
2,122
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/3/16 下午10:21 # @File : 面向对象.py import types # 双下划线开头的实例变量是不是一定不能从外部访问呢? # 其实也不是。不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name, # 所以,仍然可以通过_Student__name来访问__name变量 class Person(object): def __init__(self, name, age, gender): self.__name = name self.__age = age self.__gender = gender def get_name(self): return self.__name def get_age(self): return self.__age def get_gender(self): return self.__gender def set_name(self, name): self.__name = name def set_age(self, age): self.__age = age def set_gender(self, gender): self.__gender = gender def print_person(self): print('%s: %s: %s' % (self.__name, self.__age, self.__gender)) p = Person('张三', 18, 'male') p.print_person() #判断一个变量是否是某个类型 print(isinstance(p, Person)) #继承和多态 class Animal(object): def run(self): print("Animal is running...") class Dog(Animal): def run(self): print("Dog is running...") class Pig(Animal): def run(self): print("Pig is running...") def run_twice(animal): animal.run() animal.run() run_twice(Animal()) run_twice(Dog()) run_twice(Pig()) #判断对象类型 class类型用isinstance print(type(run_twice) == types.FunctionType) print(type(123) == int) a = Animal() d = Dog() print(isinstance(a , Animal)) print(isinstance(d , Animal)) #判断是哪种类型中的一种 print(isinstance([1, 2, 3], (list, tuple))) #获取对象的所有属性和方法 print(dir("a")) #getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态 print(hasattr(d,'run')) #实例属性和类属性 注意 : 实例属性和类属性命名相同 则实例属性会覆盖类属性 class Ball(object): name = 'basketball'#实例属性 def __init__(self,color): self.color = color #类属性
false
447f2807b9e1fe0fb10f29ace5f2957080cf6f47
chao-ji/LeetCode
/python/array/use_input_array_as_auxiliary_memory/lc27.py
2,362
4.15625
4
"""27. Remove Element Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example 1: Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length. Clarification: Confused why the returned value is an integer but your answer is an array? Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); } """ class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ # The Idea: # LOOP INVARIANT: # at any point, # # nums[0], ..., nums[i] contains numbers != `val` # * * * * * * - - - - . # # 0 i j # <=equal to `val`==> check if nums[j] != val i = -1 for j in range(len(nums)): # in each iteration, we check if we can extend the current streak of # numbers NOT equal to `val` ending at `nums[i]` if nums[j] != val: # we CAN extend the current streak of number NOT equal to `val` i += 1 nums[i] = nums[j] # otherwise, we simply increment `j`, until we find the next number # != `val` return i + 1
true
3d057680982ace7ea0ab217be3c8667484f1d1f8
SACHSTech/ics2o1-livehack-2-DanDoesMusic
/problem1.py
678
4.34375
4
###this takes the 2 speeds the limit and the users speed### speed = int(input("how fast was the diver: ")) limit = int(input("what is the speed limit: ")) ###this chacks if they are above the speed limit it took me a bit but i got it working### if (speed - limit) >= 1 : print("your fine is 100$") elif (speed - limit) >= 21 : print("your fine is 270$") elif (speed - limit) >= 31 : print("your fine is 570$") else : print ("you are within the limit") ###it checks to see if you are above 1 u/h or unit per hour then it checks if you are 21 u/h above then 31 or more and determines your fine based on what you cross if you are below or at the limit you are safe###
true
fcbf5247a1961337748b5181a30e1d55a451e201
zar777/exercises
/chapter_one/unique_characters.py
934
4.125
4
"""Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures? Exercises 1.1 """ class UniqueCharacters(object): """this class represents an empty dictionary dictionary""" def __init__(self): self.dictionary = {} def unique(self, string): """this method is created to return the first child, given his parent""" count = 0 numbers_occurrence = 0 if string != "": for letter in string: if letter not in self.dictionary: self.dictionary[letter] = 0 else: count += 1 self.dictionary[letter] = 1 return count if __name__ == '__main__': string = "parallelo" unique_characters = UniqueCharacters() print string print unique_characters.unique(string) print unique_characters.dictionary
true
5fdc21c50426bbeffd1fab5e53df23c7fe218cd3
zar777/exercises
/Chapter_three/three_stacks.py
2,384
4.21875
4
"""Describe how you could use a single array to implement three stacks. Exercises 3.1 I WRONG BECAUSE I USE A LIST AND NOT AN ARRAY""" class ThreeStacks(object): """this class is created to represent an empty array which there are only two divisors used by delimited the three stacks""" def __init__(self): self.array = ["Divisor_one", "Divisor_two"] def push_first_stack(self, element): "push element in the first stack" self.array.insert(0, element) def push_second_stack(self, element): "push element in the second stack" self.array.insert(self.array.index("Divisor_one") + 1, element) def push_third_stack(self, element): "push element in the third stack" self.array.insert(self.array.index("Divisor_two") + 1, element) def pop_first_stack(self): "pop element in the first stack" if self.array[0] != "Divisor_one": self.array.pop(0) def pop_second_stack(self): "pop element in the second stack" if self.array[self.array.index("Divisor_one") + 1] != "Divisor_two": self.array.pop(self.array.index("Divisor_one") + 1) def pop_third_stack(self): "pop element in the third stack" if self.array.index("Divisor_two") + 1 != len(self.array): self.array.pop(self.array.index("Divisor_two") + 1) if __name__ == '__main__': three_stack = ThreeStacks() three_stack.pop_first_stack() three_stack.pop_second_stack() three_stack.pop_third_stack() print three_stack.array three_stack.push_first_stack(2) three_stack.push_first_stack(4) three_stack.push_first_stack(8) print three_stack.array three_stack.push_second_stack(55) three_stack.push_second_stack(33) three_stack.push_second_stack(22) three_stack.push_second_stack(1) print three_stack.array three_stack.push_third_stack(99) three_stack.push_third_stack("A") print three_stack.array three_stack.pop_first_stack() three_stack.pop_second_stack() three_stack.pop_third_stack() print three_stack.array three_stack.pop_first_stack() three_stack.pop_second_stack() three_stack.pop_third_stack() print three_stack.array three_stack.pop_first_stack() three_stack.pop_first_stack() three_stack.pop_first_stack() print three_stack.array
true
b494b3cfe84c7cbc8bc786011cbdf475cdf6b809
ositowang/IMooc_introToAlgorithm
/BasicSorting/selection_sort.py
776
4.375
4
""" N平法复杂度的算法 选择排序 我们从第一个开始,从头到尾找一个个头最小的小盆友,然后把它和第一个小盆友交换。 然后从第二个小盆友开始采取同样的策略,这样一圈下来小盆友就有序了。 """ def selection_sort(array): for i in range(0,len(array)): # 假设当前下标的值是最小的 min_index = i # 从当前下标的下一个开始遍历 for j in range(i+1,len(array)): #如果值小于当前的最小值,就更新当前最小值的下标 if array[j] < array[min_index]: min_index = j #最后交换当前下标和当前最小值 array[i],array[min_index] = array[min_index],array[i] return array
false
7f26fdf3884a01b784ac349de84b950039741d55
thedrkpenguin/CPT1110
/Week 4/list_modification4.py
248
4.21875
4
FOOD = ["Pizza", "Burgers", "Fries", "Burgers","Ribs"] print("Here is the current food menu: ") print(FOOD) FOOD_ITEM = str(input("Which item would you like to remove? ")) FOOD.remove(FOOD_ITEM) print("Here is the new food menu: ") print(FOOD)
true
26f43680761d404a6f18137a44934d9583aa3268
thedrkpenguin/CPT1110
/Week 11/distance2OriginProgram.py
1,157
4.40625
4
class Point(): def __init__(self,x,y): self.x = x #self.x = 6 self.y = y #self.y = 8 def distance(self): return (self.x**2 + self.y**2) ** .5 #pythagorean theorum #def distance(self,x=0,y=0): #return (x**2 + y**2) ** .5 #pythagorean theorum first_point = Point(6,8) #send 6 as first parameter, 8 as the second second_point = Point(12,20) #send 12 as first parameter, 20 as the second x = int(input("Enter a x-coordinate: ")) y = int(input("Enter a y-coordinate: ")) third_point = Point(x,y) print("The distance (first point) of this point from the origin is: "\ , first_point.distance()) print("The distance (second point) of this point from the origin is: "\ , second_point.distance()) print("The distance (third point) of this point from the origin is: "\ , third_point.distance()) #print("The distance of this point from the origin is: "\ # , Point.distance(first_point)) #print("This is with the class name first: ", type(Point.distance)) #print("This is with the objects name first: ", type(first_point.distance))
false
727d74cf441d3d1aa62a98c6b4a2b933b9ccaee0
thedrkpenguin/CPT1110
/Week 2/largestnumberCheckFOR.py
202
4.21875
4
num = 0 max_num = 0 for i in range(4): num = int(input("Enter a value for number: ")) if num > max_num: max_num = num print("The largest number entered is ", max_num)
true
8eca6001f5fc103ed8ac7a8da3e98d7c3508fd1f
thedrkpenguin/CPT1110
/Week 1/firstprogram.py
575
4.25
4
print("My Name is ", "Paul", sep = "-", end = " ") print("Paul", "Burkholder") year = 2018 month = "August" number = 3.123456789 millions = 1000000 print(f'The current month is {month} and the year is {year}.') print("The current month is" , month , "and the year is ", year, ".") print("The current month is {} and the year is {}.".format(month,year)) print("The current month is {month} and the year is {year}.".format(month="July",year="2018")) print("The number is ",format(number, '10.2f')) print("Bigger number", format(millions, ',.2f'))
false
83b0b2e4b0eb8ae1db2074ee4d953198ae0eafb0
learning-dev/46-Python-Exercises-
/ex19b.py
516
4.3125
4
""" The python way of checking for a string is pangram or not """ import string def is_pangram(in_string, alphabet=string.ascii_lowercase): # function for checking pangram or not alphaset = set(alphabet) # creating a set of all lower case return alphaset <= set(in_string.lower()) # checking while True: in_str = raw_input("Enter a string to check :") if in_str is None or in_str.isspace(): print "Error: Invalid input!" continue else: break print is_pangram(in_str)
true
6bcf6f675943b9144db51a7fefb97fbc6c0f4381
lucasolifreitas/ExerciciosPython
/secao8/exerc4.py
381
4.15625
4
""" Faça uma função para verificar se um número é quadrado perfeito. Um quadrado perfeito é um número inteiro não negativo que pode ser expresso como quadrado de outro número inteiro. """ def quadrado_perfeito(num): if num > 0 and type(num) == int: return num ** 2 else: return 'O número deve ser inteiro positivo!' print(quadrado_perfeito(9))
false
dd16f246a0197d5e21e965bc0e8c3e1f4b4bc158
dmoses12/python-intro
/pattern.py
929
4.25
4
def pattern(number): """Function to generate a pattern syntax: pattern(number) input: number output: symmetrical pattern of _ and * according to number provided return: 0 when complete """ print "Pattern for number: %s" % number # complete this function max_stars = 2 * number - 1 # max number of stars to print num_ulines = number - 1; # number underscores for first line # print to max_stars and fill with _ for i in range(1, max_stars, 2): print "_ " * num_ulines + "* " * i + "_ " * num_ulines num_ulines -= 1 # decrease underscores as we increase stars # complete and reverse pattern for i in range(max_stars, 0, -2): print "_ " * num_ulines + "* " * i + "_ " * num_ulines num_ulines += 1 # increase underscores as we decrease stars return 0 if __name__ == "__main__": pattern(1) pattern(2) pattern(3) pattern(4)
true
efce03538801ff68cee65346772dff3dd078f35f
harshalkondke/cryptography-algorithm
/Multi.py
533
4.125
4
def encrypt(text, key): result = "" for i in range(len(text)): char = text[i] if char.isupper(): mychar = ord(char) - 65 ans = (mychar * key) % 26 result += chr(ans + 65) else: mychar = ord(char) - 97 ans = (mychar * key) % 26 result += chr(ans + 97) return result text = input("Enter your text: ") key = int(input("Enter key: ")) print("Text : " + text) print("key : " + str(key)) print("Cipher : " + encrypt(text, key))
true
7a74c15d52ff4840ea630060d12fde662cf476fc
Abraham-Lincoln-High-School-MESA/2020-2021-Python
/1.- Print statements, Variables, and Operators/2_Operators.py
2,520
4.1875
4
# 11/08/2020 @author: Giovanni B """ Operators are symbols that tell the compiler to perform certain mathematical or logical manipulations. For instance, arithmetic, comparison, boolean, etc. There are several operators, and they obviously have a precedence order, this is, the order of "importance" to decide which one to perform first, for which I added an image into the folder that explains it. PD: In the image they forgot to add the parenthesis, which have the highest precedence Most of the operators are used for integer and boolean operations, the only notable exception would be that besides to sum integers, we can use the + operator to concatenate strings, this is, to join them """ # String operators print("Concatenating " + "strings") # Concatenating strings # All of the following are integer operators print(5 + 10) # 15; Summing print(10 - 2) # 8; subtracting print(30 / 3) # 10; dividing print(7 * 9) # 63; multiplying x = 8 # We can also use operators with variables y = 17 print(x - y) # -9; subtracting print(x + y) # 25; summing print(9 % 4) # 1; reminder of the division print(8 ** 2) # 64; to the power # All of the following are boolean operators print(5 == 5) # True; is 5 equal to 5? print(6 == 0) # False; is 6 equal to 0? print(4 != 0) # True; is 4 not equal to 0? print(5 != 5) # False; is 5 not equal to 5? print(10 > 10) # False; is 10 greater than 10? print(10 >= 10) # True; is 10 greater than or equal to 10? print(7 < 10) # True; is 7 less than 10? print(7 <= 7) # True; is 7 less than or equal to 7? # We can also "mix" integer and boolean operators print(10 > (2 * 3)) # True; is 10 greater than 6 (2 * 3)? print(10 == (5 * 2)) # True; is 10 equal to 10 (5 * 2)?
true
e645d502352b2169a169e6b07b08d143ba88e794
Abraham-Lincoln-High-School-MESA/2020-2021-Python
/4.- Lists/z_Practice Problems from HW 3/0- Coffee_Machine.py
1,463
4.5
4
# Initializing variables waterPerCup = 0 milkPerCup = 0 beansPerCup = 0 costPerCup = 0 # Inputting the resources print("Enter the machine's resources") water = int(input("ml of water: ")) milk = int(input("ml of milk: ")) beans = int(input("gr of coffee beans: ")) cups = int(input("cups: ")) money = int(input("How much do you have? $")) # Selecting a coffee print("What do you want to buy?") print("1.- Espresso $4\n2.- Latte $7\n3.- Cappuccino $6") option = int(input()) # Assigning the needed resources if option == 1: waterPerCup = 250 milkPerCup = 0 beansPerCup = 16 costPerCup = 4 elif option == 2: waterPerCup = 350 milkPerCup = 75 beansPerCup = 20 costPerCup = 7 elif option == 3: waterPerCup = 200 milkPerCup = 100 beansPerCup = 12 costPerCup = 6 # Inputting the number of cups cupsOfCoffee = int(input("How many cups would you like? ")) # Calculating the maximum of coffee cups we can make min = water // waterPerCup if milkPerCup != 0 and milk // milkPerCup < min: min = milk // milkPerCup if beans // beansPerCup < min: min = beans // beansPerCup if money // costPerCup < min: min = money // costPerCup if cups < min: min = cups # Choosing what message to display if min == cupsOfCoffee: print("Here you go!") elif min < cupsOfCoffee: print("I can only make " + str(min) + " cups") elif min > cupsOfCoffee: print("I can even make " + str(min) + " cups")
true
e408ea0cafaad6313366c9fce5c523fbe758479c
max-zia/nand2tetris
/assembly language/multiply.py
619
4.125
4
# multiply integers a and b without multiplication def multiply(a, b): # for all n, n*0 = 0 if a == 0 or b == 0: return 0 # operate on absolute values product = abs(a) # add a to itself b times and store in product for i in range(1, abs(b)): product += abs(a) # if a or b < 0, product must be negative # if a & b < 0, product must be positive if (a < 0): product = -product if (a < 0): product = -product return product # you can string multiply() together n times to multiply # arbitrarily long combinations of numbers. Alternatively, # you can change the function to accept any number of kwargs
true
8ed06ac79c147dbeca6a1a4a6b4678dc945a95eb
2266384/ATBSWP
/Ch 7 - Regular Expressions/regexStrip.py
542
4.46875
4
#! python3 # regexStrip.py - Function to strip spaces OR specified characters from a string import re def regexStrip(myString, character=' '): defRegex = re.compile(r'^[\s]+|[\s]+$') myRegex = re.compile(r'' + re.escape(character)) if character == ' ': return defRegex.sub('', myString) else: return myRegex.sub('', myString) print(regexStrip(' hello world ')) print(regexStrip(' hello world ', 'e')) print(regexStrip(' hello world ', 'l')) print(regexStrip(' hello world ', 'lo'))
false
e358a76b696ef686576b746673732144d79d23d3
sanashahin2225/ProjectEuler
/projectEuler1.py
365
4.25
4
# 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 multipleOfThreeandFive(num): sum = 0 for i in range(1,num): if i%3 == 0 or i%5 == 0: sum += i return sum print(multipleOfThreeandFive(1000))
true
9a7f00adcc48b8f31f768f495178aac5819f3b32
mmlakin/morsels
/count_words/count.py
483
4.28125
4
#!/usr/bin/env python3 """count.py - Take a string and return a dict of each word in the string and the number of times it appears in the string""" from string import punctuation as punctuationmarks import re def count_words(line: str) -> dict: """ Use re.findall to return a list of words with apostrophes included """ regex=r"[\w']+" linewords = re.findall(regex, line.lower()) return { word:linewords.count(word) for word in set(linewords) }
true
fedb1fb0c6cd6ec4bb814ae119317c47dae223ad
ZergOfSwarm/test
/otslegivaet_knopki_mishi22.py
1,186
4.4375
4
from tkinter import * #initialize the root window root = Tk() ############################# # 7. Click action ############################# # 1 def printHello(): print("Hello !") # Once the button is clicked, the function will be executed button_1 = Button(root, text="Click me !", command = printHello) button_1.pack() #BINDING FUNCTIONS # http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm # 2 def callback(event): print("clicked at", event.x, event.y) # Binding just means that we bind a function to an event that happens with a widget button_2 = Button(root, text="Click it") button_2.bind("<Button-1>", callback) button_2.pack() def leftClick(event): print("Left Click") def rightClick(event): print("Right Click") def scroll(event): print("Scroll") def leftArrow(event): print("Left Arrow key") def rightArrow(event): print("Right Arrow key") # Set the window size root.geometry("500x500") root.bind("<Button-1>", leftClick) root.bind("<Button-2>", scroll) root.bind("<Button-3>", rightClick) root.bind("<Left>", leftArrow) root.bind("<Right>", rightArrow) # Keep the window runing until user closes it root.mainloop()
true
ec3896f603ea5179d441f188ad908852a736693e
andrewcollette/sprint_tutorial
/sprint_tutorial/compute.py
329
4.125
4
""" Module to compute stuff """ def my_sum(x, y): """ Compute the sum of 2 numbers """ return x + y def my_power(a, n): """ Compute a^n """ pow = a for i in range(n-1): pow = pow*a return pow def my_root(a, n=2): """ Compute the nth root of a """ res = a**(1.0/n) return res
false
8957d8156bc7f65ea0df95bab71c205aa3978262
OscarH00182/Python
/Stack.py
1,067
4.34375
4
""" Stack: This is how we create a stack, we create a simple class for it and create its functions to handle values being pass to it """ class Stack: def __init__(self):#constructor self.stack = [] #we create an array named stack to handle the stack self.size = -1 def Push(self,datavalue):#This is what adds values to the stack self.stack.append(datavalue)#we add the value to the stack self.size +=1 def Pop(self): print("Value that was popped: ",self.stack.pop()) self.size -=1 if(self.size == -1 ): print("The stack is empty") def Peek(self):#We create peek to look at the first value of the stack return self.stack[0] def Size(self): return self.size stackOne = Stack() stackOne.Push(66) stackOne.Push(77) stackOne.Push(88) stackOne.Push(99) print("First Value of stack: ",stackOne.Peek()) stackOne.Pop() stackOne.Push(11) print("Size of Stack: ",stackOne.Size()) print("\nPopping Entire Stack") for i in range(stackOne.Size()+1): stackOne.Pop()
true
b6fadc89174f195651271f86522c39c9d0ec444b
OscarH00182/Python
/ChapterTwo.py
2,094
4.5625
5
name = "Oscar Hernandez" print(name.title()) print("Upper Function: ",name.upper()) print("Lower Function: ",name.lower()) firstName = "Oscar" lastName = "Hernandez" fullName = firstName + " " +lastName print("Combinding Strings: ",fullName) #rstrip Function languagee = "Python " language = "Python "#Notice: "Python " has a space vs "Python" #rstrip function drops the extra space print("\nReducing Space",language.rstrip()+"|") print("No Reducing Space",language+"|") print("\nExcerises 2-3 to 2-7") """ Store a person’s name in a variable, and print a message to that person. Your message should be simple, such as, “Hello Eric, would you like to learn some Python today?” """ name = "Eric" print("2-3") print("Hello " + name +",would you like to learn some Python today?") """ Store a person’s name in a variable, and then print that person’s name in lowercase, uppercase, and titlecase """ print("\n2-4") name = "Jack" print(name.lower()) print(name.upper()) print(name.title()) """ Find a quote from a famous person you admire. Print the quote and the name of its author. Your output should look something like the following, including the quotation marks: Albert Einstein once said, “A person who never made a mistake never tried anything new.” """ print("\n2-5") print("Albert Einstein once said, “A person who never made a mistake never tried anything new.”") #Skipped 2-6: Too easy """" Store a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, "\t" and "\n", at least once. Print the name once, so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip() """ print("\n2-7") name = " Oscar " print(name) print("\n",name)#new space print("\t",name)#tab print(name.lstrip())#left whitespace print(name.rstrip())#right whitespace print(name.strip())#both whitespace #str():converts int/float/etc to string so accept into another string age = 21 message = "Happy " + str(age) + "st birthday!" print(message)
true
9a5dd11136eb707a020db2e3dc97f0b03e91c891
jpbayonap/programs
/py_prog/decimals1.py
2,195
4.21875
4
#the objective of this programm is to compkute the division of one by a random integer given by the user #for repeated decimals the programm will print the repeated digits after reaching the first repetition from time import sleep # used for defining the intervals of time between each operation d= int(input("Input a denominator:")) print(f"1/{d} is computed") myli =[0]*(d+1) #this array will play a critical role in the computation #for any integer d , when we compute the division of it with one by recusion . mel =[0]*(d+1) count= 0 # tell us the number of operations carried out done = False # condition for finishing the computation x=1 # first step of the division i.e. how many times is d contained in one 0 e = d//10 s = "" while not done: x= x*10 #because the first quotient is zero we increase it by multiplying it by ten quotient= x//d #how many integer times can d fit in the increased value of x remainder= x%d # units needed to add to the product of quotient and d for getting x print(quotient) myli[count]= quotient #fill the array with the computed quotient mel[count] =remainder count += 1 #tells the program to move towards the next operation print(f"{count}:{quotient}({remainder})") #show the user the result of the operation sleep(0.5) # convert the array into a string in order to get the appropiate enviroment for printing the repeated decimals anwers if remainder ==0: # if there is no units needed to add in the computation , the division is over and it yields a finite answer done= True # stop the computation else: # for other case bring the computation proccess to the next step by changing the value of the expanded value with the remainder of the #previous step x =remainder if any([b == remainder for b in mel[:count] ]) : #when computing the division of one and an integer the values admitted for quotient are restricted #to 1,...,d . hence if in the computation there is two values of quotient which coincide the entries of myli between them will be repeated done= True my= [str(a)for a in myli] print("the result is") print(''.join(my[:count]) + '('+''.join(my[my.index(my[count-1]):count])+')')
true
b0679af54f904e6f16b72b0dbe786875b55c9778
martinvedia/app-docs
/codedex/enter_pin.py
243
4.21875
4
# This program accept a correct Bank pink value 1234 print("BANK OF CODÉDEX") pin = int(input("Enter your PIN: ")) while pin != 1234: pin = int(input("Incorrect PIN. Enter your PIN again: ")) if pin == 1234: print("PIN accepted!")
true
10a3ba409bc987fe4bd08cb7df222316812e28cc
joesmall37/Algorithms
/Recursion/call_stack_fibonacci.py
263
4.125
4
# define the fibonacci() function below... def fibonacci(n): # base cases if n == 1: return n if n == 0: return n # recursive step print("Recursive call with {0} as input".format(n)) return fibonacci(n - 1) + fibonacci(n - 2) fibonacci(5)
false