blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
73febf1c1bf6a8d35dc50afbedd76b2df8bb2da4 | RohanNankani/Computer-Fundamentals-CS50 | /Python/mad_lib_theatre.py.py | 2,357 | 4.25 | 4 | # Author: Rohan Nankani
# Date: November 11, 2020
# Name of Program: MadLibTheater
# Purpose: To create a mad lib theater game which ask user for input, store their input using list, and print the story.
# Intializing the list
grammar = []
# List of prompts that describe the category of the next word
# to be substituted in the story
prompts = [
"an adjective: ",
"an another adjective: ",
"a type of bird: ",
"a room in a house: ",
"a past tense verb: ",
"a verb: ",
"a name: ",
"a noun: ",
"a type of liquid: ",
"a verb ending in -ing: ",
"a plural part of the body: ",
"a plural noun: ",
"a verb ending in -ing: ",
"a noun: "
]
# Function to ask user for input for each of the prompts
def grammar_input():
for prompt in prompts:
grammar.append(input("Enter " + prompt))
# Function to print the story with the user's input
def story_template():
print("It was a " + grammar[0] + ", cold November day.")
print("")
print("I woke up to the " + grammar[1] + " smell of " + grammar[2] + " roasting in the " + grammar[3] + " downstairs.")
print("")
print("I " + grammar[4] + " down the stairs to see if I could help " + grammar[5] + " the dinner.")
print("")
print("My mom said, 'See if " + grammar[6] + " needs a fresh " + grammar[7] + ".'")
print("")
print("So I carried a tray of glasses full of " + grammar[8] + " into the " + grammar[9] + " room.")
print("")
print("When I got there, I couldn't believe my " + grammar[10] + "! There were " + grammar[11] + " " + grammar[12] + " on the " + grammar[13] + "!")
# Greeting the user at the beginning of program
print("Welcome to the Mad Lib Theater!".center(53))
print("")
print("I want you to give me the first word that comes to your mind for described category.")
print("")
print("Are you ready?")
print("")
input("Press enter to continue: ")
print("".center(48, "-"))
# Calling the grammar input function to get input from user
grammar_input()
print("")
# Calling story template function to print the story
story_template()
# Using while loop to ask the user if they want to play again
while True:
print("")
userResponse = input("Do you want to play again (Y/N)? ")
if userResponse == "Y":
print("".center(48, "-"))
grammar = []
grammar_input()
print("")
story_template()
else:
print("".center(48, "-"))
print("Thank you for playing!".center(53))
break | true |
17856f57c910a767dfc433a16fbe31b365e3e870 | sp3arm4n/OpenSource-Python | /assignment_01/src/p10.py | 364 | 4.46875 | 4 | # step 1. asks the user for a temperature in Fahrenheit degrees and reads the number
number = float(input("please enter Fahrenheit temperature: "))
# step 2. computes the correspodning temperature in Celsius degrees
number = (number - 32.0) * 5.0 / 9.0
# step 3. prints out the temperature in the Celsius scale.
print("Celsius temperature is %f"%(number)) | true |
45497bbe4e6c706c4f79e8be82bc586cc78331e3 | DarkCodeOrg/python-learning | /list.py | 288 | 4.21875 | 4 | #!/bin/python python3
""" creating an empty list and adding elements to it"""
list = []
list.append(200)
list.append("salad")
list.append("maths")
print(list)
print("this is your initial list")
new = input("Enter something new to the list: ")
list.append(new)
print(list)
| true |
192af36327e7984ba16c57dac945182bc92de21a | 2u6z3r0/automate-boaring-stuff-with-python | /inventory.py | 1,171 | 4.1875 | 4 | #!/usr/bin/python3
#chapter 5 exercise
stuff = {'gold coin': 42, 'rope': 1}
def displayInventory(stuff):
'''
:param stuff: It takes a dictionary of item name as key and its quantity as value
:return: Nothing, but it prints all items and respective quantity and total quantity(sum of all itmes qty)
'''
print("Inventory:")
totalCount = 0
for k, v in stuff.items():
print(v,k)
totalCount += v
print('Total number of items ' + str(totalCount))
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addItems):
'''
This function takes existing inventoy(dict) and new items to be added to inventory.
:param inventory: existing inventory(dictionay of item_name:qty)
:param addItems: list of items to be added to existing inventory
:return: updated inventory dict by adding new items or if item exists already, qty will be increased by 1
'''
for item in addItems:
inventory.setdefault(item, 0) #initialize qty to 0 if item does not exist already
inventory[item] += 1
addToInventory(stuff, dragonLoot)
displayInventory(stuff)
| true |
a767fd70f5fedac106f3aca0b8b48b41d38a2a8e | NATHAN76543217/BtCp_D00 | /ex03/count.py | 1,005 | 4.28125 | 4 | import string
def text_analyzer(*text):
"""
This function counts the number of upper characters,
lower characters, punctuation and spaces in a given text.
"""
if len(text) > 1:
print("ERROR")
return
if len(text) == 0 or isinstance(text[0], str) == 0:
text = []
text.append(input("What is the text to analyse?\n>> "))
ponctu_list = string.punctuation
nb_upper = 0
nb_lower = 0
nb_ponct = 0
nb_spaces = 0
letters = 0
for char in text[0]:
letters += 1
if char == ' ':
nb_spaces += 1
elif char.isupper():
nb_upper += 1
elif char.islower():
nb_lower += 1
elif char in ponctu_list:
nb_ponct += 1
print("The text contains {} characters:" .format(letters), '\n')
print("-", nb_upper, "upper letters\n")
print("-", nb_lower, "lower letters\n")
print("-", nb_ponct, "punctuation marks\n")
print("-", nb_spaces, "spaces")
| true |
cf2553bafad225366a58d08ab9a8edc6b4daa9d2 | Ayush900/django-2 | /advcbv2/basic_app/templates/basic_app/pythdjango/oops.py | 807 | 4.40625 | 4 | #class keyword is used to create your own classes in python ,just like the sets,lists,tuples etc. .these classes are also known as objects and this type of programming involving the creation of your own classes or objects is known as object oriented programming or oops....#
class football_team: #Here the new object created is the football_team which contain an attribute which tells about the league of the football team #
def __init__(self,league,pos):
self.league=league
self.pos=pos
arsenal=football_team(league = 'bpl',pos=4)
barca=football_team(league = 'la_liga',pos=1)
print('Arsenal play in {} and its position in league is {}'.format(arsenal.league,arsenal.pos))
print('FC Barcelona play in {} and its position in league is {}'.format(barca.league,barca.pos)) | true |
e98ba84add2519f4c3858cef105c6e5de54f57fb | jonathangriffiths/Euler | /Page1/SumPrimesBelowN.py | 612 | 4.15625 | 4 | __author__ = 'Jono'
from GetPrimeN import isPrime
#basic method to estimate how long it will take like this
def get_sum_primes_below_n(n):
sum=2
for i in range(3, n+1, 2):
if isPrime(i):
sum+=i
return sum
print get_sum_primes_below_n(2000000)
#note: Erastosthenes seive useful for speed
#1. Make a list of all numbers from 2 to N.
#2. Find the next number p not yet crossed out. This is a prime. If it is greater than √N, go to 5.
#3. Cross out all multiples of p which are not yet crossed out.
#4. Go to 2.
#5. The numbers not crossed out are the primes not exceeding N
| true |
3dbaed02def20cc1c27d7ed07cce6be97942b78b | za-webdev/Python-practice | /score.py | 425 | 4.25 | 4 |
#function that generates ten scores between 60 and 100. Each time a score is generated,function displays what the grade is for a particular score.
def score_grade():
for x in range(1,11):
import random
x=(random.randint(60,100))
if x >60 and x<70:
z="D"
elif x>70 and x<80:
z="C"
elif x>80 and x<90:
z="B"
elif x>90 and x<100:
z="A"
print "Score:{},Your grade is {}".format(x,z)
score_grade()
| true |
092b2594f9159f72119349177487a3c0ffe8ebde | kronecker08/Data-Structures-and-Algorithm----Udacity | /submit/Task4.py | 1,306 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
call_outgoing = []
call_incoming = []
for i in calls:
call_outgoing.append(i[0])
call_incoming.append(i[1])
call_outgoing = set(call_outgoing)
call_incoming = set(call_incoming)
num_texts = []
for i in texts:
num_texts.append(i[0])
num_texts.append(i[1])
num_texts = set(num_texts)
telemarketers = []
for i in call_outgoing:
if i in call_incoming:
continue
elif i in num_texts:
continue
else:
telemarketers.append(i)
telemarketers = sorted(telemarketers)
print("These numbers could be telemarketers: ")
for i in telemarketers:
print(i)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
| true |
d3760baba77aa112d2860cbeed1ef56f378347be | iamrobinhood12345/economic-models | /base-model.py | 2,642 | 4.21875 | 4 | # Basic Flow of Money Model
import sys
MODEL_NUMBER = 1
INPUT_STRING = """
MAIN MENU:
Input amount to loan (integer).
Input 'q' to quit program.
"""
EXIT_STRING = """
Thank you, goodbye!
By Ben Shields <https://github.com/iamrobinhood12345>
copyright 2017
"""
def issue_money(val, money_circulating, debt_to_central_bank, contracts):
"""Issue money."""
money_circulating[0] += val
print("Issuing " + str(val) + " units")
if val != 0:
debt_to_add = val + 1
debt_to_central_bank[0] += debt_to_add
print("Adding " + str(debt_to_add) + " to total debt to central bank")
contract = debt_to_add
contracts.append(contract)
print("Creating contract for " + str(contract) + " units")
else:
print("No contract created, no money issued.")
def remove_debt(money_circulating, debt_to_central_bank, contracts):
"""Remove debt."""
for i in range(len(contracts)):
if money_circulating[0] >= contracts[i]:
print("Paying off debt of contract of " + str(contracts[i]) + " units")
money_circulating[0] -= contracts[i]
print("Removing " + str(contracts[i]) + " units from money circulating")
debt_to_central_bank[0] -= contracts[i]
print("Removing " + str(contracts[i]) + " units from debt to central bank")
print("Removing contract of " + str(contracts[i]) + " units")
del contracts[i]
break
def main():
"""Handle menus and input."""
money_circulating = [0]
debt_to_central_bank = [0]
contracts = []
print("""
Economic Model """ + str(MODEL_NUMBER) + """
Turn based flow of money model.
Constituents:
Central Bank
Other (Entities that do not issue money)
""")
while True:
loan = input(INPUT_STRING)
try:
loan_val = int(loan)
except ValueError:
if loan == 'q':
print(EXIT_STRING)
sys.exit()
print("WARNING: Loan input must be an integer!")
continue
issue_money(loan_val, money_circulating, debt_to_central_bank, contracts)
remove_debt(money_circulating, debt_to_central_bank, contracts)
print("Money circulating: " + str(money_circulating[0]))
print("Total debt to central bank: " + str(debt_to_central_bank[0]))
print("Contracts: " + str(contracts))
if __name__ == "__main__":
"""Entry point. Calls main function."""
main()
| true |
a868af86d0102fe2aafd0b10782840ecad86768e | KC1988Learning/TkinterLearning | /tutorial/grid.py | 2,025 | 4.15625 | 4 | import tkinter as tk
from tkinter import ttk
from window import set_dpi_awareness
def greet():
# add strip() to remove whitespace in string
print(f"Hello {user_name.get().strip() or 'World'}! How are you?")
set_dpi_awareness()
root = tk.Tk()
root.title("Greeting App")
# configure row and column property of the root window
# weight = 0, column/row takes up size of the content
# weight is relative, if one is 0 another is 1, 1 means taking up all space
# if one is 2 another 1, means the first one occupies twice as much space
root.columnconfigure(index=0, weight=1)
user_name = tk.StringVar()
user_age = tk.IntVar()
# padding = (left, top, right, bottom)
entry_frame = ttk.Frame(root, padding=(20,10, 20, 0))
# grid will place the element on the first available row in the first column
# sticky = EW: makes the column 'sticks' to the edge of the root window
entry_frame.grid(row=0, column=0, sticky='EW')
# column 0 and 1 in entry_frame as wide as needed by the content
entry_frame.columnconfigure(index=0, weight=0)
entry_frame.columnconfigure(index=1, weight=0)
user_label = ttk.Label(entry_frame, text="Name: ")
# weight=0: takes as space as needed by the content
user_label.grid(row=0, column=0, sticky='EW')
user_entry = ttk.Entry(entry_frame, width=15, textvariable=user_name)
user_entry.grid(row=0, column=1, sticky='EW')
user_entry.focus()
# padding = (horizontal, vertical)
btn_frame = ttk.Frame(root, padding=(20, 10))
# sticky='EW' makes the row sticks to the root window
btn_frame.grid(row=1, column=0, sticky='EW')
# make the first column takes up one portion of the width of btn_frame
btn_frame.columnconfigure(index=0, weight=1)
greet_btn = ttk.Button(btn_frame, text="Greet", command=greet)
# sticky = 'EW' makes the buttom stick to the boundary of the first column
greet_btn.grid(row=0, column=0, sticky='EW')
btn_frame.columnconfigure(index=1, weight=1)
quit_btn = ttk.Button(btn_frame, text="Quit", command=root.destroy)
quit_btn.grid(row=0, column=1, sticky='EW')
root.mainloop()
| true |
24e335ecf0a79e60026e0a3f41f5277b7ab839ef | tikitae92/Python-IS340 | /Ch4/whileCheckout2.py | 1,011 | 4.15625 | 4 | #example of sale transaction in a store
#cashier doesnt know the # of items in a cart
#input price
#add to total and display in the while loop
#starts sale transaction and ends it when no items are left
#keep track of # of items in customer shopping cart
#print total # of items
#stop when user enter -1
#if negative (<-1) ask user to try again
price=0
total=0
i=1
#one while loop
#sentinel (in this example negative number will stop loop)
while price !=-1:
#display item number
price=float(input("Enter price for item #%d (enter -1 to stop): " %i))
#one method of ending the loop
#if price<0:
# print("End of sale transaction")
# break
if price >=0:
i=i+1
total=total+price
print("Total is $%.2f" %total)
elif price==-1:
i=i-1
print("Number of items:", i)
print("Total is $%.2f" %total)
break
else:
print("Invalid entry, please try again")
| true |
fbf74dfb475b7f1d3ee5e7a247c6c40b3a615d0e | camarena2/camarena2.github.io | /secretworld.py | 800 | 4.25 | 4 |
print(" Welcome to the Secret Word Game. Guess a letter in the word, then press enter:")
from random import choice
word = choice(["table", "chair", "bottle", "plate", "parade", "coding", "teacher", "markers", "phone", "grill", "friends", "fourth", "party"])
guessed = []
while True:
out = ""
for letter in word:
if letter in guessed:
out = out + letter
else:
out = out + "_"
if out == word:
print("Congrats! You guessed correctly:", word)
break
print("Guess a letter:", out)
guess = input()
if guess in guessed:
print("You already guessed this letter! Try again!")
elif guess in word:
print("Yay! Good Job!")
guessed.append(guess)
else:
print("Try Again!")
print()
| true |
041dbf38767b723327ebf197bba3cf02bbf10a5b | raymccarthy/codedojo | /adam/firstWork/adam.py | 461 | 4.21875 | 4 | calculator = "Calculator:"
print(calculator)
one = input("Enter a number: ")
two = input("Enter another number: ")
three = input("Would you like to add another number?: ")
if three == "yes" or three == "Yes":
thre = input("What would you like that number to be: ")
answer = float(one) + float(two) + float(thre)
print("The answer to you sum is" , answer,)
else:
answer = float(one) + float(two)
print("The answer to you sum is" , answer,)
| true |
a7ea7d24373085e6822da0ff924304b434ed8d52 | pasanchamikara/ec-pythontraining-s02 | /data_structures/tuples_training.py | 507 | 4.46875 | 4 | # Tuples are unchangeable once created, ordered and duplicates are allowed.
vegetable_tuple = ("cucumber", "pumkin", "tomato")
# convert his to a set and assign to vegetable_set
# get the lenght of the tuple vegetable_tuple
fruit_tuple = ("annas", )
# get the result of print(type(fruit_tuple)) with and without commas
# print only the last 2 values of the vegetable tuple
# negative indices
# change tuple values using casting to lists add new values and remove old values , convert back to lists
| true |
32d6e902356eeec9d4cfcab5bd4f1c8d4398dea3 | JoshuaR830/HAI | /Lab 1/Excercise 4/ex9.py | 272 | 4.28125 | 4 | words = ["This", "is", "a", "word", "list"]
print("Sorted: " + sorted(words))
print("Original: " + words)
words.sort()
print("Original: " + words)
# sorted(words) prints does not change the order of the original list
# words.sort() changes the original order of the list | true |
0fdac6ba0c12be57e9d07c067ce5be5042971876 | BurlaSaiTeja/Python-Codes | /Lists/Lists05.py | 342 | 4.21875 | 4 | """
Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).
"""
def sqval():
l=list()
for i in range(1,31):
l.append(i**2)
print(l[:5])
print(l[-5:])
sqval()
"""
Output:
[1, 4, 9, 16, 25]
[676, 729, 784, 841, 900]
"""
| true |
e9ffcaced1121fa20de7c5f4df840bc8821a3c58 | anc1revv/coding_practice | /leetcode/easy/letter_capitalize.py | 490 | 4.375 | 4 | '''
Using the Python language, have the function LetterCapitalize(str) take the str
parameter being passed and capitalize the first letter of each word.
Words will be separated by only one space.
'''
def letter_capitalize(input_str):
list_words = input_str.split(" ")
for word in list_words:
for i in range(len(word)):
if i == 0:
return ' '.join(list_words)
def main():
input_str = "hello bye"
print letter_capitalize(input_str)
if __name__ == "__main__": main() | true |
2b3c1bc9399793ce14fd920e8dfda39062655465 | Swastik-Saha/Python-Programs | /Recognize&Return_Repeated_Numbers_In_An_Array.py | 472 | 4.1875 | 4 | def repeated():
arr = []
length = int(raw_input("Enter the length of the array: "))
for i in range(0,length):
arr.append(int(raw_input("Enter the elements of an array: ")))
arr.sort()
count = 0
for i in range(0,length):
print "The number taken into consideration: " + str(i)
print "The number of occurences of the number above: " + str(arr.count(i))
| true |
971881bad3c2980c5c2875ff07d1ac50d2a45299 | wojtekminda/Python3_Trainings | /SMG_homework/10_2_Asking_for_an_integer_number.py | 2,299 | 4.53125 | 5 | '''
Write input_int() function which asks the user to provide an integer number
and returns it (as a number, not as a string). It accepts up to 3 arguments:
1. An optional prompt (like input() built-in function).
2. An optional minimum acceptable number (there is no minimum by default).
3. An optional maximum acceptable number (there is no maximum by default).
The function keeps asking the user until she provides a well-formed integer number within range.
Example usage of the function:
a = input_int("Enter an integer: ")
b = input_int("Enter a positive integer: ", 1)
c = input_int("Enter an integer not greater than 8: ", largest=8)
d = input_int("Enter an integer (4..8): ", 4, 8)
print("Provide another integer (4..8):")
e = input_int(smallest=4, largest=8)
print("Your numbers multiplied by 2:", a * 2, b * 2, c * 2, d * 2, e * 2)
Example session with the script:
Enter an integer: cake
Enter an integer: 3.4
Enter an integer: -5
Enter a positive integer: -10
Enter a positive integer: 0
Enter a positive integer: 1000
Enter an integer not greater than 8: 1000
Enter an integer not greater than 8: 7
Enter an integer (4..8): 1
Enter an integer (4..8): 4
Provide another integer (4..8):
9
8
Your numbers multiplied by 2: -10 2000 14 8 16
'''
def input_int(prompt='', smallest=None, largest=None):
number = input(prompt)
while number:
try:
number = int(number)
if smallest == None and largest == None:
return number
elif largest == None:
if not number < smallest:
return number
elif smallest == None:
if not number > largest:
return number
else:
if not (number < smallest or number > largest):
return number
except ValueError as exc:
print(exc)
number = input(prompt)
a = input_int("Enter an integer: ")
print(a)
b = input_int("Enter a positive integer: ", 1)
print(b)
c = input_int("Enter an integer not greater than 8: ", largest=8)
print(c)
d = input_int("Enter an integer (4..8): ", 4, 8)
print(d)
print("Provide another integer (4..8):")
e = input_int(smallest=4, largest=8)
print("Your numbers multiplied by 2:", a * 2, b * 2, c * 2, d * 2, e * 2)
| true |
09c024e3dfde0a07e652fd8bfb02357b736bc1ac | wojtekminda/Python3_Trainings | /SMG_homework/01_3_Should_I_go_out.py | 1,319 | 4.15625 | 4 | '''
A user is trying to decide whether to go out tonight.
Write a script which asks her a few yes-no questions and decides for her according to the following scheme:
[NO SCHEME]
'''
raining = input("Is it raining? ")
if raining == "yes":
netflix = input("Is the new episode on Netflix out already? ")
if netflix == "yes":
print("Stay home")
elif netflix == "no":
umbrella = input("Damn it. Do you have an umbrella? ")
if umbrella == "yes":
drinking = input("Do you feel like drinking tonight? ")
if drinking == "yes":
print("Go, then!")
elif drinking == "no":
sure = input("Yeah, right. You sure? ")
if sure == "yes":
print("What a drag! Stay home.")
elif sure == "no":
print("You gotta go out.")
elif umbrella == "no":
sugar = input("Are you made of sugar? ")
if sugar == "yes":
print("Being moody? Go to sleep, honey")
elif sugar == "no":
print("Dress up and leave")
elif raining == "no":
reason = input("Do you need another reason? ")
if reason == "yes":
print("World sucks. Go out!")
elif reason == "no":
print("Are you still here?")
| true |
2b11221a58ddff3101a95aa892b0ed5ab4997f80 | 5h3rr1ll/LearnPythonTheHardWay | /ex15.py | 1,076 | 4.375 | 4 | #importing the method argv (argument variable) from the library sys into my code
from sys import argv
"""now I defining which two arguments I want to have set while typing the
filename. So you are forced to type: python ex15.py ArgumentVariable1
ArgumentVariable2"""
script, filename = argv
#since the filename is given at the comandline, open just opens the named file
#and pass it to the variable txt
txt = open(filename)
#Just writes a line of text
print "Here's your file %r:" % filename
#looks like you can't just print the content from the file, you also need to
#.read() to print it out
print txt.read()
#just writes a line of text
print "Type the filename again:"
#getting a input from the user and saves it into the variable "file_again"
file_again = raw_input("> ")
#open the file with the givin name and saves it's content into the variable
#text_again
txt_again = open(file_again)
#prints out the content which was givin to the variable "txt_again". Spent
#attation to the .read()!Won't work without it!
print txt_again.read()
txt.close()
txt_again.close()
| true |
a4877ed3f2bb5586e5143b85119eeb1f75efeb6c | kmjawadurrahman/python-interactive-mini-games | /guess_the_game.py | 2,176 | 4.40625 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
which_range = ""
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global guess_count
global which_range
global secret_number
guess_count = 7
which_range = 0
secret_number = random.randrange(0,100)
print "New game. Range is from 0 to 100"
print "Number of guesses remaining is", guess_count
print ""
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
new_game()
def range1000():
# button that changes the range to [0,1000) and starts a new game
global guess_count
global which_range
global secret_number
guess_count = 9
which_range = 1
secret_number = random.randrange(0,1000)
print "New game. Range is from 0 to 1000"
print "Number of guesses remaining is", guess_count
print ""
def input_guess(guess):
# main game logic goes here
global guess_count
guess_count -= 1
guess_ = int(guess)
print "Guess was", guess_
print "Number of guesses remaining is", guess_count
if guess_ < secret_number:
print "Higher"
print ""
elif guess_ > secret_number:
print "Lower"
print ""
else:
print "Correct"
print ""
if which_range:
range1000()
else:
range100()
if guess_count <= 0:
print "You ran out of guesses. The number was", secret_number
print ""
if which_range:
range1000()
else:
range100()
# create frame
f = simplegui.create_frame("Guess the number", 200, 200)
# register event handlers for control elements and start frame
f.add_button("Range is [0, 100)", range100, 200)
f.add_button("Range is [0, 1000)", range1000, 200)
f.add_input("Enter a guess", input_guess, 200)
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
| true |
f95c90cefc62f8a1531c8a0d32ddc4e91a3dbc86 | Otumian-empire/python-oop-blaikie | /05. Advanced Features/0505.py | 604 | 4.15625 | 4 | # With context
# open file and close it
fp = open('Hello.txt', '+a')
print('I am a new text file', file=fp)
fp.close()
# We don't have to close it
with open('Hello.txt', '+a') as op:
print('I am a new line in the Hello.txt file', file=op)
# seems like not a valid python3 code
# class MyWithClass:
# def __enter__(self):
# print("Entered the class")
# def __exit__(self, type, value, traceback):
# print("Exit the class")
# def say_hello(self):
# print('Hello')
# with MyWithClass as cc:
# c = cc()
# c.say_hello()
# print("After the with block") | true |
566946645bd44e94bafe916c9e2f0aeadd4b1cb5 | mjayfinley/Conditions_and_Functions | /EvenOdd/EvenOdd.py | 220 | 4.3125 | 4 | numberInput = int(input("Please enter a number: "))
if numberInput == 0:
print("This number is neither odd or even.")
elif numberInput %2 == 0:
print("This number is even")
else:
print("This number is odd")
| true |
08a27190e2210d7bedda769c93c6a9d710cb474e | BarDalal/Matrices--addition-and-multiplication | /AddMinPart.py | 1,148 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Name: Bar Dalal
Class: Ya4
The program adds the common parts of two matrices.
The sum's size is as the common part's size.
"""
import numpy as np
def MinAddition(a, b):
"""
The function gets two matrices.
The function returns the sum of the common parts of the matrices (minimum size).
"""
if (a.shape[0] >= b.shape[0]):
x= b.shape[0]
else:
x= a.shape[0]
# x is the minimum number of rows from the two matrices
if (a.shape[1] >= b.shape[1]):
y= b.shape[1]
else:
y= a.shape[1]
# y is the minimum number of columns from the two matrices
c= np.zeros([x,y], dtype = int) # the sum of the common parts of the matrices
for row in range(x):
for column in range (y):
c[row, column]= a[row, column] + b[row, column]
return c
def main():
arr = np.array([[1, 2, 3, 7], [4, 5, 6, 90], [7, 8, 9, 6]])
arr2= np.array([[10, 20, 50],[30, 40, 20], [1, 2, 3], [6, 8, 0]])
result= MinAddition(arr, arr2)
print (result)
if __name__ == "__main__":
main()
| true |
afa5e2e385ff2086f25c471ac148c7032980d250 | nighatm/W19A | /app.py | 1,004 | 4.1875 | 4 | import addition
import subtraction
import multiplication
import divide
print("Please choose an operation")
print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Division")
try:
userChoice = int(input ("Enter Choice 1 or 2 or 3 or 4 : "))
except:
print ('You have entered an invalid option.')
else:
if userChoice in ('1', '2', '3', '4' ):
number1 = int(input("Enter first number: "))
number2 = int(input ("Enter second number: "))
if (userChoice == '1'):
print( "Result is: " str(addition.add(number1, number2)))
elif (userChoice == '2'):
print("Result is: " str(subtraction.subtract(number1, number2)))
elif (userChoice == '3'):
print ("Result is: " str(multiplication.multiply(number1, number2)))
elif (userChoice == '4'):
print("Result is: " str(divide.division(number1,number2)))
else:
print("Invalid user input")
| true |
cfd8276cedbf35d4542948135e6c68c986d00c89 | Coadiey/Python-Projects | /Python programs/PA7.py | 2,214 | 4.15625 | 4 | # Author: Coadiey Bryan
# CLID: C00039405
# Course/Section: CMPS 150 – Section 003
# Assignment: PA7
# Date Assigned: Friday, November 17, 2017
# Date/Time Due: Wednesday, November 22, 2017 –- 11:55 pm
#Description: This program is just a simple class setup that changes the output into a string based on the input using dictionaries
#
# Certification of Authenticity:
# I certify that this assignment is entirely my own work.
import random
class Card():
def __init__(self,suit,rank):
self.__rank = rank
self.__suit = suit
def getModSuit(self):
suit = self.__suit
dictionary = {0:"Hearts",1:"Spades",2:"Diamonds",3:"Clubs"}
if suit in dictionary:
return dictionary[suit]
else:
return "ERROR"
def getModRank(self):
rank = self.__rank
dictionary = {1:"Ace",2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'10',11:'Jack',12:'Queen',13:'King'}
if rank in dictionary:
return dictionary[rank]
else:
return "ERROR"
def getSuit(self):
return self.__suit
def getRank(self):
return self.__rank
def setSuit(self,suit):
self.__suit = suit
def setRank(self,rank):
self.__rank = rank
def main():
card1 = Card(2,12) # this will create a card that is a Queen of Diamonds
rank = str(card1.getModRank())
suit = str(card1.getModSuit())
print("Card #1: %s of %s" % (rank,suit))
suitgiver = random.randint(0,3) # these 3 lines will create a “random” card from the deck
rankgiver = random.randint(1,13)
card2 = Card(suitgiver,rankgiver)
rank2 = card2.getModRank()
suit2 = card2.getModSuit()
print("Card #2: %s of %s" % (rank2, suit2))
suitgiver2 = random.randint(0,3) # these 3 lines will create a “random” card from the deck
rankgiver2 = random.randint(1,13)
card3 = Card(suitgiver2,rankgiver2)
rank3 = card3.getModRank()
suit3 = card3.getModSuit()
print("Card #2: %s of %s" % (rank3, suit3))
if __name__ =='__main__':
main() | true |
96672006f4ee0b8ce9cb023f0f14c9a5eb385b71 | EmreTekinalp/PythonLibrary | /src/design_pattern/factory_pattern.py | 1,791 | 4.1875 | 4 | """
@author: Emre Tekinalp
@contact: e.tekinalp@icloud.com
@since: May 28th 2016
@brief: Example of the factory pattern.
Unit tests to be found under:
test/unit/test_factory_pattern.py
"""
from abc import abstractmethod
class Connection(object):
"""Connection class."""
@abstractmethod
def description(self):
"""description function which needs to be overriden by the subclass."""
pass
# end def description
# end class Connection
class OracleConnection(Connection):
"""OracleConnection class."""
def description(self):
"""description function."""
return 'Oracle'
# end def description
# end class OracleConnection
class SqlServerConnection(Connection):
"""SqlServerConnection class."""
def description(self):
"""description function."""
return 'SQL Server'
# end def description
# end class SqlServerConnection
class MySqlConnection(Connection):
"""MySqlConnection class."""
def description(self):
"""description function."""
return "MySQL"
# end def description
# end class MySqlConnection
class Factory(object):
"""Factory base class."""
def __init__(self, object_type):
"""Initialize Computer class."""
self._object_type = object_type
# end def __init__
def create_connection(self):
"""create connection function."""
if self._object_type == 'Oracle':
return OracleConnection()
elif self._object_type == 'SQL Server':
return SqlServerConnection()
elif self._object_type == 'MySQL':
return MySqlConnection()
else:
return Connection()
# end if return connection objects
# end def create_connection
# end class Computer
| true |
f9ff6527ee3c680cefc70bb37a49ba2465005b51 | kirushpeter/flask-udemy-tut | /python-level1/pypy.py | 2,426 | 4.25 | 4 | """
#numbers
print("hello world")
print(1/2)
print(2**7)
my_dogs = 2
a = 10
print(a)
a = a + a
print(a)
puppies = 6
weight = 2
total = puppies * weight
print(total)
#strings
print(len("hello"))
#indexing
mystring = "abcdefghij"
print(mystring[-1])
print(mystring[0:7:2])#start is included start stop and step
print(mystring[::3])
"""
"""
mystring = "hello world"
print(mystring.split())
"""
"""
username = "sammy"
color = "blue"
print("the {} favourite is {}".format(username,color))
print(f"The {username} chose {color}" )
#lists
#they ordered sequences that can hold a number of objects
myList = [1,2,3]
print(len(myList))
mylist = ['w','e','f','g']
mylist.append('k')
print(mylist)
#dictionaries
d = {'key1':'value1','key2':'value2'}
print(d)
print(d['key1'])
salaries = {'john':20,'sally':30,'sammy':15}
print(salaries['sally'])
#tuples - immutable (1,2,3)
t = (1,2,3)
print(t[0])
#sets -unordered collections of unique elements
x = set()
print(x)
x.add(1)
x.add(8)
print(x)
s = "flask"
print(s[0])
print(s[2:])
print(s[1:4])
print(s[-1])
print(s[::-1])
l = [3,7,[1,4,'hello']]
l[2][2] = "goodbye"
print(l)
mylistt = [1,1,1,1,1,2,2,2,2,3,3,3,3]
print(set(mylistt))
age = 4
name = "sammy"
print(f"hello my dog's name is {name} and he is {age} years old")
"""
"""
#logical comparisons
username = "admin"
check = "admin"
if username == check and 1==1:
print(access granted)
else:
print("all above conditions were not true")
"""
"""
username = "dhdjjd"
permission = False
if username == "admin" and permission:
print("full access granted")
elif username == "admin" and permission == False:
print("admin access only,no full permission")
else:
print("no access")
"""
#loops
"""
my_iterable = [1,2,3,3,4,5,6]
for items in my_iterable:
print(items ** 3)
"""
"""
salaries = {"john": 50,"kamau":60,"peter": 80}
for employee in salaries:
print(employee)
print("has salary of: ")
print(salaries[employee])
print(' ')
"""
"""
mypairs = [('a',1),('b',3),('c',4)]
for (item1,item2) in mypairs:
print(item1)
print(item2)
"""
i = 1
while i < 5:
print(f"i is currently : {i}")
i = i + 1
for x in range (0,11,2):
print(x)
#functions
def report_person(name):
print("reporting person " + name)
report_person("cindy")
def add_num(num1,num2):
return num1 + num2
result = add_num(2,4)
print(result)
| true |
eeb0f0366684a36245718065c8858f43f70736f7 | danielstaal/project | /code/chips_exe.py | 2,117 | 4.15625 | 4 | '''
Executable file Chips & Circuits
Date: 26/05/2016
Daniel Staal
This program allows the user to choose a print, netlist, search methods and
a filename to output the result
To execute this program: python chips_exe.py
'''
import astar3D
import netlists
import time
import sys
if __name__ == "__main__":
print ""
print "Welcome to Chips & Circuits! Please give the starting variables:"
print ""
measures = []
netlist = None
# choose print
printNo = int(raw_input("print(1 or 2): "))
if printNo == 1:
# dimentions of the grid
# print #1
measures.append(18)
measures.append(13)
measures.append(7)
elif printNo == 2:
# print #2
measures.append(18)
measures.append(17)
measures.append(7)
else:
measures.append(6)
measures.append(6)
measures.append(6)
# choose netlist
netlistNo = int(raw_input("netlist(1, 2 or 3): "))
if netlistNo == 1:
netlists = netlists.getNetlist1()
elif netlistNo == 2:
netlists = netlists.getNetlist2()
elif netlistNo == 3:
netlists = netlists.getNetlist3()
else:
netlists = netlists.getNetlistTest()
netlist = netlists[0]
gates = netlists[1]
# choose iterations
iterations = int(raw_input("number of iterations: "))
# choose deletion method
randomOrNeighbour = "n" #raw_input("random or neighbour deletion(r or n): ")
# hill climber or not
reMaking = "y"#raw_input("Remaking(y or n): ")
# if reMaking == "y":
# reMaking = True
# else:
# reMaking = False
# sort from shortest to longest before connecting?
shortFirst = "y"# raw_input("Shortfirst(y or n): ")
# if shortFirst == "y":
# shortFirst = True
# else:
# shortFirst = False
# provide a .csv file name
fileName = raw_input("csv file name: ")
# execute the algorithm with the given parameters
astar3D.executeAlgorithm(measures, netlist, gates, iterations, fileName, randomOrNeighbour, reMaking, shortFirst) | true |
1f32a7062a40bc6e14c6c0f7ba17d065746feb7c | josh-perry/ProjectEuler | /problem 1.py | 439 | 4.21875 | 4 | # Problem 1: Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def euler_1():
total = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
total += i
print("The answer should be: " + str(total))
if __name__ == "__main__":
euler_1()
| true |
a185c1f5b1101ae320e5781d1a73548e270a6f57 | Zahidsqldba07/code-signal-solutions-GCA | /GCA/2mostFrequentDigits.py | 1,053 | 4.125 | 4 | def mostFrequentDigits(a):
#Tests
# a: [25, 2, 3, 57, 38, 41] ==> [2, 3, 5]
# a: [90, 81, 22, 36, 41, 57, 58, 97, 40, 36] ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# a: [28, 12, 48, 23, 76, 64, 65, 50, 54, 98] ==> [2, 4, 5, 6, 8]
"""
Given an array of integers a, your task is to calculate the digits that occur the most number of times in the array. Return the array of these digits in ascending order.
Example
For a = [25, 2, 3, 57, 38, 41], the output should be mostFrequentDigits(a) = [2, 3, 5].
Here are the number of times each digit appears in the array:
0 -> 0
1 -> 1
2 -> 2
3 -> 2
4 -> 1
5 -> 2
6 -> 0
7 -> 1
8 -> 1
The most number of times any number occurs in the array is 2, and the digits which appear 2 times are 2, 3 and 5. So the answer is [2, 3, 5].
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer a
An array of positive integers.
Guaranteed constraints:
1 ≤ a.length ≤ 103,
1 ≤ a[i] < 100.
[output] array.integer
The array of most frequently occurring digits, sorted in ascending order.
"""
| true |
da574aa59126be1b3964190559c478a296f5b4a9 | Zahidsqldba07/code-signal-solutions-GCA | /arcade/intro/026-evenDigitsOnly.py | 515 | 4.1875 | 4 | def evenDigitsOnly(n):
n = [int(i) for i in str(n)]
for d in n:
if d%2 != 0:
return False
return True
"""
Check if all digits of the given integer are even.
Example
For n = 248622, the output should be
evenDigitsOnly(n) = true;
For n = 642386, the output should be
evenDigitsOnly(n) = false.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer n
Guaranteed constraints:
1 ≤ n ≤ 109.
[output] boolean
true if all digits of n are even, false otherwise.
""" | true |
8d9c2d0492cfb620649087e4e007031357eee827 | Zahidsqldba07/code-signal-solutions-GCA | /GCA/2countWaysToSplit.py | 1,719 | 4.1875 | 4 | def countWaysToSplit(s):
listS= list(s)
# print (listS)
lenS = len(listS)
count = 0
for i in range(1,lenS):
for j in range(i+1, lenS):
ab = s[0:j]
bc = s[i:lenS]
ca = s[j:lenS] + s[0:i]
# print("AB is :",ab,"BC is:",bc,"CA is:",ca)
if ab != bc and bc != ca and ca != ab :
count += 1
# print(count)
return count
"""
You are given a string s. Your task is to count the number of ways of splitting s into three non-empty parts a, b and c (s = a + b + c) in such a way that a + b, b + c and c + a are all different strings.
NOTE: + refers to string concatenation.
Example
For s = "xzxzx", the output should be countWaysToSplit(s) = 5.
Consider all the ways to split s into three non-empty parts:
If a = "x", b = "z" and c = "xzx", then all a + b = "xz", b + c = "zxzx" and c + a = xzxx are different.
If a = "x", b = "zx" and c = "zx", then all a + b = "xzx", b + c = "zxzx" and c + a = zxx are different.
If a = "x", b = "zxz" and c = "x", then all a + b = "xzxz", b + c = "zxzx" and c + a = xx are different.
If a = "xz", b = "x" and c = "zx", then a + b = b + c = "xzx". Hence, this split is not counted.
If a = "xz", b = "xz" and c = "x", then all a + b = "xzxz", b + c = "xzx" and c + a = xxz are different.
If a = "xzx", b = "z" and c = "x", then all a + b = "xzxz", b + c = "zx" and c + a = xxzx are different.
Since there are five valid ways to split s, the answer is 5.
Input/Output
[execution time limit] 4 seconds (py3)
[input] string s
A string to split.
Guaranteed constraints:
3 ≤ s.length ≤ 100.
[output] integer
The number of ways to split the given string.
""" | true |
b5224f264e6e51d57eacf32a54564688eed5c143 | Zahidsqldba07/code-signal-solutions-GCA | /arcade/intro/09-allLongestStrings.py | 1,206 | 4.125 | 4 | """
Given an array of strings, return another array containing all of its longest strings.
Example
For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be
allLongestStrings(inputArray) = ["aba", "vcd", "aba"].
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.string inputArray
A non-empty array.
Guaranteed constraints:
1 ≤ inputArray.length ≤ 10,
1 ≤ inputArray[i].length ≤ 10.
[output] array.string
Array of the longest strings, stored in the same order as in the inputArray.
"""
"""
Understand:
given an array of strings, return new array with values of the longest strings
Plan:
create empty list
create longest variable set to 1
loop through finding length of each string
if string length > longest
longest = string length
loop through again
append strings with length value longest to new array
"""
def allLongestStrings(inputArray):
new = []
longest = 0
for i in range(len(inputArray)):
if len(inputArray[i]) > longest:
longest = len(inputArray[i])
for j in range(len(inputArray)):
if len(inputArray[j]) == longest:
new.append(inputArray[j])
return new
| true |
ac6519b87bdd7461be54798c7a74088110759986 | kampetyson/python-for-everybody | /8-Chapter/Exercise6.py | 829 | 4.3125 | 4 | '''
Rewrite the program that prompts the user for a list of
numbers and prints out the maximum and minimum of the numbers at
the end when the user enters “done”. Write the program to store the
numbers the user enters in a list and use the max() and min() functions to
compute the maximum and minimum numbers after the loop completes.
Enter a number: 6
Enter a number: 2
Enter a number: 9
Enter a number: 3
Enter a number: 5
Enter a number: done
Maximum: 9.0
Minimum: 2.0
'''
numbers = None
number_list = list()
while True:
numbers = input('Enter number: ')
if(numbers == 'done'):
break
try:
float(numbers)
except:
print('Bad Input')
quit()
number_list.append(numbers)
print('Minimum:',min(number_list))
print('Maximum:',max(number_list)) | true |
b3bc71dff70c5bf4e21e0bc4e2af3f826c41406d | kampetyson/python-for-everybody | /2-Chapter/Exercise3.py | 212 | 4.15625 | 4 | # Write a program to prompt the user for hours and rate perhour to compute gross pay.
hours = int(input('Enter Hours: '))
rate = float(input('Enter Rate: '))
gross_pay = hours * rate
print('Pay:',gross_pay) | true |
789ffe90d787d656159bbefc7dfeafb7bd02a287 | kampetyson/python-for-everybody | /7-Chapter/Exercise2.py | 1,108 | 4.15625 | 4 | # Write a program to prompt for a file name, and then read
# through the file and look for lines of the form: X-DSPAM-Confidence: 0.8475
# When you encounter a line that starts with “X-DSPAM-Confidence:”
# pull apart the line to extract the floating-point number on the line.
# Count these lines and then compute the total of the spam confidence
# values from these lines. When you reach the end of the file, print out
# the average spam confidence.
# Enter the file name: mbox.txt
# Average spam confidence: 0.894128046745
# Enter the file name: mbox-short.txt
# Average spam confidence: 0.750718518519
try:
fname = input('Enter a file name: ')
fhandle = open(fname)
except:
print('File not found')
exit()
total = 0
average = 0
count = 0
for line in fhandle:
line = line.strip()
if line.startswith('X-DSPAM-Confidence:'):
colon_pos = line.find(':')
extracted_num = float(line[colon_pos+1:])
total += extracted_num
count += 1
average = total/count
print('Average spam confidence:',round(average,4))
| true |
9b3edb65b838b153430aa177b1609260908e98b4 | kampetyson/python-for-everybody | /7-Chapter/Exercise1.py | 614 | 4.40625 | 4 | # Write a program to read through a file and print the contents
# of the file (line by line) all in upper case. Executing the program will
# look as follows:
# python shout.py
# Enter a file name: mbox-short.txt
# FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008
# RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPROJECT.ORG>
# RECEIVED: FROM MURDER (MAIL.UMICH.EDU [141.211.14.90])
# BY FRANKENSTEIN.MAIL.UMICH.EDU (CYRUS V2.3.8) WITH LMTPA;
# SAT, 05 JAN 2008 09:14:16 -0500
try:
fname = input('Enter a file name: ')
fhandle = open(fname)
except:
print('File not found')
exit()
for line in fhandle:
print(line.upper()) | true |
21045c28a2f3a5e004a2b42b3d6f7d04aa122e8a | usmansabir98/AI-Semester-101 | /PCC Chapter 5/5-5.py | 779 | 4.125 | 4 | # 5-5. Alien Colors #3: Turn your if-else chain from Exercise 5-4 into an if-elifelse
# chain.
# • If the alien is green, print a message that the player earned 5 points.
# • If the alien is yellow, print a message that the player earned 10 points.
# • If the alien is red, print a message that the player earned 15 points.
# • Write three versions of this program, making sure each message is printed
# for the appropriate color alien.
def test_color(color):
if color=='green':
print("You earned 5 points")
elif color=='yellow':
print("You earned 10 points")
else:
print("You earned 15 points")
alien_color= 'green'
test_color(alien_color)
alien_color = 'yellow'
test_color(alien_color)
alien_color = 'red'
test_color(alien_color) | true |
8f6f7f0c6308b83fa51fbdf2f2e00717f736b63e | CISVVC/test-ZackaryBair | /dice_roll/main.py | 2,080 | 4.28125 | 4 | """
Assignment: Challenge Problem 5.13
File: main.py
Purpose: Rolls dice x amount of times, and prints out a histogram for the number of times that each number was landed on
Instructions:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Analyzing dice rolls is a common example in understanding probability and statistics.
The following program calculates the number of times the sum of two dice (randomly rolled) is equal to six or seven.
import random
num_sixes = 0
num_sevens = 0
num_rolls = int(input('Enter number of rolls:\n'))
if num_rolls >= 1:
for i in range(num_rolls):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
roll_total = die1 + die2
#Count number of sixes and sevens
if roll_total == 6:
num_sixes = num_sixes + 1
if roll_total == 7:
num_sevens = num_sevens + 1
print('Roll %d is %d (%d + %d)' % (i, roll_total, die1, die2))
print('\nDice roll statistics:')
print('6s:', num_sixes)
print('7s:', num_sevens)
else:
print('Invalid number of rolls. Try again.')
---------
Create a different version of the program that:
Prints a histogram in which the total number of times the dice rolls
equals each possible value is displayed by printing a character, such as
*, that number of times. The following provides an example:
"""
import random
rollResults = []
numberRoles = 0
sidesOnDice = 6 #set the number of sides on a dice, also used for a counter
print('Rolls a given number of dice and prints out the results')
print()
#get number of roles
while numberRoles <= 0:
numberRoles = int(input('How many roles would you like to do?: '))
#roll dice, store results
for roll in range(numberRoles):
rollResults.append(random.randint(1, sidesOnDice))
#print histogram
while sidesOnDice > 0:
print(sidesOnDice, end = ': ')
for result in rollResults:
if result == sidesOnDice:
print('*', end = '')
sidesOnDice -= 1
print()
| true |
bb3e967a7776b571cca10fdb988cb09b8980cf63 | gptix/cs-module-project-algorithms2 | /moving_zeroes/moving_zeroes.py | 458 | 4.28125 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
def moving_zeroes(arr):
# Your code here
original_length = len(arr)
out = [element for element in arr if element is not 0]
out = out + [0]*original_length
return out[:original_length]
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [0, 3, 1, 0, -2]
print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}") | true |
db13074a2c8dca8e5d1708a80760d6626f3b0b9b | AdyGCode/Python-Basics-2021S1 | /Week-7-1/functions-4.py | 1,251 | 4.34375 | 4 | """
File: Week-7-1/functions-4.py
Author: Adrian Gould
Purpose: Demonstrate taking code and making it a function
Move the get integer code to a function (see functions-3
for the previous code)
Design:
Define get_integer function
Define number to be None
While number is none
Try the following
Ask user for an integer
Break from While loop
If an exception given:
Display "Ooops! Not an integer"
return number
Define main function
Define number1 as the result from "get integer"
Display the number
If main is being executed:
Call main function
Test:
Run code and enter the following value: 123
Run code and enter the following value: 12.5
Run code and enter the following value: abc
"""
def get_integer():
number = None
while number is None:
try:
number = int(input("Enter an integer: "))
break # cheat - let's get outta the loop NOW!
except ValueError:
print("OOPS! not an integer value")
return number
def main():
number1 = get_integer()
print(number1)
if __name__ == "__main__":
main()
| true |
425571e8bb0512c2a92f9068883189291acb771b | AdyGCode/Python-Basics-2021S1 | /Week-13-1/gui-7-exercise.py | 1,242 | 4.1875 | 4 | # --------------------------------------------------------------
# File: Week-13-1/gui-7-exercise.py
# Project: Python-Class-Demos
# Author: Adrian Gould <Adrian.Gould@nmtafe.wa.edu.au>
# Created: 11/05/2021
# Purpose: Practice using GUI
#
# Problem: Create a GUI that asks a user for their name and
# the year of their birth. When a button is pressed
# it presents a greeting of the form
# "Welcome NAME, you are XX this year."
#
# The GUI should look something like this:
# Name: __________________ label/text input
# Birth Year: __________________ label/number input
# __________________________________ label
# [How Old?] button
# --------------------------------------------------------------
from breezypythongui import EasyFrame
class AgeApplication(EasyFrame):
def __init__(self):
"""Sets up the window, labels, and button."""
EasyFrame.__init__(self)
self.setSize(600, 300)
self.setTitle("How old am I?")
# Methods to handle user events.
def main():
"""Entry point for the application."""
AgeApplication().mainloop()
if __name__ == "__main__":
main()
| true |
b306448e151d13b2caeb8cfced3a9650affc29ba | jfbeyond/Coding-Practice-Python | /101_symmetric_tree.py | 1,026 | 4.15625 | 4 |
# 101 Symmetric Tree
# Recursively
def isSymmetric(root):
# current node left child is equal to current node right child
if not root: return False
return checkSymmetry(root, root):
def checkSymmetry(node1, node2):
if not node1 and not node2: return True
if node1 and node2 and node1.val == node2.val:
return checkSymmetry(node1.left, node2.right) and checkSymmetry(node1.right, node2.left)
return False
# O(n) and O(1)
# Iteratively
def isSymmetric(root):
# BFS -- Queue
stackl = [root]
stackr = [root]
while stackl and stackr:
nl = stackl.pop(0)
nr = stackr.pop(0)
# if both nodes are none just go to next iteration
if not nl and not nr:
continue
# This means only one is None, then it's False
if not nl or not nr:
return False
if nl.val != n2.val:
return False
stackl.append(nl.left)
stackl.append(nl.right)
stackr.append(nr.right)
stackr.append(nr.left)
return True
# O(n) and O(n) | true |
1353ee42c247cd5d9a30cb3bd9fc5f33639d181a | F4Francisco/Algorithms_Notes_For_PRofessionals | /Section1.2_FizzBuzzV2.py | 777 | 4.125 | 4 | ''' Optimizing the orginal FizzBuzz:
if divisable by 3 sub with Fizz
if divisable by 5 sub with Buzz
if divisable by 15 sub with FizzBuzz
'''
# Create an array with numbers 1-5
number = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
#iterate through the array and check which numbers are fizz and which are Buzz
for num in number :
if num % 15 == 0:
print(num) , ("FizzBuzz")
elif num % 5 == 0:
print (num) , ("Buzz")
elif num % 3 == 0:
print (num) , ("Fizz")
else:
print (num)
'''The runtime for the orginal algorithm has been improved by dividing by 15:
we do not have to check for both 3 and 5 again instead we check one time
Check for numbers divisable by 3 (Fizz)
Check for numbers divisable by 5 (Buzz)
and Check for numbers divisable by 15 (FizzBuzz)
'''
| true |
e5e7ef14baa4d4b7b3596bb4adf7cadaddea2e07 | SimaFish/python_practice | /class_practice/auto.py | 2,571 | 4.40625 | 4 | # Zen of Python
import this
# The definition of a class happens with the `class` statement.
# Defining the class `Auto`.
# class Auto(object): is also an allowable definition
class Auto():
# ToDo class attributes vs. instance attributes
# https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
# The __init__() function is called automatically every time the class is being used to create a new object.
# Use the __init__() function to assign values to object properties, or other operations
# that are necessary to do when the object is being created. Notice two leading and trailing underscores.
# The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
# It does not have to be named `self`, you can call it whatever you like, but it has to be the first parameter of any function in the class.
def __init__(self, brand, model, year=None):
self.brand = brand
self.model = model
self.year = year
# __hash__() should return the same value for objects that are equal.
# It also shouldn't change over the lifetime of the object.
# Generally you only implement it for immutable objects.
def __hash__(self):
return 1357
# `equal`
def __eq__(self, other):
return not other
# not `equal`
def __ne__(self, other):
return not self.__eq__(other)
# A method is basically a function that belongs to a class.
def get_year(self):
if self.year is None:
return 'Undefined'
else:
return str(self.year)
def desc_auto(self):
print('\nObject:', id(self))
print('Auto:', self.brand + ' ' + self.model)
print('Manufactured:', self.get_year())
# Create an instance (object) of `Auto` class.
renault_logan = Auto('Renault', 'Logan', 2011)
# Invoke method `desc_auto`.
renault_logan.desc_auto()
# `__sizeof__()` method returns the size of object in bytes
print('\nObject size (bytes):', renault_logan.__sizeof__())
# Delete the year property from the renault_logan object:
del renault_logan.year
print('\nAfter deletion of `year` attribute:')
try:
print(renault_logan.year, '\n')
except AttributeError:
print('`renault_logan` object no longer has attribute `year`')
# Delete the `renault_logan` object:
del renault_logan
print('\nAfter deletion of `renault_logan` object:')
try:
print(id(renault_logan), '\n')
except NameError:
print('`renault_logan` object is not exists', '\n') | true |
43594d3f6b04fcee5ff2285226da49fd96471d89 | SimaFish/python_practice | /modules/mod_string.py | 1,027 | 4.25 | 4 | import string
# String constants (output type: str).
# The lowercase letters 'abcdefghijklmnopqrstuvwxyz'.
print('1: ' + string.ascii_lowercase)
# The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
print('2: ' + string.ascii_uppercase)
# The concatenation of the ascii_lowercase and ascii_uppercase constants described above.
print('3: ' + string.ascii_letters)
# The string '0123456789'.
print('4: ' + string.digits)
# The string '0123456789abcdefABCDEF'.
print('5: ' + string.hexdigits)
# String of ASCII characters which are considered punctuation characters in the C locale:
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.
print('6: ' + string.punctuation)
# A string containing all ASCII characters that are considered whitespace.
# This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
print('7: ' + string.whitespace)
# String of ASCII characters which are considered printable.
# This is a combination of digits, ascii_letters, punctuation, and whitespace.
print('8: ' + string.printable) | true |
6896682b041713dff84ab145274b7858f3f3c7bc | seo0/MLstudy | /adsa_2016/module13_graphs01/part02_basics02/graphs_etc.py | 1,760 | 4.3125 | 4 |
import networkx as nx
import matplotlib.pyplot as plt
from module13_graphs01.part01_basics.graphs_basics import print_graph, display_and_save
def modulo_digraph(N,M):
"""
This function returns a directed graph DiGraph) with the following properties (see also cheatsheet at: http://screencast.com/t/oF8Nr1TdYDbl):
- The graph has N nodes, labelled using numbers from 1 to N-1
- All nodes in the same M-modulo class are on the same path (the path from the node with lower value to highest value)
- All nodes that are multiple of M-1 (or, in other words, for which node % (M-1) == 0) are on the same path (that gos from lower to higher values)
Hint:
- Initialise the DiGraph, for each node you can store two properties (value of % M, value of % (M-1))
- Scan the created graph to create paths based on similar values of the two properties
- Create edges in the graph using the values of the lists of nodes that you created at the previous step
More about DiGraphs at: https://networkx.github.io/documentation/development/reference/classes.digraph.html
"""
pass
def longest_shortest_path(G):
"""
Given a graph G, this functions prints on screen the longest among the shortest paths between two nodes in G.
note that you can check whether a path exists between two nodes using nx.has_path(G, node1, node2)
If there are more than 1 longest shortest path, then it doesn't matter which one is chosen
"""
pass
if __name__ == '__main__':
G = modulo_digraph(6,3)
print_graph(G)
longest_shortest_path(G)
G = modulo_digraph(7, 2)
print_graph(G)
G = modulo_digraph(10, 5)
print_graph(G)
longest_shortest_path(G) | true |
1895a345a9021d25dcdc91982ff00b6f3090474a | luckydimdim/grokking | /tree_breadth_first_search/minimum_depth_of_a_binary_tree/main.py | 1,086 | 4.1875 | 4 | from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def find_minimum_depth(root):
'''
Find the minimum depth of a binary tree.
The minimum depth is the number of nodes along the shortest path
from the root node to the nearest leaf node.
'''
if root is None:
return -1
queue = deque()
queue.append(root)
level = 0
while queue:
level += 1
level_size = len(queue)
for _ in range(level_size):
curr = queue.popleft()
if not curr.left and not curr.right:
return level
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
return -1
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print("Tree Minimum Depth: " + str(find_minimum_depth(root)))
root.left.left = TreeNode(9)
root.right.left.left = TreeNode(11)
print("Tree Minimum Depth: " + str(find_minimum_depth(root)))
main()
| true |
48f1fa5d3668a54ec73e49e377c610b3bfdba024 | luckydimdim/grokking | /modified_binary_search/search_bitonic_array/main.py | 1,139 | 4.15625 | 4 | def search_bitonic_array(arr, key):
'''
Given a Bitonic array, find if a given ‘key’ is present in it.
An array is considered bitonic if it is monotonically increasing and then monotonically decreasing.
Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1].
Write a function to return the index of the ‘key’. If the ‘key’ is not present, return -1.
'''
start, end = 0, len(arr) - 1
while start <= end:
mid = start + (end - start) // 2
is_asc = mid + 1 < len(arr) and arr[mid] < arr[mid + 1]
if arr[mid] == key:
return mid
if is_asc:
if arr[mid] < key:
start = mid + 1
else:
end = mid - 1
else:
if arr[mid] < key:
end = mid - 1
else:
start = mid + 1
return -1
def main():
print(search_bitonic_array([1, 3, 8, 4, 3], 4))
print(search_bitonic_array([3, 8, 3, 1], 8))
print(search_bitonic_array([1, 3, 8, 12], 12))
print(search_bitonic_array([10, 9, 8], 10))
main()
| true |
9e429a3d67b58bd3e34e0868fa203e80c8215925 | luckydimdim/grokking | /modified_binary_search/next_letter/main.py | 1,092 | 4.125 | 4 | import string
def search_next_letter(letters, key):
'''
Given an array of lowercase letters sorted in ascending order,
find the smallest letter in the given array greater than a given ‘key’.
Assume the given array is a circular list,
which means that the last letter is assumed to be connected with the first letter.
This also means that the smallest letter in the given array
is greater than the last letter of the array and is also the first letter of the array.
Write a function to return the next letter of the given ‘key’.
'''
n = len(letters)
if key < letters[0] or key > letters[n - 1]:
return letters[0]
start, end = 0, n - 1
while start <= end:
mid = start + (end - start) // 2
if letters[mid] <= key:
start = mid + 1
else:
end = mid - 1
return letters[start % n]
def main():
print(search_next_letter(['a', 'c', 'f', 'h'], 'f'))
print(search_next_letter(['a', 'c', 'f', 'h'], 'b'))
print(search_next_letter(['a', 'c', 'f', 'h'], 'm'))
main()
| true |
5921d9a5ee2ca9e587ea6d8a54cdaf6126ffd510 | luckydimdim/grokking | /subsets/permutations_recursive/main.py | 535 | 4.1875 | 4 | from collections import deque
def find_permutations(nums):
'''
Given a set of distinct numbers, find all of its permutations.
'''
result = []
permutate(nums, 0, [], result)
return result
def permutate(nums, i, current, result):
if i == len(nums):
result.append(current)
return
for l in range(len(current) + 1):
next = list(current)
next.insert(l, nums[i])
permutate(nums, i + 1, next, result)
def main():
print("Here are all the permutations: " + str(find_permutations([1, 3, 5])))
main()
| true |
57bf01794444f9e3fc31973d50f33a3cdbd9639b | luckydimdim/grokking | /tree_breadth_first_search/zigzag_traversal/main.py | 1,289 | 4.15625 | 4 | from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def traverse(root):
'''
Given a binary tree, populate an array to represent its zigzag level order traversal.
You should populate the values of all nodes of the first level from left to right,
then right to left for the next level and keep alternating in the same manner for the following levels.
'''
result = []
if root is None:
return result
queue = deque()
queue.append(root)
zigzag = True
while queue:
level_size = len(queue)
level = deque()
zigzag = not zigzag
for _ in range(level_size):
curr = queue.popleft()
if zigzag == True:
level.appendleft(curr.val)
else:
level.append(curr.val)
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
result.append(list(level))
return result
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
root.right.left.left = TreeNode(20)
root.right.left.right = TreeNode(17)
print("Zigzag traversal: " + str(traverse(root)))
main()
| true |
03e7a2218937f12112e322ac88ce065cceb7b23f | darshanchandran/PythonProject | /PythonProject/Classes and Modules/Classes/Compositions.py | 336 | 4.28125 | 4 | #This program shows how compositions work with out inheriting the parent class
class Parent(object):
def boss(self):
print("I'm the boss")
class Child(object):
def __init__(self):
self.child = Parent()
def boss(self):
print("Child is the boss")
self.child.boss()
son = Child()
son.boss()
| true |
c0c7027ee70e6be6a0f9b067fc0f1df9b6276bc0 | EmissaryEntertainment/3D-Scripting | /Week_2/McSpadden_Exercise_2.3.py | 699 | 4.21875 | 4 | #Use each form of calculation besides modulus
print("2 + 5 = " + str(2+5))
print("2 - 5 = " + str(2-5))
print("2 * 5 = " + str(2*5))
print("2 / 5 = " + str(2/5))
print("2 ** 5 = " + str(2**5))
#Calculation whos resluts depend on order of operations
print("160 + 5 * 7 = " + str(160 + 5 * 7))
#Force change order of operations by using parenthesis
print("(160 + 5) * 7 = " + str((160 + 5) * 7))
#Long decimal result is not what is expected
print("0.1 + 0.2 = " + str(0.1+0.2))
#Find another calculation that results in a long decimal
print("3 * 0.1 = " + str(3*0.1))
#Using integer division to decide which version of python I am using
print("4 / 2 = " + str(4/2) + " Which means I have Python 3") | true |
2c709c8d07c8a738177250eb5b4d029c3945dd7b | EmissaryEntertainment/3D-Scripting | /Week_4/McSpadden_Exercise_4.3.py | 897 | 4.25 | 4 | #THREE IS A CROWD
print("-------THREE IS A CROWD-------")
names = ["Jose", "Jim","Larry","Bran"]
def check_list(list):
if len(list) > 3:
print("This list is to crowded.")
check_list(names)
del names[0]
check_list(names)
#THREE IS A CROWD - PART 2
print("-------THREE IS A CROWD - PART 2-------")
def check_list_pt2(list):
if len(list) > 3:
print("This list is to crowded.")
else:
print("This list is a great size.")
check_list_pt2(names)
#SIX IS A MOB
print("-------SIX IS A MOB-------")
names.append("Steve")
names.append("Quincy")
def six_is_a_mob(list):
if len(list) > 5:
print("There is a mob in the room.")
elif len(list) >= 3 and len(list) <= 5:
print("This room is crowded.")
elif len(list) == 1 or len(list) == 2:
print("This room is not crowded.")
else:
print("The room is empty.")
six_is_a_mob(names)
| true |
567addd4e775a0a80665b75a1666cbf1fdda28e9 | KumarjitDas/Algorithms | /Algorithms/Recursion/Python/countdown.py | 911 | 4.5 | 4 | def countdown(value: int):
""" Print the countdown values.
countdown
=========
The `countdown` function takes an integer value and decreases it. It prints
the value each time it. It uses 'recursion' to do this.
Parameters
----------
value: int
an integer value
Returns
-------
None
"""
if value <= 0: # The base case: if the value is zero
print("Stop!") # then stop countdown
return
print(value, end=' ')
countdown(value - 1) # The recursive case: call countdown
# (itself) with value decreased by 1
if __name__ == '__main__':
print('Countdown start:', end=' ')
countdown(10)
| true |
110c972931fe16b1d605396a7d2813388ebf3282 | HossamSalaheldeen/Python_lab1 | /prob3.py | 915 | 4.1875 | 4 | # Problem 3
#-------------
# Consider dividing a string into two halves.
# Case 1:
# The length is even, the front and back halves are the same length.
# Case 2:
# The length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form :
# (a-front + b-front) + (a-back + b-back)
def combine_strs(a,b):
print(len(a))
a_front = a[0:len(a)//2 if len(a)%2 == 0 else ((len(a)//2)+1)]
print(a_front)
a_back = a[((len(a)//2)) if len(a)%2 == 0 else ((len(a)//2)+1):len(a)]
print(a_back)
print(len(b))
b_front = b[0:len(b)//2 if len(b)%2 == 0 else ((len(b)//2)+1)]
print(b_front)
b_back = b[((len(b)//2)) if len(b)%2 == 0 else ((len(b)//2)+1):len(b)]
print(b_back)
ab = (a_front + b_front) + (a_back + b_back)
return ab
print(combine_strs("abcd","abcd"))
| true |
2a7963e01f163f9b2c85e8d64de66630914f7328 | JemrickD-01/Python-Activity | /WhichWord.py | 617 | 4.21875 | 4 | def stringLength(fname,lname):
if len(fname)>len(lname):
print(fname,"is longer than",lname)
elif len(fname)<len(lname):
print(lname,"is longer than",fname)
else:
print(fname,"and",lname,"have the same size")
choices = ["y","n"]
ans="y"
while ans=="y":
x=input("enter your first word: ")
y=input("enter your second word: ")
stringLength(x,y)
ans=input("would you like to continue?(y/n): ")
if ans not in choices:
print("Enter y or n only")
ans=input("would you like to continue? y/n")
else:
print("Done")
| true |
af1ecc1dfb000a8dd0aab062123a29c489a7f426 | Raj-kar/PyRaj-codes | /password.py | 1,300 | 4.28125 | 4 | ''' Homework 1 -
WAP to genarate a secure password.
- 1. password must contains minimim 8 char.
- 2. both upper and lower case.
- 3. must contains two number and one special char.
bonus - shuffle the password, for better security.
Homework 2 -
Optimize the below Code.
'''
# Wap to check a password is secure or not ?
from string import ascii_lowercase, ascii_uppercase, digits, punctuation
password = input("Enter your password :: ")
if len(password) < 8:
print("Password must contains minimim 8 char.")
else:
lowerCase = False
for letter in password:
if letter in ascii_lowercase:
lowerCase = True
break
if lowerCase == True:
upperCase = False
for letter in password:
if letter in ascii_uppercase:
upperCase = True
break
if upperCase == True:
count = 0
for letter in password:
if letter in digits:
count += 1
if count >= 2:
special_char = False
for letter in password:
if letter in punctuation:
special_char = True
break
if special_char == True:
print("Password VALID !!!! :) ")
else:
print("minimim one special char required")
else:
print("Minimum 2 digits required !")
else:
print("Minimum 1 upperCase letter required")
else:
print("Minimum 1 lowerCase letter required !") | true |
82fc2124669344ca0291a5d9bef9d8f70b01e7b9 | avantikabagri/lecture8 | /3/gradepredict_stubs.py | 2,028 | 4.21875 | 4 |
# reads a CSV from a file, and creates a dictionary of this form:
# grade_dict['homeworks'] = [20, 20, 20, ...]
# grade_dict['lectures'] = [5, 5, 5, ...]
# ...
# params: none
# returns: a dictionary as specified above
def get_data():
return {}
# param: list of lecture excercise scores
# return: total scores for lecture exercises, after dropping lowest 4
def calculate_lecture_exercise_score(lecture_scores):
return 0
# param: list of discussion scores
# return: total scores for discussions, dropping lowest 2
def calculate_discussion_score(discussion_scores):
return 0
# param: list of homework scores
# return: total points for homeworks, after dropping lowest 2
def calculate_homework_score(homework_scores):
return 0
# param: list of midterm scores
# return: total points for midterm category
def calculate_midterm_score(midterm_scores):
return 0
# param: list of project scores
# return: total points for project category
def calculate_project_score(project_scores):
return 0
# given the total points earned, converts to the final letter grade
# param: total_score
# return: string representing a letter grade
def convert_to_letter_grade(total_score):
return 'X'
def test():
#test for calculate_homework_score
homeworks = [20,20,20,20,20,20,20,20,20,20,20,20,20,20]
expected_output = 20*12
homeworks2 = [10,10,12,12,14,14,16,16,18,18,20,20,22,22]
expected_output2 = 12+12+14+14+16+16+18+18+20+20+22+22
if calculate_homework_score(homeworks) == expected_output:
print("pass 1")
else:
print("fail 1")
if calculate_homework_score(homeworks2) == expected_output2:
print("pass 2")
else:
print("fail 2")
test()
grade_dict = get_data()
total_score = 0
if 'homeworks' in grade_dict:
total_score += calculate_homework_score(grade_dict['homeworks'])
# same for the other categories
letter_grade = convert_to_letter_grade(total_score)
print('You will get a', letter_grade, 'with', total_score, 'points')
# write some tests here
| true |
42ea0a6fe036ea1fbb3059a715461680a0e13146 | saubhik/catalog | /src/catalog/tries/add-and-search-word-data-structure-design.py | 2,412 | 4.3125 | 4 | # Add and Search Word - Data structure design
#
# https://leetcode.com/problems/add-and-search-word-data-structure-design/
#
import unittest
from typing import Dict
class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = dict()
self.end: bool = False
class WordDictionary:
def __init__(self):
"""
Initialize data structure
"""
self.root = TrieNode()
def add_word(self, word: str) -> None:
"""
Adds a word into the data structure.
:param word: the word to add.
:return: None
"""
current_node = self.root
for letter in word:
if letter not in current_node.children:
current_node.children[letter] = TrieNode()
current_node = current_node.children[letter]
current_node.end = True
def search(self, word: str, current_node: TrieNode = None) -> bool:
"""
Returns if the word is in the data structure.
A word could contain the dot character "." to represent any one letter.
:param word: the word to search for.
:param current_node: current node the trie we start searching from.
:return: True or False.
"""
if not current_node:
current_node = self.root
if not word:
return current_node.end
if word[0] in current_node.children:
return self.search(word[1:], current_node.children[word[0]])
if word[0] != ".":
return False
for key in current_node.children:
if self.search(word[1:], current_node.children[key]):
return True
return False
class Test(unittest.TestCase):
def test_add_word(self):
word_dict = WordDictionary()
word_dict.add_word("dog")
self.assertEqual(True, word_dict.search("dog"))
self.assertEqual(False, word_dict.search("dogs"))
def test_search(self):
word_dict = WordDictionary()
word_dict.add_word("dog")
word_dict.add_word("mad")
self.assertEqual(True, word_dict.search("dog"))
self.assertEqual(False, word_dict.search("..e"))
self.assertEqual(True, word_dict.search("..d"))
self.assertEqual(True, word_dict.search(".a."))
self.assertEqual(False, word_dict.search(".p."))
if __name__ == "__main__":
unittest.main()
| true |
58d34d94f58f56f4c1e8dbf9d3b8a97d23ed8e0e | Ry09/Python-projects | /Random Stuff/collatz.py | 1,142 | 4.65625 | 5 | # This is a program to run the Collatz Sequence. It will
# take a number from the user and then divide it by 2 if
# it is even, or multiply by 3 and add 1 if it is odd. It
# will loop through this until it reaches the value of 1.
def collatz(num):
try:
num = int(num)
print(num)
if num == 1:
print("Cannot begin with 0 or 1.")
return 0
while(num != 1):
if num == 0:
print("Cannot begin with 0 or 1.")
return 0
elif num % 2 == 0:
num = num / 2
print(num)
continue
else:
num = num * 3 + 1
print(num)
continue
return num
except ValueError:
print("Incorrect value entered. Please input a number.")
return 0
while True:
x = input("Please enter a number to begin the Collatz Sequnce. Also note that it cannot begin with 0 or 1: ")
if collatz(x) == 1:
print("And there you have the Collatz Sequence!")
break
else:
continue
input("\n\n\nPress enter to exit.")
| true |
927170aae55b2529e503f3e1836cd0ac6d18516b | rayadamas/pythonmasterclassSequence | /coding exercise 14.py | 662 | 4.21875 | 4 | # Write a program which prompts the user to enter three integers separated by ","
# user input is: a, b, c; where those are numbers
# The following calculation should be displayed: a + b - c
# 10, 11, 10 = 11
# 7, 5, -1 = 13
# Take input from the user
user_input = input("Please enter three numbers: ")
# Split the given input string into 3 parts
number_split = user_input.split(',')
# Convert the tokens into integers
number_tuple = []
for st in number_split:
number_tuple.append(int(st))
# Calculate the result: a + b - c
result = number_tuple[0] + number_tuple[1] - number_tuple[2]
# Output the result
print(result)
| true |
a6c5cc0f90f540202efa1c8f6b1098d99c3c4397 | surprise777/StrategyGame2017 | /Game/current_state.py | 1,959 | 4.3125 | 4 | """module: current_state (SuperClass)
"""
from typing import Any
class State:
"""a class represent the state of class.
current_player - the player name who is permitted to play this turn.
current_condition - the current condition of the state of the game
"""
current_player: str
current_condition: str
def __init__(self) -> None:
"""initialize the class.
>>> st1 = State()
"""
self.current_player = ''
self.current_condition = ''
def __str__(self) -> str:
"""return the string represention of the class.
"""
raise NotImplementedError("Must implement a subclass!")
def __eq__(self, other: "State") -> bool:
"""compare if self is equivalent to the other.
"""
return type(self) == type(other) and \
self.current_condition == other.current_condition and \
self.current_player == other.current_player
def get_possible_moves(self) -> list:
"""get a list of all possible moves of self game which are valid.
"""
raise NotImplementedError("Must implement a subclass!")
def is_valid_move(self, move: Any) -> bool:
"""return True if the move from the str_to_move is valid.
"""
raise NotImplementedError("Must implement a subclass!")
def make_move(self, move_to_make: Any) -> "State":
"""return new current state class after changing the move of the game.
"""
raise NotImplementedError("Must implement a subclass!")
def get_current_player_name(self) -> str:
"""return the current player's name of the self game.
>>> st1 = State()
>>> st1.current_player ='a'
>>> st1.get_current_player_name()
'a'
"""
return self.current_player
if __name__ == "__main__":
from doctest import testmod
testmod()
import python_ta
python_ta.check_all(config="a1_pyta.txt")
| true |
a23930569e83eb420cc1f2290f35bb43853be0c2 | caboosecodes/Python_Projects | /python_If.py | 297 | 4.25 | 4 |
height = 200
if height > 150:
if height > 195:
print('you are too tall ride the roller coaster')
else:
print('you can ride the roller coaster')
elif height >= 125:
print('you need a booster seat to ride the roller coaster')
else:
print('where are your parents?')
| true |
c901a714e56f22c3f31fef767205df16ab561035 | ScottSko/Python---Pearson---Third-Edition---Chapter-5 | /Chapter 5 - Maximum of Two Values.py | 379 | 4.21875 | 4 | def main():
num1 = int(input("Please enter a value: "))
num2 = int(input("Please enter another value: "))
greater_value = maximum(num1, num2)
print("The greater value is", greater_value)
def maximum(num1,num2):
if num1 > num2:
return num1
elif num1 == num2:
print("The values are equal.")
else:
return num2
main() | true |
3ce6d57c9a06622e7cae3f1bc2fa2baa1946be36 | Nikhil-Xavier-DS/Sort-Search-Algorithms | /bubble_sort.py | 467 | 4.28125 | 4 | """
Implementation of Bubble Sort.
"""
# Author: Nikhil Xavier <nikhilxavier@yahoo.com>
# License: BSD 3 clause
def Bubble_sort(arr):
"""Function to perform Bubble sort in ascending order.
TIME COMPLEXITY: Best:O(n), Average:O(n^2), Worst:O(n^2)
SPACE COMPLEXITY: Worst: O(1)
"""
for outer in range(len(arr)-1, 0, -1):
for inner in range(outer):
if arr[inner] > arr[inner+1]:
arr[inner], arr[inner+1] = arr[inner+1], arr[inner]
| true |
b8d279107217bfbf7174bb4dd054b254a5e90a7c | SreeramSP/Python-Programs-S1 | /factorial.py | 235 | 4.1875 | 4 | n=int(input("Enter the number="))
factorial=1
if n<0:
print("No negative Numbers")
elif n==0:
print("The factorial of 0 is 1")
else:
for i in range(1,n+1):
factorial=factorial*i
print("Factorial=",factorial)
| true |
283112adcd03688236d72a9748711469976a4976 | standrewscollege2018/2021-year-11-classwork-SamEdwards2006 | /Paracetamol.py | 662 | 4.125 | 4 | #sets the constants
AGE_LIMIT = 12
WEIGHT_LIMIT = 0
on = 1
#finds the users age
while(on > 0):
age = int(input("How old are you: "))
#tests if the age is more than 12,
#if not, it will go to the else.
if age >= AGE_LIMIT:
print("Recommend two 500 mg paracetamol tablets")
elif age >= 0:
#takes the users weight, and if it is more than 0
# it will multiply the weight by 10
weight = float(input("How much do you weigh: "))
if weight > WEIGHT_LIMIT:
print("Your recommended dose is", weight * 10,"mg")
else:
print("invalid weight")
else:
print("invalid age")
| true |
78a556658eea5d03ebbdd76ecf3e7d2888f3860c | rafa761/leetcode-coding-challenges | /2020 - august/008 - non-overlapping intervals.py | 1,500 | 4.40625 | 4 | """
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
"""
from typing import List
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if len(intervals) < 2:
return 0
intervals.sort()
count, last_included = 0, 0
for i in range(1, len(intervals)):
if intervals[i][0] < intervals[last_included][1]:
count += 1
if intervals[i][1] < intervals[last_included][1]:
last_included = i
else:
last_included = i
return count
if __name__ == '__main__':
S = Solution()
print('-> 1: ', S.eraseOverlapIntervals([[1, 2], [2, 3], [3, 4], [1, 3]]))
print('-> 2: ', S.eraseOverlapIntervals([[1, 2], [1, 2], [1, 2]]))
print('-> 0: ', S.eraseOverlapIntervals([[1, 2], [2, 3]]))
print('-> 2: ', S.eraseOverlapIntervals([[1, 100], [11, 22], [1, 11], [2, 12]]))
| true |
2442c3261cc4d4280d0a46878a3e10d250298b4a | vismayatk002/PythonAssignment | /BasicCorePrograms/PrimeFactors.py | 542 | 4.3125 | 4 | """
@Author : Vismaya
@Date : 2021-10-18 11:39
@Last Modified by : Vismaya
@Last Modified time : 2021-10-18 12:52
@Title : Prime factors of a number
"""
def is_prime(num):
flag = 0
for j in range(2, num):
if num % j == 0:
flag = 1
break
j += 1
return flag;
number = int(input("Enter the Number : "))
i = 2
print("Prime factors : ")
while i <= number:
if number % i == 0:
result = is_prime(i)
if result == 0:
print(i)
i += 1
| true |
33579d9a2d351a6a33f82b708c68be6233c45afb | DrSneus/cse-20289-sp21-examples | /lecture09/is_anagram.py | 2,111 | 4.1875 | 4 | #!/usr/bin/env python3
import os
import sys
# Functions
def usage(status=0):
print(f'''Usage: {os.path.basename(sys.argv[0])} [flags]
-i Ignore case distinctions
This program reads in two words per line and determines if they are anagrams.
''')
sys.exit(status)
def count_letters(string):
''' Returns a dictionary containing counts of each letter in string
>>> count_letters('aaa bb c')
{'a': 3, 'b': 2, 'c': 1}
'''
counts = {} # Discuss: counting pattern
for letter in string:
if not letter.isspace():
counts[letter] = counts.get(letter, 0) + 1 # Discuss: get dictionary method
return counts
def is_anagram(word1, word2):
''' Returns whether or not word1 and word 2 are anagrams
>>> is_anagram('dormitory', 'dirty room')
True
>>> is_anagram('asdf', 'asdfg')
False
'''
counts1 = count_letters(word1)
counts2 = count_letters(word2)
for key in counts1: # Discuss: iterating through dictionary
if counts1[key] != counts2.get(key, 0):
return False
for key in counts2:
if counts2[key] != counts1.get(key, 0):
return False
return True
def main():
# Parse command-line options
arguments = sys.argv[1:] # Review: command line arguments
ignorecase = False
while arguments and arguments[0].startswith('-'):
argument = arguments.pop(0) # Discuss: popping from queue
if argument == '-i':
ignorecase = True
elif argument == '-h':
usage(0)
else:
usage(1)
# Process standard input
for line in sys.stdin:
if ignorecase:
line = line.lower()
word1, word2 = line.split(' ', 2) # Discuss: splitting string
if is_anagram(word1, word2):
print('ANAGRAM!')
else:
print('NOT ANAGRAM!')
# Main Execution
if __name__ == '__main__':
main()
| true |
0b777077897ac2ae8fc9bea47dae6853cafd31fd | jemarsha/leetcode_shenanigans | /Random_problems/Merged_k_linked_lists.py | 1,138 | 4.375 | 4 | #from typing import List
class Node:
def __init__(self,value):
self.value = value
self.next = None
def merge_lists(lists):
"""
This function merges sorted linked lists- Reads the values in one at a time into a list O(kn). Then
sorts them O(nlogn). Then puts them into a linked list (O(n). Overall complexity is O(kn). This can be improved
@param lists: list of sorted linked lists
@return: a sorted linked list
"""
nodes = []
head = point= Node(0)
for val in lists:
while val:
nodes.append(val.value)
val= val.next
nodes = sorted(nodes)
for val2 in nodes:
point.next = Node(val2)
print(point.next.value, end = '->')
point= point.next
#return(nodes)
print('\n')
return head.next.value
if __name__ == "__main__":
list_1 = Node(1)
list_1.next = Node(4)
list_1.next.next = Node(5)
list_2 = Node(1)
list_2.next = Node(3)
list_2.next.next = Node(4)
list_3 = Node(2)
list_3.next = Node(6)
k_lists = [list_1, list_2, list_3]
print((merge_lists(k_lists))) | true |
70826eefc7345f3d96c93173f0b17a4b5c1123e5 | Sumanpal3108/21-days-of-programming-Solutions | /Day14.py | 371 | 4.625 | 5 | str1 = input("Enter any String: ")
str2 = input("Enter the substring you want to replace: ")
str3 = input("Enter the string you want to replace it with: ")
s = str1.replace(str2,str3)
print("The original string is: ",str1)
print("The substring you want to replace: ",str2)
print("The string you want to use instead: ",str3)
print(s)
input("Enter any key to exit") | true |
fe511ba08d1ba756f4a7b7122ccee3b331bdf1a3 | Yasir77788/Shopping-Cart | /shoppingCart.py | 1,959 | 4.21875 | 4 | # shopping cart to perform adding, removing,
# clearing, and showing the items within the cart
# import functions
from IPython.display import clear_output
# global list variable
cart = []
# create function to add items to cart
def addItem(item):
clear_output()
cart.append(item)
print("{} has been added.".format(item))
# create function to remove item from cart
def removeItem(item):
clear_output()
try:
cart.remove(item)
print("{} has been removed.".format(item))
except ValueError as e:
print("Sorry we could not remove that item.")
print(e)
# create fucntio to show items int cart
def showCart():
clear_output()
if cart:
print("Here is your cart:")
for item in cart:
print("- {}".format(item))
else:
print("Your cart is empty.")
# create function to clear itmes from the cart
def clearCart():
clear_output()
cart.clear()
print("Your cart is empty")
# creat main function that loops until the user quit
def main():
done = False
while not done:
print("\nPlease, select one option from the following:")
ans = input("\nquit/add/remove/show/clear: ").lower()
if ans == "quit":
print("Thanks for using...")
showCart()
done = True
elif ans == "add":
item = input("What would you like to add? ").title()
addItem(item)
elif ans == "remove":
showCart()
item = input("What item would u like to remove? ").title()
removeItem(item)
elif ans == "show":
showCart()
elif ans == "clear":
clearCart()
print("Cart has been cleared.")
else:
print("Sorry that was not an option.")
# run the programm
if __name__ == "__main__":
main()
| true |
6f4cfa2188d0845d9ad888f1540edd6f74c83b87 | Kevinloritsch/Buffet-Dr.-Neato | /Python Warmup/Warmup #3 - #2 was Disneyland/run3.py | 766 | 4.125 | 4 | import math
shape = input("What shape do you want the area of? Choose a rectangle, triangle, or circle ;) ")
if shape=='rectangle':
rone = input("What is the length of the first side? ")
rtwo = input("What is the length of the second side? ")
answer = int(rone)*int(rtwo)
print(answer)
elif shape=='triangle':
tone = input("What is the length of the base? ")
ttwo = input("What is the length of the height? ")
answer = int(tone)*int(ttwo)
answer = int(answer)/2
print(answer)
elif shape=='circle':
cone = input("What is the length of the radius? ")
answer = int(cone)*int(cone)
answer = int(answer)*math.pi
print("Your answer is approximatly", answer, end='\n')
else:
print("Loser--not a valid shape...")
| true |
27fd01098ce6f68a304f25eb885af97217863453 | shivambhojani/Python-Practice | /remove_char.py | 372 | 4.3125 | 4 | # Write a method which will remove any given character from a String?
def remove(str, char):
new_str = ""
for i in range(0, len(str)):
if i != char:
new_str = new_str + str[i]
return new_str
a = input("String: ")
b = int(input("which Character you want to remove: "))
b = b-1
new_string = remove(a, b)
print(new_string)
| true |
4067c6b39abf37b18537c930109aa732e9dfe885 | menliang99/CodingPractice | /PeakingIterator.py | 714 | 4.25 | 4 | # Decorator Pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.
class PeekingIterator(object):
def __init__(self, iterator):
self.iter = iterator
self.peekFlag = False
self.nextElement = None
def peek(self):
if not self.peekFlag:
self.nextElement = self.iter.next()
self.peekFlag = True
return self.nextElement
def next(self):
if not self.peekFlag:
return self.iter.next()
nextElement = self.nextElement
self.peekFlag = False
self.nextElement = None
return nextElement
def hasNext(self):
return self.peekFlag or self.iter.hasNext()
| true |
0312a221309f546836230b69bf7b6c81f02bac56 | mhetrick29/COS429_Assignments | /A4_P2/relu_backprop.py | 1,208 | 4.15625 | 4 | def relu_backprop(dLdy, x):
import numpy as np
# Backpropogates the partial derivatives of loss with respect to the output
# of the relu function to compute the partial derivatives of the loss with
# respect to the input of the relu function. Note that even though relu is
# applied elementwise to matrices, relu_backprop is consistent with
# standard matrix calculus notation by making the inputs and outputs row
# vectors.
# dLdy: a row vector of doubles with shape [1, N]. Contains the partial
# derivative of the loss with respect to each element of y = relu(x).
# x: a row vector of doubles with shape [1, N]. Contains the elements of x
# that were passed into relu().
# return:
# [dLdX]: a row vector of doubles with shape [1, N]. Should contain the
# partial derivative of the loss with respect to each element of x.
# TODO: Implement me!
dLdX = np.multiply(dLdy, dRelu(x))
return dLdX
# helper function to get all values in x greater than 0 and turn into 1
# this is 'Z' function
def dRelu(x):
for i in range(len(x)):
if (x[0][i] > 0):
x[0][i] = 1
else:
x[0][i] = 0
return x
| true |
e56c29cc6afc63b4ec4cf5afc97355e0385ee367 | nunu2021/DijkstraPathFinding | /dijkstra/basic_algo.py | 2,208 | 4.125 | 4 | import pygame
graph = {
'a': {'b': 1, 'c': 1, 'd': 1},
'b': {'c': 1, 'f': 1},
'c': {'f': 1, 'd': 1},
'd': {'e': 1, 'g': 1},
'e': {'g': 1, 'h': 1},
'f': {'e': 1, 'h': 1},
'g': {'h': 1},
'h': {'g': 1},
}
def dijkstra(graph, start,goal):
shortest_distance ={} # records the cost to reach to that node
track_predecessor = {} # keep track of the path that has led us to this node
unseenNodes = graph # to iterate through the entire graph
infinity = 9999999999 # infinity can basically be considered a very large number
track_path = [] # going to trace out journey back to the source node, which is the optimal route
for node in unseenNodes:
shortest_distance[node] = infinity
shortest_distance[start] = 0
while unseenNodes:
min_distance_node = None
for node in unseenNodes:
if min_distance_node == None:
min_distance_node = node
elif shortest_distance[node] < shortest_distance[min_distance_node]:
min_distance_node = node
path_options= graph[min_distance_node].items()
for child_node, weight in path_options: # checks if the path to
if weight + shortest_distance[min_distance_node] < shortest_distance[child_node]:
shortest_distance[child_node] = weight + shortest_distance[min_distance_node]
track_predecessor[child_node] = min_distance_node
# since dijkstra's algo does not allow back tracking, we will not be able to visit the nodes we have already gone through
unseenNodes.pop(min_distance_node)
# vvv before this code, the program has the shortest path from anywhere to anywhere.
currentNode = goal
while currentNode != start:
try:
track_path.insert(0, currentNode)
currentNode = track_predecessor[currentNode]
except KeyError:
print('Path is not reachable')
break;
track_path.insert(0, start)
if shortest_distance != infinity:
print("Shortest Distance is " + str(shortest_distance[goal]))
print("Optimal path is: " + str(track_path))
dijkstra(graph, 'a', 'h')
| true |
079b0e961c408f6b2b6c8edf65b56eaa0f2b4e61 | WaqasAkbarEngr/Python-Tutorials | /smallest_number.py | 612 | 4.1875 | 4 | def smallest_number():
numbers = []
entries = input("How many number you want to enter? ")
entries = int(entries)
while entries > 0:
entered_number = input("Enter a number? ")
numbers.append(entered_number)
smallest_number = entered_number
entries = entries - 1
print()
print("Your entered numbers are ",numbers)
for x in numbers:
if x < smallest_number:
smallest_number = x
print()
print("Smallest number is",smallest_number)
print()
input("Press any key to exit")
return ()
smallest_number() | true |
83265b7915746a67e8240e49d3819e8e6d840526 | cmobrien123/Python-for-Everybody-Courses-1-through-4 | /Ch7Asmt7.2.py | 1,146 | 4.34375 | 4 | # Exercise 7.2: Write a program to prompt for a file name, and then read
# through the file and look for lines of the form:
# X-DSPAM-Confidence:0.8475
# When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
# the line to extract the floating-point number on the line. count these lines
# and then compute the total of the spam confidence values from these lines.
# When you reach the end of the file, print out the average spam confidence.
# Enter the file name: mbox.txt
# Average spam confidence: 0.894128046745
# Enter the file name: mbox-short.txt
# Average spam confidence: 0.750718518519
# Test your file on the mbox.txt and mbox-short.txt files.
hname = input('please enter file name')
fname = open(hname)
# fname = open('mbox-short.txt')
total= 0
count = 0
for line in fname:
if not line.startswith('X-DSPAM-Confidence:'):
continue
# print(line)
# print(len(line))
x =line[20:27]
y= float(x)
# print(y)
total = total + y
count= count +1
# print(total)
# print(count)
avg = total/count
avgg = str(avg)
# print(avg)
print("Average spam confidence:", avgg)
# print('done')
| true |
d0a8a00b9834f82ef386fb2d2bc1a93bbd5c092a | arkadym74/pthexperience | /helloworld.py | 1,664 | 4.3125 | 4 | #Prints the Words "Hello World"
'''This is a multiline comment'''
print("Hello World")
userAge, userName = 30, 'Peter'
x = 5
y = 10
y = x
print("x = ", x)
print("y = ", y)
brand = 'Apple'
exchangeRate = 1.235235245
message = 'The price of this {0:s} laptop is {1:d} USD and the exchange rate is {2:4.2f} USD to 1 EUR'.format('Apple', 1299, 1.235235245)
message1 = '{0} is easier than {1}'.format('Pyhon', 'Java')
message2 = '{1} is easier than {0}'.format('Python', 'Java')
message3 = '{:10.2F} and {:d}'.format(1.234234234, 12)
message4 = '{}'.format(1.234234234)
print(message1)
print(message2)
print(message3)
print(message4)
#List
userAge = [21, 22, 23 ,24, 25]
userAge3 = userAge[2:4]
print(userAge3)
userAge4 = userAge[1:5:2]
print(userAge4)
userAge5 = userAge[:4]
print(userAge5 )
userAge[2] = 30
print(userAge)
userAge.append(100)
print(userAge)
del userAge[3]
print(userAge)
myList = [1,2,3,4,5,"Hello"]
print(myList)
print(myList[2])
print(myList[-1])
myList2 = myList[1:5]
print(myList2)
myList[1] = 20
print(myList)
myList.append('How are you')
print(myList)
del myList[6]
print(myList)
#Tupple
monthOfYear = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct","Nov", "Dec")
print(monthOfYear[0])
print(monthOfYear[-1])
#Dictionary
userNameAndAge = {"Peter":38, "John":51, "Alex":13, "Alvin":"Not Available"}
print(userNameAndAge)
userNameAndAge = dict(Peter = 38, John = 51, Alex = 13, Alvin = "Not Available")
print(userNameAndAge)
print(userNameAndAge["John"])
userNameAndAge["John"] = 21
print(userNameAndAge)
userNameAndAge = {}
userNameAndAge["Joe"] = 40
print(userNameAndAge)
| true |
4af66f31e555e7fd67d00869653e8c7048c1f472 | mgomesq/neural_network_flappybird | /FlappyBird/brain.py | 1,735 | 4.46875 | 4 | # -*- coding: utf-8 -*-
'''
Brain
=====
Provides a Brain class, that simulates a bird's brain.
This class should be callable, returning True or False
depending on whether or not the bird should flap its wings.
How to use
----------
Brain is passed as an argument to Bird, which is defined in
the classes module.
'''
import numpy as np
class Brain:
''' An abstraction of a flappy bird's brain.
The brain is a Neural Network with two input nodes, one
hidden layer with 6 nodes and one output node.
Arguments
---------
weights1 - weights mapping input to first hidden layer,
has shape (6,2)
weights2 - weights mapping first hidden layer to output,
has shape (1,6)
'''
def __init__(self, weights1: np.array, weights2: np.array):
self.weights1 = weights1
self.weights2 = weights2
self.activation = lambda x: 1 if x > 0.5 else 0
def __call__(self, information: np.array):
''' Here should be defined the main logic for flapping.
Arguments
---------
information - Information is a np.array containing the inputs
the bird will use to make an informed decision.
Returns
-------
Returns a boolean corresponding to the decision of
wing flapping.
'''
layer1_output = np.matmul(self.weights1, information)
layer1_output = np.array([self.activation(value) for value in layer1_output])
layer2_output = np.matmul(self.weights2, layer1_output)
layer2_output = np.array([self.activation(value) for value in layer2_output])
if layer2_output[0] == 1:
return True
return False
| true |
bba081265a85bbf2988ee18245ba83140fe8bb4a | Tlepley11/Home | /listlessthan10.py | 225 | 4.1875 | 4 | #A program that prints all integers in a list less than a value input by the user
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
x = input("Please enter a number: ")
b = []
for i in a:
if i < x: print(i); b.append(i)
print(b)
| true |
b652e232cb08379678bcdd9173d596a4afef4a05 | jamie0725/LeetCode-Solutions | /566ReshapetheMatrix.py | 1,737 | 4.25 | 4 | """
n MATLAB, there is a very useful function called 'reshape', which can reshape
a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive
integers r and c representing the row number and column number of the wanted
reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original
matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal,
output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4].
The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the
previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the
original matrix.
"""
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
nNums = []
temp = [0] * c
oR = 0
oC = 0
if r * c != len(nums)*len(nums[0]):
return nums
for rIndex in range(r):
for cIndex in range(c):
temp[cIndex] = nums[oR][oC]
if oC + 1 == len(nums[0]):
oR += 1
oC = 0
else:
oC += 1
if cIndex == c - 1:
nNums.append(temp[0:])
return nNums
| true |
293fe7ead7c870e3f25bde546f2b34337eb32378 | optionalg/cracking_the_coding_interview_python-1 | /ch4_trees_and_graphs/4.2_minimal_tree.py | 1,190 | 4.125 | 4 | # [4.2] Minimal Tree: Given a sorted(increasing order)
# array with unique integer elements, write an algorithm
# to create a binary search tree with minimal height
# Space complexity:
# Time complexity:
import unittest
def create_bst(array):
if not array:
return None
elif len(array) == 1:
return TreeNode(array[0])
n = len(array)
head_node = TreeNode(array[n/2])
left_child = create_bst(array[:n/2])
right_child = create_bst(array[n/2 + 1:])
head_node.left = left_child
head_node.right = right_child
return head_node
class Test(unittest.TestCase):
def test_create_bst(self):
bst = create_bst([2,3,4,5,6,7])
self.assertEqual(bst.value, 5)
self.assertEqual(bst.left.value, 3)
self.assertEqual(bst.left.left.value, 2)
self.assertEqual(bst.left.right.value, 4)
self.assertEqual(bst.right.value, 7)
self.assertEqual(bst.right.left.value, 6)
class TreeNode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
if __name__ == '__main__':
unittest.main()
| true |
b0d9de4d3f59d074ea1ffc412a99e8610ddccab6 | optionalg/cracking_the_coding_interview_python-1 | /ch5_bit_manipulation/5.7_pairwise_swap.py | 1,734 | 4.15625 | 4 | # [5.7] Pairwise Swap: Write a program to swap odd and even bits
# in an integer with as few instructions as possible (e.g., bit
# 0 and bit 1 are swapped, bit 2 and bit 3 and swapped, and so on)
import unittest
def pairwise_swap(num):
even_mask = create_even_mask(num)
odd_mask = create_odd_mask(num)
even_cleared = num & even_mask
odd_cleared = num & odd_mask
combined = (odd_cleared >> 1) | (even_cleared << 1)
return (odd_cleared >> 1) | (even_cleared << 1)
def create_odd_mask(num):
bin_representation = bin(num)[2:]
bit_length = len(bin_representation)
bit_sign = '0'
mask = []
for i in range(bit_length):
mask.insert(0, bit_sign)
bit_sign = '1' if bit_sign =='0' else '0'
return int(''.join(mask),2)
def create_even_mask(num):
bin_representation = bin(num)[2:]
bit_length = len(bin_representation)
bit_sign = '1'
mask = []
for i in range(bit_length):
mask.insert(0, bit_sign)
bit_sign = '1' if bit_sign =='0' else '0'
return int(''.join(mask),2)
class Test(unittest.TestCase):
def test_create_even_mask(self):
self.assertEqual(create_even_mask(int('111000', 2)), int('010101',2))
self.assertEqual(create_even_mask(int('1110000', 2)), int('1010101',2))
def test_create_odd_mask(self):
self.assertEqual(create_odd_mask(int('111000', 2)), int('101010',2))
self.assertEqual(create_odd_mask(int('11100110', 2)), int('10101010',2))
def test_pairwise_swap(self):
self.assertEqual(pairwise_swap(int('111000',2)), int('110100',2))
self.assertEqual(pairwise_swap(int('11100111',2)), int('11011011',2))
if __name__ == '__main__':
unittest.main()
| true |
3dc3b3e5045027bcccafc7907b667a0d2c8ec606 | optionalg/cracking_the_coding_interview_python-1 | /ch1_arrays_and_strings/1.1_is_unique.py | 798 | 4.1875 | 4 | # Time complexity: O(n) because needs to check each character
# Space complexity: O(c) where c is each character
import unittest
def is_unique(s):
# create a hashmap to keep track of char count
char_count = {}
for char in s:
# if character is not in hashmap add it
if not char in char_count:
char_count[char] = 1
else:
# if char is in hashmap, means there is a duplicate character
return False
return True
class Test(unittest.TestCase):
def test_unique(self):
self.assertTrue(is_unique('abcdefg'))
self.assertTrue(is_unique('1234567'))
self.assertFalse(is_unique('aabcdefg'))
self.assertFalse(is_unique('123456788'))
if __name__ == "__main__":
unittest.main()
| true |
738c5f3cfa7d3c58b05c5738822e0d807dbf1f7b | optionalg/cracking_the_coding_interview_python-1 | /ch8_recursion_and_dynamic_programming/8.1_triple_step.py | 1,634 | 4.15625 | 4 | # [8.1] Triple Step: A child is running up a staircase with n
# steps and can hop either 1 step, 2 steps, or 3 steps at a
# time. Implement a method to count how many possible ways
# the child can run up the stairs.
import unittest
def fib(n):
if n < 1:
raise ValueError('Must be positive Integer')
elif n < 3:
return 1
elif n < 4:
return 2
else:
a = 1
b = 1
c = 2
d = 4
for i in xrange(n-4):
a = b
b = c
c = d
d = a + b + c
return d
def fib_r(n):
memo = {}
return fib_r_helper(n, memo)
def fib_r_helper(n, memo):
if n in memo:
return memo[n]
if n < 1:
raise ValueError('Must be positive Integer')
elif n < 3:
return 1
elif n < 4:
return 2
else:
result = fib_r(n-1) + fib_r(n-2) + fib_r(n-3)
memo[n] = result
return result
class Test(unittest.TestCase):
def test_fib(self):
self.assertEqual(fib(1), 1)
self.assertEqual(fib(2), 1)
self.assertEqual(fib(3), 2)
self.assertEqual(fib(4), 4)
self.assertEqual(fib(5), 7)
self.assertEqual(fib(6), 13)
self.assertRaises(ValueError, fib, -1)
def test_fib_r(self):
self.assertEqual(fib_r(1), 1)
self.assertEqual(fib_r(2), 1)
self.assertEqual(fib_r(3), 2)
self.assertEqual(fib_r(4), 4)
self.assertEqual(fib_r(5), 7)
self.assertEqual(fib_r(6), 13)
self.assertRaises(ValueError, fib_r, -1)
if __name__ == '__main__':
unittest.main()
| true |
fdee0f3aaae1372696e95ba72cb3ca090df592fb | pieland-byte/Introduction-to-Programming | /week_4/ex_3.py | 1,341 | 4.3125 | 4 | #This program creates a dictionary from a text file of cars and prints the
#oldest and newest car from the original file
#create a list from the text file
def car_list():
car_list = [] #Empty list
with open ("cars_exercise_3.txt" , "r") as car_data: #Open text file in read mode
for line in car_data: #With every line in text file
car_list.append(line.rstrip("\n")) #Append line to car_list
return car_list
#Create a dictionary of the car information giving the keys as "make", "model" and "year"
def car_dict():
i = 0
car_dict = []
car_1 = car_list()
while i <len(car_1):
car_dict.append({"make" : car_1[i], "model" : car_1[i + 1], "year" : car_1[i + 2]})
i += 3
return car_dict
#Return the newest car
def newest():
newest = max(car_dict(), key=lambda x: x["year"]) #Find the car with the highest value in key "year"
return newest
def oldest():
oldest = min(car_dict(), key=lambda x: x["year"]) #Find the car with the lowest value in key "year"
return oldest
print("The newest car is: ", newest())
print("The oldest car is: ", oldest())
| true |
c546d7555f99c6bb2b2fa6d0266e6615256aecb2 | pieland-byte/Introduction-to-Programming | /week_3/ex_2.py | 1,309 | 4.625 | 5 | #This program calculates the volume of given shapes specified by
#the user using recursion
import math
# creating a menu with options for user input
def main_menu():
menu_choice = input("Please type 1 for sphere, 2 for cylinder and 3 for cone: ")
if menu_choice == "1":
result = sphere(int(input("Enter radius of sphere ")))
print("volume of sphere is", result)
elif menu_choice == "2":
radius = int(input("Enter radius: "))
height = int(input("Enter height: " ))
result = cylinder(radius, height)
print("Volume of cylinder is ", result)
elif menu_choice == "3":
radius = int(input("Enter radius: "))
height = int(input("Enter height: " ))
result = cone(radius,height)
print("volume of cone is", result)
else:
print("input error")
main_menu()
# function to calculate volume of sphere radius r
def sphere(r):
return (math.pi *(r **3))* (4/3)
#function to calculate volume of cylinder with radius r and height h
def cylinder(r,h):
return (math.pi * r**2) * h
# function to calculate volume of cone with radius r and height h
def cone(r,h):
return ((math.pi * r**2) * h)* (1/3)
main_menu()
| true |
119d31f2c4846ba1416da750b0e87a38d77509f3 | pieland-byte/Introduction-to-Programming | /week_4/ex_2.py | 1,159 | 4.15625 | 4 | #This program asks the user to name a sandwich ingredient and shows
#corresponding sandwiches from the menu
sandwiches = [] #Empty list
with open ("menu.txt","r") as menu: #Read menu.txt
for line in menu: #For each line
sandwiches.append(line.rstrip("\n")) #Add line to sandwiches list without newline
def sand_choice():
choice = input("Enter which sarnie you would like: ") #User input choice
choice = choice.title() #Convert input to title case
if len(choice) < 3: #To prevent input of string with 1 or 2 characters or spaces from returning a valid result
print("Please enter a valid choice")
sand_choice()
else:
for n in sandwiches: #Look through sandwich list
if choice in n: #If user input matches substring in string list sandwiches
print("We have",n,"available") #Print multiple response
sand_choice()
| true |
401075a7b543a9eb6a6d81c820a371aa3a24a66f | pieland-byte/Introduction-to-Programming | /week_4/ex_1.py | 546 | 4.1875 | 4 | #This program asks the user to name a sandwich and shows corresponding
#sandwiches from the menu
sandwiches = []
with open ("menu.txt","r") as menu:
for line in menu:
sandwiches.append(line.rstrip("\n"))
def sandwich_choice():
choice = input("Enter which sarnie you would like: ")
for ind in sandwiches:
if choice in sandwiches:
print("We have",choice,"available")
break
else:
print("That is unavailable, sorry.")
break
sandwich_choice()
| true |
0cbb1fbbfac2c26c8bba84d4ae8ca5a74ec76b98 | ioana01/Marketplace | /tema/consumer.py | 2,311 | 4.28125 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Thread
import time
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
"""
Constructor.
:type carts: List
:param carts: a list of add and remove operations
:type marketplace: Marketplace
:param marketplace: a reference to the marketplace
:type retry_wait_time: Time
:param retry_wait_time: the number of seconds that a producer must wait
until the Marketplace becomes available
:type kwargs:
:param kwargs: other arguments that are passed to the Thread's __init__()
"""
Thread.__init__(self)
self.carts = carts
self.marketplace = marketplace
self.retry_wait_time = retry_wait_time
self.cart_id = marketplace.new_cart()
self.name = kwargs['name']
def run(self):
# The list of carts is iterated
for i in range(0, len(self.carts)):
# The list of products of the current cart is iterated
for j in range(0, len(self.carts[i])):
# Check the type of the operation
if self.carts[i][j]['type'] == 'add':
# Call the add_to_cart method until the desired quantity is added
# If the product is not available, the consumer will wait
for _ in range(0, self.carts[i][j]['quantity']):
while not self.marketplace.add_to_cart(
self.cart_id, self.carts[i][j]['product']):
time.sleep(self.retry_wait_time)
elif self.carts[i][j]['type'] == 'remove':
# Call the remove_from_cart method until the desired quantity is removed
for _ in range(0, self.carts[i][j]['quantity']):
self.marketplace.remove_from_cart(self.cart_id, self.carts[i][j]['product'])
# Print the final order of the consumer
product_list = self.marketplace.place_order(self.cart_id)
for product, _ in product_list:
print(self.name, "bought", product[0])
| true |
4ff3e99a408d896b4260680980b204794cae01f4 | dnaport22/pyex | /Functions/averageheight.py | 1,081 | 4.15625 | 4 | #~PythonVersion 3.3
#Author: Navdeep Dhuti
#StudentNumber: 3433216
#Code below generate answer for question::
#What is the average value of the numbers in the field [height] in the range(1.75)and(2.48)inclusive?
#Function starts
def Average_height(doc_in):
doc = open(doc_in+'.csv','r') #Open the input file came from 'infile'
#initialise variables
firstline = True
numofheight = 0
sumofheight = 0
#passing file into a for loop
for data_fields in doc:
if firstline:
firstline = False
else:
#splitting and organising the data in file
data_fields = data_fields.strip().split(',')
#defining variable required for calculation
height = float(data_fields[5])
if height >= 1.75 and height <= 2.48:
numofheight += 1
sumofheight += height
#calculating average
average_height = numofheight/sumofheight
#rturning average
return ('%f'%average_height)
#closing opened file
doc.close()
| true |
a9fb3bc90fe2ce347f1ca6ea02239760e35963e6 | PhaniMandava7/Python | /Practice/Sets.py | 591 | 4.40625 | 4 | # Sets are collection of distinct elements with no ordering.
# Sets are good at membership testing.
# empty_set = {} -------> this creates a dict.
empty_set = set()
courses_set = {'History', 'Physics', 'Math'}
print(courses_set)
courses_set.add('Math')
print(courses_set)
print('Math' in courses_set)
courses_set = {'History', 'Physics', 'Math'}
courses_set2 = {'History', 'Arts', 'Music'}
print(courses_set.intersection(courses_set2))
print(courses_set.difference(courses_set2))
# courses_set.difference_update(courses_set2)
# print(courses_set)
print(courses_set.union(courses_set2)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.