blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7c84e6e89a805b58125905b65148432c6e189677 | kagomesakura/numBob | /numBob.py | 280 | 4.15625 | 4 | #print how many times the word bob occurs in string
s = 'azcbobobegghakl'
numBob = 0
for i in range(len(s)):
if s[i:i+3] == "bob":
# [i:i+3] checks the current char + the next three chars.
numBob += 1
print ('Number of times bob occurs is: ' + str(numBob))
| true |
d3e9ca28d8c7bfb6c93c3580ed3dffd5f0f6cabd | edubs/lpthw | /ex03.py | 1,216 | 4.65625 | 5 | # Study drills
# 1 above each line, user the # to write a comment to yourself explaining what the line does
# 2 remember in exercise 0 when you started python3.6? start python3.6 this way again and using the math operators, use python as a calculator
# 3 find something you need to calculate and write a new .py file that does it
# 4 rewrite ex3.py to use floating point numbers so it's more accurate. 20.0 is floating point
print("I will now count my chickens:")
# divides 30 by 6 (5) then adds 25 resulting in 30.0
print("Hens", 25.0 + 30.0 / 6.0)
# 100 - 3 = 97
# 25 by 3 (75) then mods 4 resulting 3, the amount from 75 leftover after 18*4 (72)
print("Roosters", 100.0 - 25.0 * 3.0 % 4.0)
# gratuitous order of operations exercise
print("Now I will count the eggs:")
print(3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0)
print("Is it true that 3.0 + 2.0 < 5.0 - 7.0?")
print(3.0 + 2.0 < 5.0 - 7.0)
print("What is 3.0 + 2.0?", 3.0 + 2.0)
print("What is 5.0 - 7.0?", 5.0 - 7.0)
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5.0 > -2.0)
print("is it greater or equal?", 5.0 >= -2.0)
print("is it less or equal?", 5.0 <= -2.0)
| true |
6c99118054f5d24b3d145b5902fb77c66802a8b2 | Renjihub/code_training | /Python/Duplicates.py | 446 | 4.34375 | 4 | # Print duplicate characters from string
# Take sample string and print all duplicate characters.
sample_str = "Helloo"
print("Sample String :",sample_str)
duplicate = set()
for char in sample_str:
count = 0
for char_s in sample_str:
if char.lower()==char_s.lower():
count = count+1
if count>1:
duplicate.add(char)
if duplicate:
print("Duplicate elements are : ",duplicate)
else:
print("No repeating character found.")
| true |
2d3c303813ec11805c04eaa1618963857e88ee64 | mygerges/100-Days-of-Code | /Nested Condition.py | 347 | 4.15625 | 4 | height = float(input("Please enter your height: "))
age = int(input("Enter your age: "))
if height > 120:
if age < 12 :
print("You can Play, and payment $5")
elif age <= 18:
print("You can Play, and payment $7")
else:
print("You can Play, and payment $12")
else:
print("Sorry can't play due to your height") | true |
a6d8d8d27cdc5053037f52ce897fb6c6844277e3 | naumanasrari/NK_PyGamesBook | /1-chap1-get-started.py | 355 | 4.34375 | 4 | x=3
y=2
mul = x * y
add1 = x + y
sub1 = x - y
dev1 = x / y
expon1 = x ** y
print("multiplication of x and y: ",mul)
print("Addition of x and y: ",add1)
print("Substraction of x and y: ",sub1)
print(" Divsion of x and y in Integer: ",int(dev1))
print(" Divsion of x and y in Float: ",float(dev1))
print("Exponent of x and y: ",expon1)
#print(result)
| true |
9d93d0a24c3c8072c13e033f9ad8a6e1a3858eed | rbabaci1/CS-Module-Recursive_Sorting | /src/searching/searching.py | 2,178 | 4.28125 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
midpoint = (start + end) // 2
if start > end:
return -1
if arr[midpoint] == target:
return midpoint
if arr[midpoint] > target:
return binary_search(arr, target, start, midpoint - 1)
else:
return binary_search(arr, target, midpoint + 1, end)
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
def agnostic_binary_search(arr, target):
isAsc, start, end = False, 0, len(arr) - 1
if len(arr) >= 2:
if arr[0] < arr[-1]:
isAsc = True
while start <= end:
midpoint = (start + end) // 2
if arr[midpoint] == target:
return midpoint
if isAsc:
if arr[midpoint] > target:
end = midpoint - 1
else:
start = midpoint + 1
else:
if arr[midpoint] > target:
start = midpoint + 1
else:
end = midpoint - 1
return -1
# def isAscending(arr):
# if len(arr) >= 2:
# if arr[0] < arr[1]:
# return True
# return False
# def agnostic_recursive_binary_search(arr, target, start=0, end=None):
# isAsc = isAscending(arr)
# if not end:
# end = len(arr) - 1
# midpoint = (start + end) // 2
# # base cases
# if start > end:
# return -1
# if arr[midpoint] == target:
# return midpoint
# if isAsc:
# if arr[midpoint] > target:
# return agnostic_binary_search(arr, target, start, midpoint - 1)
# else:
# return agnostic_binary_search(arr, target, midpoint + 1, end)
# else:
# if arr[midpoint] > target:
# return agnostic_binary_search(arr, target, midpoint + 1, end)
# else:
# return agnostic_binary_search(arr, target, start, midpoint - 1)
# return -1
| true |
2fff7530868944972faeaee929f3a617c6693bfd | sagsam/learn-python | /string-manipulation.py | 1,718 | 4.125 | 4 | print('C:\some\name') # here \n means newline!
# o/p :
###########
# C:\some #
# ame #
###########
# If you don’t want characters prefaced by \ to be interpreted as special characters,
# you can use raw strings by adding an r before the first quote:
print(r'C:\some\name') # note the r before the quote
# o/p :
################
# C:\some\name #
################
# String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''.
# End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line.
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
# Sting Concatination
print(3 * 'un' + 'ium') # 3 times 'un', followed by 'ium'
print('Py''thon')
text = ('Put several strings within parentheses '
'to have them joined together.')
print(text)
prefix = 'Py'
# print(prefix 'thon') error
print(prefix + 'thon') #concatenate variables or a variable and a literal, with +:
print(len(text))
word = 'Python'
print(word[5]) # character in position 5
# since -0 is the same as 0, negative indices start from -1.
print(word[-1]) # last character
# Slicing
print(word[0:2]) # characters from position 0 (included) to 2 (excluded)
# start is always included, and the end always excluded.
# s[:i] + s[i:] is always equal to s:
print(word[:2] + word[2:])
# an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
print(word[:2]) # character from the beginning to position 2 (excluded)
print(word[4:]) # characters from position 4 (included) to the end
| true |
f4d7d0ab00cc1438d2e66ba11b405006e1842922 | mohitgauniyal/Python-Learning | /list.py | 672 | 4.34375 | 4 | shopping_list = ["Apple","Banana"] #to create items list
print(shopping_list)
print(shopping_list[0:1]) #to print first two items from the list.
shopping_list.append("Mango") #to add items in the current list.
print(shopping_list)
del shopping_list[0] #to delete items from the list.
print(shopping_list)
shopping_list[1] = "MANGO" #to update the list item.
print(shopping_list)
print(len(shopping_list))
list_num = [0,1,2,3,4,44,5] #new list.
print(min(list_num)) #to print min.
print(max(list_num)) #to print max.
union_list = shopping_list + list_num #union of lists
print(union_list)
multiply_content = shopping_list * 2 #double the list items
print(multiply_content)
| true |
ef371444b4406e23c1be33ee8dce8449656f098d | MichealGarcia/code | /py3hardway/ex44f.py | 2,026 | 4.46875 | 4 | # Composition
# Inheritance is useful, but another way to do it
# is just to use other classes and modules
# rather than rely on implicit inhereitance.
# Two of three ways of inheritance involve writing new code
# to replace or alter funcitonality.
# This can be replicated by calling functions in a module.
#EXAMPLE:
class Other(object):
def override(self):
print("OTHER override()")
def implicit(self):
print("OTHER implicit()")
def altered(self):
print("OTHER altered()")
class Child(object):
def __init__(self):
self.other = Other()
def implicit(self):
# calling a method instead of rewriting the code.
# Isn't this the same as using pass????
self.other.implicit()
def override(self):
print("CHILD override()")
def altered(self):
print("CHILD, BEFORE OTHER altered()")
# So, instead of calling super()
self.other.altered()
print("CHILD, AFTER OTHER altered()")
son = Child()
son.implicit()
son.override()
son.altered()
# So, did I need to make class Other?
# When to use inheritance or composition
# You don't want duplicated code all over your software.
# It's not clean, or efficient.
# Inheritance solves the problem of reuse, but when is it appropriate?
# Inheritance is good for implied features set in base classes.
# Composition solves the issue by giving you modules and capability to call functions
# Both solve the problem, but when to use eachother?
# Subjective, but here is an answer.
# 1. Avoid multiple inheritance at all costs, as it's too complex to be
# Reliable. if you're stuck with it, then be prepared to know the class
# hierarchy and spend time finding where everything comes from.
# 2. Use composition to package code into modules that are used in many
# unrelated places and situations.
# 3. Use inheritance only when there are clearly related pieces of code that
# fit under a single concept or if you have to because of something you're using.
| true |
451431f093e7960dfa025130bb0b5a0d7f57794c | MichealGarcia/code | /py3hardway/ex9.py | 683 | 4.3125 | 4 |
# variable containing a string of each day
# of the week separated by a space
days = "Mon Tue Wed Thu Fri Sat Sun"
# using a back-slash n will print the following text in a new line.
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days: ", days)
print("Here are the months: ", months)
# This is new, and my guess is that using three quotes is the
# same as telling the print function to copy as typed including new lines.
# This also created the opportunity to use single and double quotes in the string.
print("""
Theres something going on here.
With three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""") | true |
62d63d655efd9c5fdd3dbfd1a18dd33b6e085fdf | MichalKala/Python_Guess_the_Number_game | /Python_Guess_the_Number_game/Python_Guess_the_Number_game.py | 1,004 | 4.3125 | 4 | import random
#generate computer's number
Computer_number = random.randint(0, 20)
print("Your opponent has secretly selected number between 0-20\nYour goal is to guess the number!")
print("")
#Set loop to let user repeat the choice until they win
Outcome = 0
while Outcome < 6:
#Let user to choose a number
User_choice = input("Guess the number: ")
print("")
#Check if enetered value is int
try:
User_number = int(User_choice)
except ValueError:
print("Please do not enter floating numbers or strings! Try again...")
print("")
break
User_choice = int(User_choice)
if Computer_number > User_choice:
print("Wrong! Your number is too low, please try again")
print("")
Outcome = 2
elif Computer_number < User_choice:
print("Wrong! Your number is too high, please try again")
print("")
Outcome = 4
else:
print("You win!!! Congratz!")
print("")
Outcome = 6
| true |
44b959d49f4f7c6ed97bbcb02cb11b7e3815c575 | sriley86/Python-4th | /Python Chapter 5 Maximum of Two Values.py | 567 | 4.53125 | 5 | # Chapter 4 Exercise 12 Maximum of Two Values
# Write a function named max that accepts two integer values as arguments
# and returns the value that is the greater of the two. Use the function in a
# program that prompts the user to enter two integer values. The program should
# display the value that is the greater of the two.
# Input
a = int(input('Enter a integer: '))
b = int(input('Enter another integer: '))
# Process and Output
def max(a, b):
if a > b:
print(a, 'is bigger than', b)
else:
print(b, 'is bigger than', a)
max(a, b) | true |
00899bc6681527a2f79b03a8fea5727a613d199a | sriley86/Python-4th | /Python Chapter 2 Sales Tax.py | 1,939 | 4.21875 | 4 | # Chapter2 Exercise 6 Sales Tax
# This program displays the Sales tax on purchased amount
# Definition of the main function
def main():
# Get the purchase amount
purchaseAmount = getinput()
print("The amount of the purchase:", purchaseAmount)
statesalestax = calstatesalestax(purchaseAmount)
print("The state sales tax:", statesalestax)
countysalestax = calcountysalestax(purchaseAmount)
print("The county sales tax:", countysalestax)
Totalsalestax = caltotalsalestax(statesalestax, countysalestax)
print("The total sales tax:", Totalsalestax)
Totalofthesale = totalofsale(purchaseAmount, Totalsalestax)
print("The total of the sale:", Totalofthesale)
# definition of getinput function
def getinput():
# Get the purchase amount
purchaseAmount = float(input("Enter the amount of a purchase:"))
return purchaseAmount
# Definition of the calstatesalestax function
def calstatesalestax(purchaseAmount):
# Assign the value to State sales tax percentage
Statesalestaxpercentage = 0.04
# Calculate the state sales tax
statesalestax = purchaseAmount * Statesalestaxpercentage
return statesalestax
# Definition of the calcountysalestax function
def calcountysalestax(purchaseAmount):
# Assign the value to county sales tax percentage
countysalestaxpercentage = 0.02
# Calculate the county sales tax
countysalestax = purchaseAmount * countysalestaxpercentage
return countysalestax
# Definition of the caltotalsalestax function
def caltotalsalestax(statesalestax, countysalestax):
# Calculate the total sales tax
Totalsalestax = statesalestax + countysalestax
return Totalsalestax
# Definition of the totalofsale function
def totalofsale(purchaseAmount, totalsalestax):
# Calculate the total of the sale
Totalofthesale = purchaseAmount + totalsalestax
return Totalofthesale
# calling the main function
main() | true |
4b86009c40bf7db7bab264dda8e59da68ba1640b | Magictotal10/FMF-homework-2020spring | /homework6/pandas_exercise.py | 1,264 | 4.25 | 4 | import pandas as pd
# Here you have to do some exercises to familiarize yourself with pandas.
# Especially some basic operations based on pd.Series and pd.DataFrame
# TODO: Create a Series called `ser`:
# x1 1.0
# x2 -1.0
# x3 2.0
# Your code here
ser = pd.Series([1.0, -1.0, 2.0],index=['x1','x2','x3'])
# TODO: Create a DataFrame called `df`:
# x0 x1 x2
# s0 -1.1 0.8 -2.5
# s1 -1.3 -1.0 -1.2
# s2 1.7 1.8 2.1
# s3 0.9 0.3 1.1
# Your code here
df = pd.DataFrame(
[[-1.1, 0.8, -2.5],
[-1.3, -1.0, -1.2],
[-1.7, 1.8, -2.1],
[-0.9, 0.3, 1.1],],
index=['s0','s1','s2','s3'],
columns=['x0','x1','x2']
)
# TODO: select `df` by column="x1":
print( df['x1'])
# TODO: select `df` by third row and first column:
print(df.iloc[2,0])
# TODO: change `df`'s column's name x0 to y0:
df = df.rename( columns={'x0':'y0'})
# TODO: select `df` where column's name start with x:
print( df[df.columns[df.columns.str.startswith('x')]])
# TODO: change `ser`'s index to [y0,x1,x2]:
ser.index = df.columns
# TODO: change `df` where column y0 multiply -1.5:
df['y0'] = df['y0'] * -1.5
# TODO: calculate `df` dot `ser`:
print(df.dot(ser))
# TODO: merge `ser` with the result of previous task:
df.append(ser, ignore_index=True)
| true |
5acffb9fb1eae601653914242f88d2ed5fac2fa3 | lightjameslyy/python-full-stack | /basics/02-python-basics/01_python_basics/lt_08_buy_apple_2.py | 205 | 4.21875 | 4 | # 1. input price of apple
price = float(input("price of apple per Kg: "))
# 2. input weight of apples
weight = float(input("weight of apples: "))
# 3. calculate money
money = weight * price
print(money) | true |
3e91a965e8381d5742cff08340f6a369a137ba91 | AswiniSankar/OB-Python-Training | /Assignments/Day-1/p9.py | 372 | 4.4375 | 4 | # program to find the given two string is equal or else which is smaller and bigger
string1 = input("enter the string1")
string2 = input("enter the string2")
if string1 == string2:
print("both strings are equal")
elif string1 > string2:
print(string1 + " is greater " + string2 + " is smaller")
else:
print(string1 + " is smaller " + string2 + " is greater")
| true |
f36d87c95330bca12b4d2caab7acd19336466d1e | AswiniSankar/OB-Python-Training | /Assignments/Day-5/p1.py | 334 | 4.15625 | 4 | # python program to calculate BMI of Argo
def BMIOfArgo(weight, height):
return (weight / (height * height))
age = int(input("Hai Arge, what is your Age?"))
weight = float(input("What is your weight in kg ?"))
height = float(input("What is your Height in meters"))
print("The MBI is {:.1f}".format(BMIOfArgo(weight, height)))
| true |
6a229363003fbc4d6a16a91fb9d82140c5e4c030 | AswiniSankar/OB-Python-Training | /Assignments/Day-5/p2.py | 806 | 4.28125 | 4 | # program to find BMI status
def toFindBMI(weight, height):
return round(weight / (height * height), 1)
def BMIstatus(BMIvalue):
if BMIvalue < 18.5:
print("your BMI is " + str(BMIvalue) + " which means you are underweight")
elif 18.5 <= BMIvalue and BMIvalue <= 24.9:
print("your BMI is " + str(BMIvalue) + " which means you are healthy")
elif 25.0 <= BMIvalue and BMIvalue <= 29.9:
print("your BMI is " + str(BMIvalue) + " which means you are overweight")
else:
print("your BMI is " + str(BMIvalue) + " which means you are obese")
name = input("what is your name? ")
height = float(input("Hai " + name + ", What is your Height in meters? "))
weight = float(input("What is your weight in kg? "))
result = toFindBMI(weight, height)
BMIstatus(result)
| true |
718fab3a92812374785b62fee3e140082e83626e | vikasbaghel1001/Hactoberfest2021_projects | /CDMA-Python/gen_file.py | 760 | 4.40625 | 4 | '''File Generator Module'''
# modify PATH variable according to the filepath you want generate files in
PATH = "./textfiles/input/input"
file_no = int(input('Enter Number of Files : '))
msg = input('Enter text : ')
print('Length of text is {}'.format(len(msg)))
def generate_files(num):
'''Function for generating files'''
while num:
with open(PATH + str(num) + '.txt', 'w', encoding='utf-8') as fptr:
fptr.write(msg)
num -= 1
print('Done! {} Files were created with "{}" written in each of them!'.format(file_no, msg))
ask = input('Are you sure to generate {} files? (y/N): '.format(file_no))
if ask in ('y', 'Y'): generate_files(file_no)
else: print('You chose not to generate any files!')
| true |
41dd03437d4a4bddca4781687897f8fc5a4a1abf | vikasbaghel1001/Hactoberfest2021_projects | /Weight conversion using Python Tkinter.py | 1,689 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 8 12:27:42 2021
@author: DHIRAJ
"""
# Python program to create a simple GUI
# weight converter using Tkinter
from tkinter import *
# Create a GUI window
window = Tk()
# Function to convert weight
# given in kg to grams, pounds
# and ounces
def convertfrom_kg():
# convert kg to gram
gram = float(e2_value.get())*1000
# convert kg to pound
pound = float(e2_value.get())*2.20462
# convert kg to ounce
ounce = float(e2_value.get())*35.274
# Enters the converted weight to
# the text widget
tt1.delete("1.0", END)
tt1.insert(END,gram)
tt2.delete("1.0", END)
tt2.insert(END,pound)
tt3.delete("1.0", END)
tt3.insert(END,ounce)
# Create the Label widgets
ee1 = Label(window, text = "Enter the weight in Kg")
ee2_value = StringVar()
ee2 = Entry(window, textvariable = e2_value)
ee3 = Label(window, text = 'Gram')
ee4 = Label(window, text = 'Pounds')
ee5 = Label(window, text = 'Ounce')
# Create the Text Widgets
tt1 = Text(window, height = 1, width = 20)
tt2 = Text(window, height = 1, width = 20)
tt3 = Text(window, height = 1, width = 20)
# Create the Button Widget
bb1 = Button(window, text = "Convert", command = convertfrom_kg)
# grid method is used for placing
# the widgets at respective positions
# in table like structure
ee1.grid(row = 0, column = 0)
ee2.grid(row = 0, column = 1)
ee3.grid(row = 1, column = 0)
ee4.grid(row = 1, column = 1)
ee5.grid(row = 1, column = 2)
tt1.grid(row = 2, column = 0)
tt2.grid(row = 2, column = 1)
tt3.grid(row = 2, column = 2)
bb1.grid(row = 0, column = 2)
# Start the GUI
window.mainloop()
| true |
f5f565eacee20a64965707cef7501f4265c34b1d | ncaleanu/allthingspython | /advanced_func/collections.py | 1,727 | 4.125 | 4 | '''
counter,
defaultdict,
ordereddict (not in this file),
namedtuple,
deque
'''
# counter - keeps track of how many times an element appears
from collections import Counter
'''
device_temp = [14.0, 14.5, 15.0, 14.0, 15.0, 15.0, 15.5]
temp_count = Counter(device_temp)
print(temp_count)
print(temp_count[14.0])
'''
# defaultdict - never raises key error, just returns the value
# returned by the func when the object was created
from collections import defaultdict
'''
coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'),('Rolf', 'Cambridge')]
# defaultdict takes in a function: list
alma_mater = defaultdict(list)
# if key doesnt exist in dict
# then function called empty list created ^^
for coworker in coworkers:
alma_mater[coworker[0]].append(coworker[1])
# If you want to raise an error from invalid keys,
# set default factory to None. Note that empty lists still created above
alma_mater.default_factory = None
print(alma_mater['Rolf'])
print(alma_mater['Noah'])
'''
# named tuple. A more explicit way of using tuples!
# Good for reading from databases and CSVs
from collections import namedtuple
'''
account = ('checking', 1850.90)
Account = namedtuple('Account', ['name', 'balance'])
accountNamedTuple = Account(*account)
print(accountNamedTuple)
print(accountNamedTuple._asdict()['balance'])
'''
# Double ended queue, can push/remove items from
# front or back of queue. GOOD FOR THREADS (thread safe)
from collections import deque
'''
friends = deque(('Rolf', 'Charlie', 'Jen', 'Anna'))
# Working at the back
friends.append('Jose')
friends.pop()
# Working at the start
friends.appendleft('Noah')
friends.popleft()
print(friends)
''' | true |
3da236e3ada6bafbcef1cfe174dc337ee879fbd4 | ncaleanu/allthingspython | /advanced_func/collections-exercises.py | 2,617 | 4.5 | 4 | from collections import defaultdict, OrderedDict, namedtuple, deque
# PRACTISING WITH SOME DATA STRUCTURES FROM COLLECTIONS
def task1() -> defaultdict:
"""
- create a `defaultdict` object, and its default value would be set to the string `Unknown`.
- Add an entry with key name `Alan` and its value being `Manchester`.
- Return the `defaultdict` object you created.
"""
# you code starts here:
task1 = defaultdict(lambda: 'Unknown')
task1.update({'Alan': 'Manchester'})
return task1
print(task1())
def task2(arg_od: OrderedDict):
"""
- takes in an OrderedDict `arg_od`
- Remove the first and last entry in `arg_od`.
- Move the entry with key name `Bob` to the end of `arg_od`.
- Move the entry with key name `Dan` to the start of `arg_od`.
- You may assume that `arg_od` would always contain the keys `Bob` and `Dan`,
and they won't be the first or last entry initially.
"""
# you code starts here:
arg_od.popitem(last=False) # removes first item
arg_od.popitem() # removes last item
arg_od.move_to_end('Bob') # moves Bob to end
arg_od.move_to_end('Dan', last=False) # moves Dan to front
print(arg_od)
o = OrderedDict([
('Alan', 'Manchester'),
('Bob', 'London'),
('Chris', 'Lisbon'),
('Dan', 'Paris'),
('Eden', 'Liverpool'),
('Frank', 'Newcastle')
])
print(o)
task2(o)
def task3(name: str, club: str) -> namedtuple:
"""
- create a `namedtuple` with type `Player`, and it will have two fields, `name` and `club`.
- create a `Player` `namedtuple` instance that has the `name` and `club` field set by the given arguments.
- return the `Player` `namedtuple` instance you created.
"""
# you code starts here:
Player = namedtuple('Player', ['name', 'club'])
player = Player(name, club)
return player
print(task3('Noah', 'BadGirlsClub'))
arg_deque = deque()
arg_deque.append("Noah")
arg_deque.append("Jop")
arg_deque.append("Hop")
arg_deque.append("Red")
arg_deque.append("Goop")
def task4(arg_deque: deque):
"""
- Manipulate the `arg_deque` in any order you preferred to achieve the following effect:
-- remove last element in `deque`
-- move the fist (left most) element to the end (right most)
-- add an element `Zack`, a string, to the start (left)
"""
# your code goes here
arg_deque.pop() # remove last item
arg_deque.rotate(-1) # move the first item to end
arg_deque.appendleft('Zack')
task4(arg_deque)
| true |
768599312e43354921ef68be9e2ac25d98f03b69 | MaxOvcharov/stepic_courses | /parser_csv_rss/login_validator.py | 1,045 | 4.21875 | 4 | """ Login validator """
import re
def check_login(login):
""" This function checks an login on the following conditions:
1) Check login using a regular expression;
2) Check len of login < 1 and login < 21;
3) Check the prohibited symbol in login;
4) Check login ends on latin letter or number;
"""
# Check len of login < 1 or login < 21
if (len(login) < 1) or (len(login) > 20):
raise ValueError('Login len out of range (1-20)')
# Check login using a regular expression
res = re.match(r'^([a-zA-z0-9.-]+)$', login)
if not res:
raise ValueError("Bad syntax of entered login")
# Check login ends on latin letter or number
if login.endswith(".") or login.endswith("-"):
raise ValueError("Login can not ends on '.' or '-'")
return True
if __name__ == '__main__':
# Enter your login
put_login = raw_input('Enter login here -> ')
# Start checking login
if check_login(put_login):
print "This is correct login: ", put_login
| true |
5cb487213c686fb99dafa28ba059dfa438b79183 | MohammedAbuMeizer/DI_Bootcamp | /Week_7/Day_2/Exercises XP #1/Exercise 2 What’s Your Favorite Book/Exercise 2 What’s Your Favorite Book .py | 284 | 4.125 | 4 | title = input("Enter a title of your favorite Book : ")
def favorite_book(title="Alice in Wonderland"):
print(f"One of my favorite books is {title}")
while title == "" or title ==" ":
print("You didnt type any title we will put our default")
title = "Alice in Wonderland"
favorite_book(title)
| true |
1c4d365c66a38cb35a2fee5fe6656d829888bc03 | mwilso17/python_work | /files and exceptions/reading_file.py | 508 | 4.34375 | 4 | # Mike Wilson 22 June 2021
# This program reads the file learning_python.txt contained in this folder.
filename = 'txt_files\learning_python.txt'
print("--- Reading in the entire file:")
with open(filename) as f:
contents = f.read()
print(contents)
print("\n--- Looping over the lines in the file.")
with open(filename) as f:
for line in f:
print(line.rstrip())
print("\n--- Storing the lines in a list:")
with open(filename) as f:
lines = f.readlines()
for line in lines:
print(line.rstrip()) | true |
77c0c93b87eacd40750c50ff1b4044ed9db38b6d | mwilso17/python_work | /OOP and classes/dice.py | 1,093 | 4.46875 | 4 | # Mike Wilson 22 June 2021
# This program simulates dice rolls and usues classes and methods from the
# Python standard library
from random import randint
class Die:
"""Represents a die that can be rolled."""
def __init__(self, sides=6):
"""Initialize the die. 6 by default."""
self.sides = sides
def roll_die(self):
"""Return a number between 1 and the number of sides."""
return randint(1, self.sides)
# Make a 6 sided die and roll it 10 times.
d6 = Die()
results = []
for roll_num in range(10):
result = d6.roll_die()
results.append(result)
print("\nThe 10 rolls of a 6 sided dice came up: ")
print(results)
# Make a 10 sided die and roll it 10 times.
d10 = Die(sides=10)
results = []
for roll_num in range(10):
result = d10.roll_die()
results.append(result)
print("\nThe 10 rolls of a 10 sided dice came up: ")
print(results)
# Make a 20 sided die and roll it 10 times.
d20 = Die(sides=20)
results = []
for roll_num in range(10):
result = d20.roll_die()
results.append(result)
print("\nThe 20 rolls of a 6 sided dice came up: ")
print(results) | true |
3bd1bc2752c36de661bea0628e1e544fa030d403 | mwilso17/python_work | /functions/cars.py | 412 | 4.25 | 4 | # Mike Wilson 20 June 2021
# This program stores info about a car in a dictionary.
def make_car(make, model, **other):
"""makes a dictionary for a car"""
car_dictionary = {
'make': make.title(),
'model': model.title(),
}
for other, value in other.items():
car_dictionary[other] = value
return car_dictionary
my_car = make_car('honda', 'civic', color='grey', repairs='engine')
print(my_car) | true |
0e0f98ebf7b50fa048c7d6f384cf7a297ac897a9 | mwilso17/python_work | /lists/lists_loops/slices/our_pizzas.py | 871 | 4.46875 | 4 | # Mike Wilson 8 June 2021
# This program slices from one list and adds it to another, while keeping
# two seperate lists that operate independantly of one another.
my_favorite_pizzas = ['pepperoni', 'deep dish', 'mushroom']
your_favorite_pizzas = my_favorite_pizzas[:]
print("My favorite pizzas are: ")
print(my_favorite_pizzas)
print("\nYou like many of the same pizzas I do!")
print("\nYour favorite pizzas are: ")
print(your_favorite_pizzas)
print("\n Let's add some more pizzas to our favorites.")
my_favorite_pizzas.append('extra cheese')
my_favorite_pizzas.append('salami')
your_favorite_pizzas.append('Detroit style')
your_favorite_pizzas.append('veggie')
print(my_favorite_pizzas)
print(your_favorite_pizzas)
for pizza in my_favorite_pizzas:
print(f"I really like {pizza} pizza!")
for pizza in your_favorite_pizzas:
print(f"You really like {pizza} pizza!") | true |
2d452ea8ecfeedd2a5c64bf6c75ffc230358f58b | mwilso17/python_work | /user input and while loops/movie_tickets.py | 590 | 4.15625 | 4 | # Mike Wilson 15 June 2021
# This program takes user input for age then returns the price of their movie
# ticket to them.
prompt = "\nWhat is your age? "
prompt += "\nEnter 'quit' when you are finished."
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10.")
elif age < 65:
print("Your ticket is $15.")
elif age < 400:
print("You get a senior discount. Your ticket is $12.")
elif age >= 400:
print("Sorry, we don't let vampires into this theater.") | true |
142c6b7728d282d6d2e1e60eddb6d50cb4193f12 | mwilso17/python_work | /functions/messages.py | 648 | 4.28125 | 4 | # Mike Wilson 20 June 2021
# This program has a list of short messages and displays them.
def show_messages(messages):
"""print messages in list"""
for message in messages:
print(message)
def send_messages(messages, sent_messages):
"""print each message and move it to sent messages"""
print("\nSending all messages")
while messages:
current_messages = messages.pop()
print(current_messages)
sent_messages.append(current_messages)
messages = ['hey!', 'What\'s up?', ':)']
show_messages(messages)
sent_messages = []
send_messages(messages[:], sent_messages)
print("\nFinal lists:")
print(messages)
print(sent_messages) | true |
a558286ad23fad033b1a2d61fd7d3e959723c13f | mwilso17/python_work | /user input and while loops/deli.py | 841 | 4.5 | 4 | # Mike Wilson 17 June 2021
# This program simulates a sandwich shop that takes sandwich orders
# and moves them to a list of finished sandwiches.
# list for sandwich orders
sandwich_orders = ['club', 'ham and swiss', 'pastrami', 'turkey', 'veggie']
# empty list for finished sandwiches
finished_sandwiches = []
# the following code lets customers know we are out of pastrami today
# and removes those orders from the list.
print("Sorry, but we are out of pastrami right now.")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
# code to 'make' sandwiches.
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print(f"I am making your {current_sandwich} sandwich now.")
finished_sandwiches.append(current_sandwich)
for sandwich in finished_sandwiches:
print(f"Here is your {sandwich} sandwich.") | true |
5fdff9be03e18e4ff1c7cc64cd210e32a82e3acf | mwilso17/python_work | /user input and while loops/dream_vacation.py | 674 | 4.34375 | 4 | # Mike Wilson 17 June 2021
# The following program polls users about their dream vacations.
# 3 prompts to be used
name_prompt = "\nWhat is your name? "
vacation_prompt = "If you could vacation anywhere in the world, where would you go? "
next_prompt = "\nWould someone else like to take the poll? (yes/no): "
# empty dictionary to store responses in
responses = {}
while True:
name = input(name_prompt)
vacation = input(vacation_prompt)
responses[name] = vacation
repeat = input(next_prompt)
if repeat != 'yes':
break
print("\n-------Results-------")
for name, place in responses.items():
print(f"{name.title()} would like to vacation to {place.title()}.") | true |
17537c25a434845c6e187f034b266b03648dacc4 | Trice254/alx-higher_level_programming | /0x06-python-classes/5-square.py | 1,413 | 4.53125 | 5 | #!/usr/bin/python3
"""
Module 5-square
Defines class Square with private size and public area
Can access and update size
Can print to stdout the square using #'s
"""
class Square:
"""
class Square definition
Args:
size (int): size of a side in square
Functions:
__init__(self, size)
size(self)
size(self, value)
area(self)
print(self)
"""
def __init__(self, size=0):
"""
Initializes square
Attributes:
size (int): defaults to 0 if none; don't use __size to call setter
"""
self.size = size
@property
def size(self):
""""
Getter
Return: size
"""
return self.__size
@size.setter
def size(self, value):
"""
Setter
Args:
value: sets size to value if int and >= 0
"""
if type(value) is not int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
def area(self):
"""
Calculates area of square
Returns:
area
"""
return (self.__size)**2
def my_print(self):
"""
Prints square with #'s
"""
print("\n".join(["#" * self.__size for rows in range(self.__size)]))
| true |
429d7655eb45e48f079bdbda71dc8226a0dba108 | Trice254/alx-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 555 | 4.21875 | 4 | #!/usr/bin/python3
"""
Text Indention module
"""
def text_indentation(text):
"""
print text
2 new lines after each of these characters: ., ? and :
Args:
text (str): text
Raise
TypeError: when text is not str
"""
if type(text) is not str:
raise TypeError("text must be a string")
a = 0
while a < len(text):
if text[a] in [':', '.', '?']:
print(text[a])
print()
a += 1
else:
print(text[a], end='')
a += 1
| true |
495df61d0c1e33a0a9f167d501c471fdad9e8a83 | Trice254/alx-higher_level_programming | /0x06-python-classes/4-square.py | 1,192 | 4.625 | 5 | #!/usr/bin/python3
"""
Module 4-square
Defines class Square with private size and public area
Can access and update size
"""
class Square:
"""
class Square definition
Args:
size (int): size of a side in square
Functions:
__init__(self, size)
size(self)
size(self, value)
area(self)
"""
def __init__(self, size=0):
"""
Initializes square
Attributes:
size (int): defaults to 0 if none; don't use __size to call setter
"""
self.size = size
@property
def size(self):
""""
Getter
Return: size
"""
return self.__size
@size.setter
def size(self, value):
"""
Setter
Args:
value: sets size to value, if int and >= 0
"""
if type(value) is not int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
def area(self):
"""
Calculates area of square
Returns:
area
"""
return (self.__size)**2
| true |
12852a2bc16c9fc29f21c49f2fee14258cd2dcc2 | Trice254/alx-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 654 | 4.5 | 4 | #!/usr/bin/python3
"""
Square Printer Module
"""
def print_square(size):
"""
Print square using #
Args:
size (int) : Size of Square
Raise
TypeError: if size is not int
ValueError: if size is less than 0
TypeError: if size is float and less than 0
Return:
Printed Square
"""
if type(size) is float and size < 0:
raise TypeError("size must be an integer")
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
for x in range(size):
print("#" * size)
| true |
9ec77aa854fa81a09b3007e3c8662f8c22c72cbe | ajjaysingh/Projects | /mybin/pre_versions/addword_v1.0.py | 2,663 | 4.46875 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.4/bin/python3
# File Name : addword.py
# Description : It adds the provided word to my custom dictionary. The new words that I learn.
# Author : Ajay
# Date : 2016-05-03
# Python Version : 3
#==================================================
import os
import sys
def instructions():
print("\n\t***Please Follow the prompts, If you want to enter multiple meanings seperate them using simicolon(;).")
print("\n\t***You can add any additional information you want to add ")
# move to directory containg the dictionary
# IMPORTANT - while handling files always do this => first make a temp copy of file then proceed if try fails the you should restore the file
os.chdir("/Users/chaser/Projects/")
# print(os.system("ls"))
try:
temp_name = ".myDict_temp" #name of the temporary duplicate file
os.system("cp "+ "myDict "+ temp_name)
print(instructions())
# print("copied")
# os.system("ls " + "-la")
with open("myDict", 'a') as dictionary: #always use this because if opening of file fails the file will not get overwritten
new_word = str(sys.argv[1])
meaning = input("\nEnter the meaning for the word " + new_word + ": ") #raw_input renamed to input, take input the m
example = input("\nEnter some example for the word: ")
count = 0 # count the total no of words already present
with open("myDict", 'r') as read_file: # open the file just for reading the number of words already present, we can not read a file in append mode
for line in read_file :
if line[0:3] == ">>>" : # [0:3] is like [)
count = count + 1 # the line is read as an array, [0:3] means 0,1,2 here 3 is not include
if (len(line) > 4) and new_word.upper() == line[3:-1]:
print("Word already present")
exit(1) # on exit 1 it will go to except
# print(count)
dictionary.write(">>>\n")
dictionary.write(str(count + 1) + ". " + new_word.upper() + "\n")
dictionary.write("Meaning: " + meaning + '\n')
dictionary.write("Example: " + example + '\n' + '\n')
# os.system("rm "+ temp_name) #we need to remove the temp file whether try suceeds or fails
except:
files = os.listdir()
if temp_name in files:
os.system("cp " + temp_name + " myDict")
print("try agian!")
finally: # always executed whether try suceeds or not
files = os.listdir()
if temp_name in files:
os.system("rm " + temp_name)
| true |
caec37b13d91ee25e2a4c8322d1d1f9035277521 | Morgenrode/MIT_OCW | /ex3.py | 213 | 4.125 | 4 | '''Given a string containing comma-separated decimal numbers,
print the sum of the numbers contained in the string.'''
s = input('Enter numbers, separated by commas: ')
print(sum(float(x) for x in s.split(',')))
| true |
fbbb1c4ec214fb01e299d4bbd3f44de9100966d6 | oswalgarima/leetcode-daily | /arrays/max_prod_two_elements.py | 1,334 | 4.21875 | 4 | """
1464. Maximum Product of Two Elements in an Array
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/
Given the array of integers nums,
you will choose two different indices i and j of that array.
Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0),
you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
"""
# Runtime: 44ms
class Solution:
def maxProduct(self, nums: List[int]) -> int:
# Thought proces:
# We need to take note of the index that generated that highest maximum product of two elements in an array
# max_prod = 0
# # Given that we must start from 0
# for i in range(0, len(nums) - 1):
# for j in range(i + 1, len(nums)):
# temp_prod = (nums[i] - 1) * (nums[j] - 1)
# if temp_prod > max_prod:
# max_prod = temp_prod
# else:
# continue
# Given a more efficient way – the last two number will of a sorted array will always give the bigger prod
nums.sort()
return (nums[-1] - 1) * (nums[-2] - 1)
| true |
f0d0be61871f9357033bc8148e11e83edcfc28d0 | oswalgarima/leetcode-daily | /arrays/max_prod_three_nums.py | 681 | 4.125 | 4 | """
628. Maximum Product of Three Numbers
https://leetcode.com/problems/maximum-product-of-three-numbers/
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example:
Input: nums = [1,2,3]
Output: 6
Input: nums = [1,2,3,4]
Output: 24
"""
# Runtime: 252ms (73.64%)
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
incld_neg = 1
excld_neg = 1
w_neg_val = nums[:2] + [nums[-1]]
pos_val = nums[-3:]
for i in w_neg_val:
incld_neg *= i
for j in pos_val:
excld_neg *= j
return max(incld_neg, excld_neg)
| true |
914f699c06f95507eba2da62deaa44aaf25519ef | limbryan/sudoku_solver | /solver.py | 2,292 | 4.1875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Takes in a position in the board and outputs if it is possible or not to put the number n inside
def possible(board,x,y,n):
# checks the row
for i in range(len(board[0])):
# exits the function straightaway if the number n already exists in the row
if board[x][i] == n:
return False
# checks the column
for j in range(len(board[0])):
if board[j][y] == n:
return False
# first determine which of the 9 major boxes the x-y position is in
# it doest not matter where in box it is, becasue we haev to check the whole box
# so we just have to determine which of the box it is in
x_b = (x//3)*3
y_b = (y//3)*3
# check the same box
for ib in range(3):
for jb in range(3):
# checking the entire box the x-y is in
if board[x_b+ib][y_b+jb] == n:
return False
# if it passes all the rules return True
return True
def solve(board):
for x in range(9):
for y in range(9):
if board[x][y] == 0:
for n in range(1,10):
res = possible(board,x,y,n)
if res ==True:
board[x][y] = n
# further solve again - recursion
# the recursion just means going deepre into a tree/node
solve(board)
# this leaves the option that going deeper into the tree did not work so it remains empty as the previous branch was a wrong move
board[x][y] = 0 #NEEDED
return board
print("Solved")
print(np.matrix(board))
#input("More")
#initalise the sudoku board as a list
board = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
print(board)
#just for viewing purposes - we are doing this sovler with lists only though we can do it with numpy arrays as well
board_np = np.matrix(board)
print(board_np)
# this is the main function
solve(board)
| true |
e2c613f1f0b1a69a554fb52d7f63b7a36a395439 | DavidErroll/Euler-Problems | /Problem_14.py | 1,570 | 4.1875 | 4 | # The following iterative sequence is defined for the set of positive integers:
# n → n/2 (n is even)
# n → 3n + 1 (n is odd)
# Using the rule above and starting with 13, we generate the following sequence:
# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
# It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
# Which starting number, under one million, produces the longest chain?
# NOTE: Once the chain starts the terms are allowed to go above one million.
def collatz_chain_length(start_point):
if start_point < 2:
x = 2
else:
x = start_point
chain_length = 1
limit = 0
while x != 1 and limit < 1000000:
if x % 2:
x = 3 * x + 1
chain_length += 1
limit += 1
else:
x = x / 2
chain_length += 1
limit += 1
return(chain_length)
def max_length(max_value):
current_max_length = 1
max_iteration = 1
for i in range(max_value + 1):
test_iteration_length = collatz_chain_length(i)
if test_iteration_length >= current_max_length:
max_iteration = i
current_max_length = test_iteration_length
else:
pass
return(max_iteration, current_max_length)
def interface():
max_val = int(input("Maximum Collatz chain value = "))
print(max_length(max_val))
def main():
interface()
main()
| true |
de6fa700d107e662dc8fcf8b99e11cd94df60e80 | CODEVELOPER1/PYTHON-FOLDER | /SECRECT_WORD_GAME.py | 566 | 4.28125 | 4 | #Secert Word Game with loops
secert_word = "giraffe" #secert word
guess = "" #stores user response
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secert_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter Secert Word Guess. You Only have 3 tries, Choose Wisely: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print('Nice Try, but you didn\'t succeed, you ran out of guesses. Thanks for Playing! Good-Bye')
else:
print("You got the Secert Word")
| true |
4ed6dd63fd3eccf0ffebcc101885dce17354a61c | mmrubayet/python_scripts | /codecademy_problems/Wilderness_Escape.py | 2,805 | 4.3125 | 4 | print("Once upon a time . . .")
######
# TREENODE CLASS
######
class TreeNode:
def __init__(self, story_piece):
self.story_piece = story_piece
self.choices = []
def add_child(self, node):
self.choices.append(node)
def traverse(self):
story_node = self # assign story_node to self
print(story_node.story_piece) # print out story_node's story_piece
while story_node.choices != []: # while story_node has choices:
choice = int(input("Enter 1 or 2 to continue the story: ")) # get the user's choice using input()
if not choice in [1, 2]: # if the choice is invalid
print("Invalid Choice! Please enter 1 or 2: ") # tell the user
else: # if the choice is valid
chosen_index = choice - 1
chosen_child = story_node.choices[chosen_index]
print(chosen_child.story_piece)
story_node = chosen_child # set choice as the new story_node
######
# VARIABLES FOR TREE
######
story = \
"""
You are in a forest clearing.
There is a path to the left.
A bear emerges from the trees and roars!
Do you:
1 ) Roar back!
2 ) Run to the left...
"""
story_root = TreeNode(story)
story_a = \
"""
The bear is startled and runs away.
Do you:
1 ) Shout 'Sorry bear!'
2 ) Yell 'Hooray!'
"""
choice_a = TreeNode(story_a)
story_b = \
"""
You come across a clearing full of flowers.
The bear follows you and asks 'what gives?'
Do you:
1 ) Gasp 'A talking bear!'
2 ) Explain that the bear scared you.
"""
choice_b = TreeNode(story_b)
story_a_1 = \
"""
The bear returns and tells you
it's been a rough week.
After making peace with a talking bear,
he shows you the way out of the forest.
YOU HAVE ESCAPED THE WILDERNESS.
"""
choice_a_1 = TreeNode(story_a_1)
story_a_2 = \
"""
The bear returns and tells you that
bullying is not okay before leaving you alone
in the wilderness.
YOU REMAIN LOST.
"""
choice_a_2 = TreeNode(story_a_2)
story_b_1 = \
"""
The bear is unamused. After smelling the flowers,
it turns around and leaves you alone.
YOU REMAIN LOST.
"""
choice_b_1 = TreeNode(story_b_1)
story_b_2 = \
"""
The bear understands and apologizes
for startling you.
Your new friend shows you a
path leading out of the forest.
YOU HAVE ESCAPED THE WILDERNESS.
"""
choice_b_2 = TreeNode(story_b_2)
story_root.add_child(choice_a)
story_root.add_child(choice_b)
choice_a.add_child(choice_a_1)
choice_a.add_child(choice_a_2)
choice_b.add_child(choice_b_1)
choice_b.add_child(choice_b_2)
user_choice = input("What is your name? \n_> ")
print(f"\nWelcome {user_choice}!")
######
# TESTING AREA
######
story_root.traverse()
| true |
9417c401c7b1c7d47b79b381d0aaf82162266b18 | mmrubayet/python_scripts | /codecademy_problems/Sorting Algorithms with python/bubble_sort.py | 310 | 4.15625 | 4 | from swap import *
def bubble_sort(arr):
for el in arr:
for index in range(len(arr)-1):
if arr[index] > arr[index + 1]:
swap(arr, index, index + 1)
##### test statements
nums = [5, 2, 9, 1, 5, 6]
print("Pre-Sort: {0}".format(nums))
bubble_sort(nums)
print("Post-Sort: {0}".format(nums))
| true |
45905e00ddeb09731899b3fb4482103e66e695d4 | blakeskrable/First-Project | /First.Project.py | 248 | 4.21875 | 4 | number=int(input("Guess a number between 1-10: "))
while number != 10:
print("Wrong! Guess Again!")
number=int(input("Enter a new number: "))
if number == 10:
print("Congratulations! Good Guess! You Have Completed The Program!")
| true |
0102e2f8ebaab1d92f6a5fa7c2ffc2d134fd96f1 | ashilp/Pleth_Test | /pleth_2.py | 1,082 | 4.125 | 4 | import os
def read_path(path):
'''
Function to list out directories, subdirectories, files with proper indentation
'''
#indent according to the level of the directory
level = path.count("\\")
print("\n************Output************\n")
if not os.path.exists(path):
print("Error: Path does not exist")
return
for root, dirs, files in os.walk(path):
#for indentation of directory, sub-directory, files
space = " "*(root.count("\\")-level)
if (os.path.isdir(root)):
print(space+"/"+os.path.basename(root))
for f in files:
print (space+" "+f)
print("\n******************************\n")
if __name__=="__main__":
path = input("\nEnter full path of the directory: ")
read_path(path)
'''
Test Cases Verified:
- Tested invalid or non existent paths
- Tested for valid paths with recursive sub directories and files
- Tests for empty directory
- Tested for directory names containing spaces
- Tested for soft-links or shortcuts
''' | true |
75cb6dc8589bfb41f161f89bbd4d3849d2ecdc3d | jcohenp/DI_Exercises | /W4/D2/normal/ex_6.py | 1,739 | 4.5625 | 5 |
# A movie theater charges different ticket prices depending on a person’s age.
# if a person is under the age of 3, the ticket is free
# if they are between 3 and 12, the ticket is $10
# and if they are over age 12, the ticket is $15 .
# Apply it to a family, ask every member of the family their age, and at the end of the loop, tell them the cost of the tickets for the whole family.
#
#get number of group members:
size_group = int(input("How many tickets would you like to purchase\n"))
group_member_age = []
# group_member_age_input = ""
total_cost = 0
while size_group > 0:
if size_group == None:
continue
else:
group_member_age_input = int(input("What is your age?\n"))
if group_member_age_input == "":
error = -1
error_msg = "no input"
print(f"Error {error}, {error_msg}\n")
continue
else:
group_member_age.append(group_member_age_input)
size_group -=1
if group_member_age_input >= 3 and group_member_age_input <= 12:
total_cost += 10
elif group_member_age_input > 12:
total_cost += 15
print (f"Total cost: {total_cost}\n\n")
# A group of teenagers is coming to your movie theater and want to see a movie that is restricted for people between 16 and 21 years old.
# Write a program that ask every user their age, and then tell them which one can see the movie.
# Tip: Try to add the allowed ones to a list.
for group_member in group_member_age:
if group_member > 21:
print(f"{group_member},years old you can watch the movie")
else:
print(f"{group_member},years old sorry kid - too young!") | true |
69a0eadad9f12debc8722949571a4ec9adca922f | jcohenp/DI_Exercises | /W4/D2/normal/ex_3 2.py | 695 | 4.40625 | 4 |
# Recap – What is a float? What is the difference between an integer and a float?
# Earlier, we tried to create a sequence of floats. Did it work?
# Can you think of another way of generating a sequence of floats?
# Create a list containing the sequence 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 without hard-coding the sequence.
# An integer is a natural number, a float is a decimal
# yes you can create a sequence of floats in a list for example
list_of_floats = [1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
print(list_of_floats)
# Create a list containing the sequence 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 without hard-coding the sequence.
set_of_floats = {1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5}
print(set_of_floats)
| true |
4d7f787e45e409ae15a01e88740f8acba4d43c45 | jcohenp/DI_Exercises | /W4/D1/ninja/ex_1/ex_2.py | 205 | 4.25 | 4 | # Given two variables a and b that you need to define, make a program that print Hello World only if a is greater than b.
a = 4
b = 6
if a > b:
print("Hello World")
else:
print("a is too small") | true |
a44bfcc01ea351adf209f4642c6dd8510410f435 | ramyasinduri5110/Python | /strings.py | 942 | 4.34375 | 4 | #Strings in python
#how we can write strings in python
str1_singlequote='Hello World!'
str2_doublequotes="The string declaration in double quotes"
str_block=''' this is the biggest block of code with
multiple lines of text
'''
#type gives you the information about the data type
print(type(" Hey! there I am using python :D"))
print('The string written with single quotes : '+str1_singlequote)
print('The string written with double quotes : '+str2_doublequotes)
print('The string block : '+str_block)
#string concatenation
#string concatenation only works with strings
first_name='ramya'
last_name='kondepudy'
full_name=first_name+''+last_name
print('full name after concatenation: '+full_name)
#Type Conversion
print('converting an integer value to a string ')
print(type(str(100)))
b=str(100)
c=int(b)
d=type(c)
print(d)
#Escape Sequences
#t adds the tab
#n adds the new line
weather="it's \"kind of\" sunny"
print(weather)
| true |
562b8a5b2b3d0b2dfedc2ba890c3adbd22a57bf1 | neelpopat242/audio_and_image_compression | /app/utils/images/linalg/utils.py | 2,937 | 4.375 | 4 | import math
def print_matrix(matrix):
"""
Function to print a matrix
"""
for row in matrix:
for col in row:
print("%.3f" % col, end=" ")
print()
def rows(matrix):
"""
Returns the no. of rows of a matrix
"""
if type(matrix) != list:
return 1
return len(matrix)
def cols(matrix):
"""
Returns the no. of columns of a matrix
"""
if type(matrix[0]) != list:
return 1
return len(matrix[0])
def eye(size):
"""
Returns an identity matrix
"""
mat = list()
for r in range(size):
row = list()
for c in range(size):
if r == c:
row.append(1)
else:
row.append(0)
mat.append(row)
return mat
def pivot_index(row):
"""
Returns the index of pivot in a row
"""
counter = 0
for element in row:
if element != float(0):
return counter
counter += 1
return counter
def pivot_value(row):
"""
Returns the value of pivot in a row
"""
for element in row:
if element > math.exp(-8):
return element
return 0
def swap(matrix, index_1, index_2):
"""
Function to swap two rows
"""
x = matrix[index_1]
matrix[index_1] = matrix[index_2]
matrix[index_2] = x
def transpose(matrix):
"""
Returns the transpose of a matrix
"""
transpose_matrix = list()
for i in range(cols(matrix)):
row = list()
for j in range(rows(matrix)):
row.append(matrix[j][i])
transpose_matrix.append(row)
return transpose_matrix
def mat_multiply(a, b):
"""
Function to multiply two matrices
"""
c = [[0 for i in range(cols(b))] for j in range(rows(a))]
for i in range(rows(a)):
for j in range(cols(b)):
for k in range(rows(b)):
c[i][j] += a[i][k] * b[k][j]
return c
def mat_splice(matrix, r, c):
"""
Function which returns a matrix with the first r rows and first c
columns of the original matrix
"""
result = list()
for i in range(r):
row = matrix[i]
result.append(row[:c])
return result
def to_int(matrix):
"""
Funciton to convert the eact element of the matrix to int
"""
for row in range(rows(matrix)):
for col in range(cols(matrix)):
for j in range(3):
matrix[row][col][j] = int(matrix[row][col][j])
return matrix
def clip(matrix):
"""
Function to clip each element to the range float[0, 1]
"""
for row in range(rows(matrix)):
for col in range(cols(matrix)):
for j in range(3):
if matrix[row][col][j] > 1:
matrix[row][col][j] = 1
if matrix[row][col][j] < 0:
matrix[row][col][j] = 0
return matrix
| true |
b6667c81ac17100692ae20ee76abe20ac9bc9d29 | NaveenLDeevi/Coursera-Python-Data-Structures | /Week#3_ProgrammingAssg_part#1.py | 463 | 4.71875 | 5 | # Coursera- Data structures course - Week#3.
#7.1 Write a program that prompts for a file name, then opens that file and reads
#through the file, and print the contents of the file in upper case. Use the file
#words.txt to produce the output below.You can download the sample data at
#http://www.pythonlearn.com/code/words.txt
#!/usr/bin/env python
input = raw_input('Enter the file name:')
int = open(input,'r')
for line in int:
print (line.upper()).strip() | true |
d4eb39c121483d83e135c3469c31c57ce457a239 | tanmay2298/The-Python-Mega-Course-Udemy | /Tkinter GUI/script1.py | 746 | 4.4375 | 4 | from tkinter import * # Imports everything fromt the tkinter library
# Tkinter program is mainly made of two things -- Window and Widgets
window = Tk() # Creates an empty window
def km_to_miles():
print(e1_value.get())
miles = float(e1_value.get())*1.6
t1.insert(END, miles)
b1 = Button(window, text = "Execute", command = km_to_miles) # NOT km_to_miles()
b1.grid(row = 0, column = 0)
e1_value = StringVar()
e1 = Entry(window, textvariable = e1_value)
e1.grid(row = 0, column = 1)
t1 = Text(window, height = 1, width = 20)
t1.grid(row = 0, column = 2)
window.mainloop() # Everything between the window = tk() line and this goes in the main window
# Also this line allows us to use the 'cross' or 'X' button to close the window
| true |
4b62175aefa73723e3b4a17ec1783c938df829fd | mishuvalova/Paradigm-homework | /string_task.py | 1,450 | 4.375 | 4 | # Given a string, if its length is at least 3,
# add 'ing' to its end.
# Unless it already ends in 'ing', in which case
# add 'ly' instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.
#
# Example input: 'read'
# Example output: 'reading'
def verbing(s):
length = len(s)
if length >= 3:
if s[-3:] == 'ing':
return s +'ly'
else:
return s + 'ing'
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
#
# Example input: 'This dinner is not that bad!'
# Example output: 'This dinner is good!'
def not_bad(s):
nn = s.find('not')
nb = s.find('bad')
if nn != -1 and nb != -1 and nb > nn:
s = s[:nn] + 'good' + s[nb +3:]
return s
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
#
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
#
# Example input: 'abcd', 'xy'
# Example output: 'abxcdy'
def front_back(a, b):
l1 = len(a)
l2 = len(b)
i1 = l1//2 - l1%2
i2 = l2//2 - l2%2
a1 = a[0:i1]
a2 = a[i1:]
b1 = b[0:i2]
b2 = b[i2:]
return a1 + b1 + a2 + b2
| true |
df9a29f6a9e12dffe386f1bd306fd0a23aad1e56 | elentz/1st-Semester-AP | /dictproblems1.py | 1,074 | 4.5625 | 5 | 1. Write a Python script to add key to a dictionary.
Sample Dictionary : {0: 10, 1: 20} Expected Result : {0: 10, 1: 20, 2: 30}
2. Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
3. Write a Python script to check if a given key already exists in a dictionary.
4. Write a Python program to iterate over dictionaries using for loops.
5. Write a Python script to sort (ascending and descending) a dictionary by value.
6. Write a Python script to generate and print a dictionary that contains number (between 1 and n) in the form (x, x*x). Sample Dictionary ( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
7. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. Sample Dictionary {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
| true |
305e920c490417d773339b1f73aae7f640d31d07 | SiegfredLorelle/pld-assignment2 | /Assignment2_Program1.py | 402 | 4.46875 | 4 | """Create a program that will ask for name, age and address.
Display those details in the following format.
Hi, my name is _____. I am ____ years old and I live in _____ .
"""
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
address = input("Please enter you address: ")
print (f"Hi, my name is {name}. I am {age} years old and I live in {address}. ")
| true |
cd773903e3d604d872f5b50d0bbbbe0c6e273a43 | MuddCreates/FlexTracker | /flexBackend.py | 488 | 4.125 | 4 | import math
def getPriceD(fileName):
"""
The function reads a text file of the price and name of each possible thing to buy.
It stores each thing as in a dictionary win form
{price:name of thing}
It then returns the dictionary
"""
priceD = {}
file = open(fileName,"r")
for line in file:
data = line.split()
priceD[float(data[0])] = data[1]
return priceD
def sortPrices(priceD):
'''
This function
'''
| true |
e7f3cb0d77610d3e477e83080408db869b6769e6 | jannekai/project-euler | /037.py | 1,750 | 4.125 | 4 | import time
import math
start = time.time()
def primes():
primes = []
n = 2
yield n
n = 3
while True:
# Return the found prime and append it to the primes list
primes.append(n)
yield n
# Find the next natural number which is not divisible by any of
# the previously found prime.
while True:
# The next number after prime is always even, so we can
# optimize by not checking the even values.
n += 2
h = int(math.sqrt(n)) + 1
isPrime = True
for i in primes:
if n % i == 0:
isPrime = False
break
if i > h:
break
# If the value was not divisible by any of the previously
# found primes, break the inner loop
if isPrime:
break
def isTruncatable(x):
global p
t = [x]
c = 0
n = x / 10
while n > 0:
if n not in p:
return False
t.append(n)
n = n / 10
c += 1
c = 10**c
n = x - (x/c*c)
while c > 1:
if n not in p:
return False
t.append(n)
c = c / 10
n = n - (n/c*c)
print t
return True
gen = primes()
s = 0
c = 0
p = set()
while c < 11:
x = gen.next()
p.add(x)
if x > 7 and isTruncatable(x):
print "Found %d" % x
c += 1
s += x
print "Sum is %d, total of %d primes were calculated" % (s, len(p))
end = time.time() - start
print "Total time was " + str(end)+ " seconds"
| true |
9218ed1c4e3314d3838e36f5516e5880d3e81b5b | vernikagupta/Opencv-code | /Rotation.py | 1,023 | 4.28125 | 4 | '''Rotation of an image means rotating through an angle and we normally rotate the
image by keeping the center. so, first we will calculate center of an image
and then we will rotate through given angle. We can rotate by taking any point on
image, more preferably center'''
from __future__ import print_function
import cv2
import argparse
def show_img(img):
cv2.imshow("canvas",img)
cv2.waitKey(0)
return
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "path to image")
args = vars(ap.parse_args())
print(args)
load_image = cv2.imread(args["image"])
#show_img(load_image)
h,w = load_image.shape[:2]
print(h,w)
Center = (h//2,w//2)
print(Center)
M = cv2.getRotationMatrix2D(Center, 45, 1.0)
rotated = cv2.warpAffine(load_image, M, (w,h))
show_img(rotated)
'''45 degree is the angle we are rotating the image and 1.0 is the scale
1.0 means same size of original. 2.0 means double the size, 0.5 means half the soze
of image''' | true |
ec98c1efd4562a910b4b98129e5cf9aad5b8d7d6 | ksharma377/machine-learning | /univariate-linear-regression/src/main.py | 1,714 | 4.15625 | 4 | """
This is the main file which builds the univariate linear
regression model.
Data filename: "data.csv"
Data path: "../data/"
The model trains on the above data and outputs the parameters and the accuracy.
The number of training cycles is controlled by the variable "epochs".
Input: x
Parameters: w0, w1
Output: y
Heuristic: h(x) = w0 + (w1 * x)
Number of training examples: m
Batch size: b
Learning rate: r
Cost function = MSE (Mean squared error)
C(w0, w1) = (1 / 2m) sigma((h(x) - y)^2)
Optimizer algorithm: Batch Gradient Descent
"""
import random
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
"""
Initializes the parameters
"""
def initialize_parameters():
global w0, w1, r, epochs
w0 = random.random()
w1 = random.random()
r = 0.1
epochs = 100
"""
Reads the data in csv format and splits into training and testing data (80-20)
"""
def read_data():
df = pd.read_csv('../data/data.csv')
global train_data, test_data
train_data, test_data = train_test_split(df, test_size = 0.2)
def calculate_mse(batch):
m = len(batch)
error = 0
for row in batch.itertuples():
x, y = row.x, row.y
h = w0 + (w1 * x)
error += (h - y) ** 2
return error / (2 * m)
"""
Trains the linear regression model.
1. Sample a batch of fixed size.
2. Calculate the error for this batch.
3. Update the parameters using Gradient Descent.
4. Repeat for epochs.
"""
def train_model():
batch_size = 1000
for epoch in range(epochs):
batch = train_data.sample(n = batch_size)
error = calculate_mse(batch)
print("Epoch: {}, Error: {}".format(epoch, error))
if __name__ == "__main__":
read_data()
initialize_parameters()
train_model()
| true |
e293adefe3f2b90d6e447422070832b53d34685d | nishapagare97/pythone-ideal-programs | /temperature program.py | 653 | 4.28125 | 4 | # question no 2
# author - nisha pagare
#date - 10-0-2021
# program should convert the temperature to the other unit. The conversions are
# f= (9/5c+32)
# c= (5/9f-32)
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("Input proper convention.")
quit()
print("The temperature in", o_convention, "is", result, "degrees.")
| true |
19da3645aa84ba2c7cd66dda81d5dad120253115 | stanmark2088/allmypythonfiles | /fahrenheit_to_c.py | 954 | 4.59375 | 5 | # Write a Python program to convert a temperature given in degrees Fahrenheit
# to its equivalent in degrees Celsius. You can assume that T_c = (5/9) x (T_f - 32),
# where T_c is the temperature in °C and T_f is the temperature in °F. Your program
# should ask the user for an input value, and print the output. The input and output
# values should be floating-point numbers.
# my version
print("\nWelcome to the fahrenheit to celsius calculator!\n")
name = input("Please tell us your name: ")
print("\nHello " + str(name) + "!")
fahrenheit_temperature = float(
input("\nPlease enter Fahrenheit temperature: "))
print("\nThe temperature in Celsius is:")
celsius_temperature = (5 / 9) * (fahrenheit_temperature - 32)
print(celsius_temperature)
print(("\nThank you for using our calculator ") + str(name) + "!")
# their version
T_f = float(input("Please enter a temperature in °F: "))
T_c = (5/9) * (T_f - 32)
print("%g°F = %g°C" % (T_f, T_c))
| true |
932d7741c60da5351cdb12f7ac0ce554232d9490 | CptnReef/Frequency-Counting-with-a-Hash-Table | /HashTable.py | 2,690 | 4.375 | 4 | from LinkedList import LinkedList
class HashTable:
def __init__(self, size):
self.size = size
self.arr = self.create_arr(size)
# 1️⃣ TODO: Complete the create_arr method.
# Each element of the hash table (arr) is a linked list.
# This method creates an array (list) of a given size and populates each of its elements with a LinkedList object.
def create_arr(self, size):
# creates array for linked list
arr = []
# I need every linked list to append to the array
for i in range(size):
#creating new linked list
new_link = LinkedList()
#adding it to the array
arr.append(new_link)
return arr
# 2️⃣ TODO: Create your own hash function.
# Hash functions are a function that turns each of these keys into an index value that we can use to decide where in our list each key:value pair should be stored.
def hash_func(self, key):
# 1. Get the first letter of the key and lower case it
first_letter = key[0].lower() #"[a]pple"
# 2. Calculate the distance from letter a
distance_from_a = ord(first_letter) - ord('a')
# 3. Mod it to make sure it is in range
index = distance_from_a % self.size
# returns index
return index
# 3️⃣ TODO: Complete the insert method.
# Should insert a key value pair into the hash table, where the key is the word and the value is a counter for the number of times the word appeared. When inserting a new word in the hash table, be sure to check if there is a Node with the same key in the table already.
def insert(self, key, value):
# Check link_list is empty or not.
index = self.hash_func(key)
self.linked_ls = self.arr[index]
current = self.linked_ls.head
# Going through the Hash Table for an empty node to assign key/value
while current != None:
# add if current node and key is True
if current.data[0] == key:
current.data[1] += value
return
# goes to the next node
current = current.next
# After Checking through Hash Table and linked list is empty
self.linked_ls.append([key, value])
# 4️⃣ TODO: Complete the print_key_values method.
# Traverse through the every Linked List in the table and print the key value pairs.
# For example:
# a: 1
# again: 1
# and: 1
# blooms: 1
# erase: 2
def print_key_values(self):
#Check all linked lists in the hashtable
for self.linked_ls in self.arr:
current = self.linked_ls.head
while current != None:
if current.data:
print(f'({current.data[0]}: {current.data[1]}')
current = current.next
| true |
97c0335ee71a8d46a3dbbb5ddbd2e3b36bbada6b | colingillette/number-string-puzzles | /interface.py | 2,960 | 4.15625 | 4 | # List Reader
# Input: List
# Output: none, but will print list to console one line at a time
def list_reader(x):
for i in range(len(x)):
print(x[i])
# Fibonacci Sequence
# Input: Number in return series
# Output: List in series
def fib(x):
if x < 1:
return False
elif x == 1:
return [0]
elif x == 2:
return [0, 1]
seq = [0, 1]
for i in range(2, x):
seq.append(seq[i-1] + seq[i-2])
return seq
# FizzBuzz
# Input: Number to generate fizzbuzz to
# Output: None. Prints to console directly
def fizz_buzz(x):
fb = lambda n, m : n % m
for i in range(x + 1):
if fb(i, 15) == 0:
print("FizzBuzz")
elif fb(i, 5) == 0:
print("Buzz")
elif fb(i, 3) == 0:
print("Fizz")
else:
print(i)
# Palendrome
# Input: A single word as string
# Output: Boolean representing whether or not the word is a palendrome
def palendrome(word):
reverse = word[::-1]
if reverse == word:
return True
else:
return False
# Word Count
# Input: a string
# Output: Number of words in string
def word_count(text):
count = 1
for c in text:
if c == ' ':
count += 1
return count
# INPUT FUNCTIONS
# Get Help
# Lists all commands that are available for the user
def get_help():
commands = {
'fizzbuzz' : 'Initiate the fizz buzz module',
'fizz' : 'Initiate the fizz buzz module. Alias for fizzbuzz',
'help' : 'Print off a list of commands',
'h' : 'Print off a list of commands. Alias for help',
'quit' : 'Terminates the program',
'q' : 'Terminates the program. Alias for quit',
'fibonacci' : 'Initate the fibonacci sequence module',
'fib' : 'Initate the fibonacci sequence module. Alias for fibonacci'
}
print()
for key in commands:
print(key + ': ' + commands[key])
print()
# Process Input
# Input: string from user
# Output: Boolean. Will always be true unless user types 'quit' or 'q'
def process_input(text):
status = True
text = text.lower()
if text == 'quit' or text == 'q':
print('Exiting program...')
status = False
elif text =='fizz' or text == 'fizzbuzz':
fizz_buzz(int(input('Enter the number you would like to go to: ')))
elif text == 'help':
get_help()
elif text == 'fib' or text == 'fibonacci':
list_reader(fib(int(input('How many numbers would you like to generate: '))))
else:
print('Please input a valid command. Type \"help\" if you need a list of commands.')
return status
# Computer
# A function that handles input from the user
def computer():
print()
print("For a list of commands, please type \"help\"")
print()
live = True
while (live):
task = str(input('Please enter a command: '))
live = process_input(task)
# MAIN BODY
computer() | true |
e29ef9d89303a36e43c0853591d8e596a1321984 | rcadia/notesPython | /More Fuctions.py | 457 | 4.21875 | 4 | #
# Tutorial - 15
# More Functions
#
# Ross Alejandro A. Bendal
# Tuesday June 18 2013 - 5:18PM
#
#
say = ['hey','now','brown']
print say.index('brown') # Search for index that will match in the text parameter
say.insert(2,'show') # Inserts a new value. (Index.'string')
print say
say.pop(2) # Removes a value in index. Returns the value
print say
say.remove('brown') # Removes the string on an index completely.
print say
say.reverse() # Reverse the indexes.
print say
| true |
ab4b30dcc2f00fdd64e320336bf731680fc8a646 | Kenn3Th/DATA3750 | /Kinematics/test.py | 1,251 | 4.25 | 4 | """
Handles user input from the terminal and test if
it can connect with the Kinematics_class.py
Also tests for forward and inverse kinematics
"""
import numpy as np
import Kinematics_class as Kc
inner_length = float(input("Length of the inner arm?\n"))
outer_length = float(input("Length of the outer arm?\n"))
answer = input("Inverse og Forward?\n")
robotic_arm = Kc.Kinematics(inner_length,outer_length)
if answer.lower()== "inverse":
print("Need two coordinates for where to go\nand I will provide the angles for the arm")
x = float(input("What is the X coordinate?\n"))
y = float(input("What is the Y coordinate?\n"))
[q1,q2] = robotic_arm.inverse(x,y)
print(f"The first angle is {q1:.2f} degrees and \nthe second angel is {q2:.2f} degrees")
elif answer.lower() == "forward":
print("Need two angles for how the arm should strech and I'll give you the X and Y coordinates")
first_angle = float(input("What is the fisrt angle?\n"))
second_angle = float(input("What is the second angle?\n"))
[x,y] = robotic_arm.forward(first_angle,second_angle)
print(f"The x, y coordinate is = [{x:.2f},{y:.2f}]")
else:
print("Error!")
print("I asked for forward or inverse kinematics")
print("Godbye!")
| true |
2a1d0766db2123cb8120b5eb9ce958c168340edc | frizzby/coyote-leg | /week2/ex4_done.py | 1,470 | 4.25 | 4 | # 4. Implement a class User with attributes name, age. The instances of this class should be sortable by age by default. So sorted([User(name='Eric', age=34), User(name='Alice', age=22)]) will return a list of sorted users by their age (ASC). How would you sort those objects by name? Don't forget to Implement __str__ method to help testing and visualize the object.
# Hint for the default sorting: __cmp__, functools.total_ordering.
#
from functools import total_ordering
@total_ordering
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return "%s %s" % (self.name, self.age)
def __eq__(self, other):
return (self.name, self.age) == (other.name, other.age)
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
return self.age < other.age
@staticmethod
def cmp(x, y):
return (x > y) - (x < y)
def __cmp__(self, other):
return User.cmp(self.age, other.age)
def main():
users = [User("mikhail", 57), User("marina", 55), User("alexandra", 19), User("mikhail", 31)]
print(users)
sorted_users_by_age = sorted(users)
print(sorted_users_by_age)
#additional sorting by age
sorted_users_by_name = sorted(sorted_users_by_age, key=lambda u: u.name)
print(sorted_users_by_name)
print(User("mikhail", 57) == User("mikhail", 57))
if __name__ == '__main__':
main()
| true |
55bd778ebeb9465d1be9d73d3fe65b6250125ad9 | mm1618bu/Assignment1 | /HW1_2.6.py | 216 | 4.1875 | 4 | # Ask user for a number
enterNumber = input("Enter a number: ")
# set inital variable to zero
totalnum = 0
# for each integer, add 1
for integer in str(enterNumber):
totalnum += int(integer)
print(totalnum)
| true |
e1063970a9018300bc0d195b71ee5ae8e33b0fd5 | MiguelFirmino/Login-System | /Login System.py | 2,245 | 4.125 | 4 | data_text = []
first_names = []
last_names = []
emails = []
passwords = []
def user_choice():
print('Hello user, create an account or login to an existing one.')
choice = input('Insert "1" if you wish to create an account or "2" if you wish to login: ')
print('\r')
if choice == '1':
create_account()
user_choice()
else:
login_account()
user_choice()
def register_info():
with open('Login_Data.txt', 'r') as login_data:
global data_text, first_names, last_names, emails, passwords
data_text = login_data.readlines()
for i in data_text:
data_text[data_text.index(i)] = i.strip()
emails = (data_text[2::4])
def create_account():
with open('Login_Data.txt', 'a') as login_data:
first_name = input('First name: ')
last_name = input('Last name: ')
email = input('Insert your Email adress: ')
while email in emails:
print('That email is already registered')
email = input('Insert another Email adress: ')
password = input('Create a password: ')
passwordc = input('Confirm your password: ')
info = [first_name, last_name, email, password]
while passwordc != password:
print('The passwords do not match.')
passwordc = input('Reinsert your password: ')
for i in info:
login_data.write(i)
login_data.write('\n')
print('Nice! Your account was registered.')
print('\r')
register_info()
def login_account():
register_info()
with open('Login_Data.txt', 'r'):
login_email = input('Email: ')
while login_email not in emails:
print('Invalid Email')
login_email = input('Reinsert your Email: ')
login_password = input('Password: ')
while login_password != data_text[data_text.index(login_email) + 1]:
print('Invalid password')
login_password = input('Reinsert your password: ')
print('Hello {} {}, welcome back!'.format(data_text[data_text.index(login_email) - 2], data_text[data_text.index(login_email) - 1]))
print('\r')
user_choice() | true |
b26949e87237076f51997342f975fb3ba56ee4d6 | mfahn/Python | /primeFinder.py | 721 | 4.28125 | 4 | #get starting value
user_start = input("Enter a starting value ")
#get ending value
user_end = input("Enter an ending value ")
increment = user_start
count = 2
prime = 1
#find if each value in the range is prime or not
#increment is every number between the user_start and user_end
for increment in range(user_end):
#count is every number between 1 and increment
for count in range (increment):
#if increment is evenly divided by count, then it cannot be prime
#prime == 1 means the value is prime, prime == 0 means it is not prime
if(increment % count == 0):
prime = 0
if(prime == 1):
print(increment+" is prime")
else:
print(increment+" is not prime") | true |
4b7a16a68dcf73d62cda7e6e8b46b5c0516eef98 | amariwan/csv-to-db | /csv2sql.py | 1,558 | 4.28125 | 4 | # Import required modules
import csv
import sqlite3
# Connecting to the geeks database
connection = sqlite3.connect('user.db')
# Creating a cursor object to execute
# SQL queries on a database table
cursor = connection.cursor()
# Table Definition
create_table = '''CREATE TABLE IF NOT EXISTS user(
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT NOT NULL,
firstname TEXT NOT NULL,
lastname TEXT NOT NULL,
department TEXT NOT NULL,
location TEXT NOT NULL);
'''
# Creating the table into our
# database
cursor.execute(create_table)
# Opening the person-records.csv file
file = open('user.csv')
# Reading the contents of the
# person-records.csv file
contents = csv.reader(file, delimiter=',')
# for row in csv_reader_object:
# print(row)
# SQL query to insert data into the
# person table
insert_records = "INSERT INTO user (id, username, email, firstname, lastname, department, location) VALUES(?, ?, ?, ?, ?, ?, ?)"
# Importing the contents of the file
# into our person table
cursor.executemany(insert_records, contents)
# SQL query to retrieve all data from
# the person table To verify that the
# data of the csv file has been successfully
# inserted into the table
select_all = "SELECT * FROM user"
rows = cursor.execute(select_all).fetchall()
# Output to the console screen
for r in rows:
print(r)
# Commiting the changes
connection.commit()
# closing the database connection
| true |
dd0337366b869db97bb9dbedfcd41a2ecb606028 | SahilTara/ITI1120 | /LABS/lab8-students/NyBestSellers.py | 1,403 | 4.34375 | 4 | def create_books_2Dlist(file_name):
"""(str) -> list of list of str
Returns a 2D list containing books and their information from a file.
The list will contain the information in the format:
Publication date(YYYY-MM-DD), Title, Author, Publisher, Genre.
Preconditions: each line in the file specified contains information about
a book. In the format Title, Author, Publisher, Publication date(DD/MM/YY),
Genre.
"""
file = open(file_name).read().splitlines()
books = []
for book in file:
book = book.split("\t")
tmp = book[3]
tmp = tmp.split("/")
year = tmp[2]
tmp[2] = tmp[0].zfill(2)
tmp[0] = year
tmp = "-".join(tmp)
book.remove(book[3])
book.insert(0, tmp)
books.append(book)
return books
def search_by_year(books, year1, year2):
"""(list of list of str, int, int)
Prints a list of books in the list books published
between year1 and year2.
Precondition: books is a list created from create_books2Dlist
"""
print("All titles between", year1, "and", year2)
for book in range(len(books)):
this_book = books[book]
date = this_book[0]
year = int(date.split('-')[0])
title = this_book[1]
author = this_book[2]
if year1 <= year <= year2:
print(title,", by", author,"(" + date + ")")
| true |
33d62035bdab6e284039773e0707cc017ed3b12a | Dmitry-White/CodeWars | /Python/6kyu/even_odd.py | 251 | 4.1875 | 4 | """
Created on Wed Aug 23 2e:28:33 2017
@author: Dmitry White
"""
# TODO: Create a function that takes an integer as an argument and
# returns "Even" for even numbers or "Odd" for odd numbers.
def even_or_odd(n):
return "Even" if n%2 == 0 else "Odd" | true |
bcd5e6cb8f0a48c7f61a2d4ddfddba5bf5579a03 | Dmitry-White/CodeWars | /Python/6kyu/expanded_form.py | 551 | 4.125 | 4 | """
Created on Wed Aug 30 23:34:23 2017
@author: Dmitry White
"""
# TODO: You will be given a number and you will need to return it as a string in Expanded Form.
# For example:
# expanded_form(42), should return '40 + 2'
# expanded_form(70304), should return '70000 + 300 + 4'
def expanded_form(num):
l = len(str(num))
nulls = 10**(l-1)
if l == 1:
return str(num)
num_new = (num//nulls)*nulls
num_rest = num - num_new
if num_rest == 0:
return str(num_new)
return str(num_new) + ' + ' + expanded_form(num_rest) | true |
3ab257aa3e0c99c106f8ae516675cd74f5253c1b | MoAbd/codedoor3.0 | /templating_engine.py | 1,615 | 4.4375 | 4 | '''
It's required to make a templating engine that takes a template and substitute the variables in it. The variables are present in the templates in the form {{some_variable}}. The variables can be nested, so for {{some_{{second_variable}}}} second_variable will be evaluated first and then the other one will be evaluated.
Input Format
N(number of variables) M(Numbers of lines for a template)
variable 1 (in the form of `variable_name=value`)
variable 2 (in the form of `variable_name=value`)
...
variable N
Template consisting of M lines
Constraints
0 <= N, M < 1000
1 <= length of a line, variable definition < 1000
Output Format
the parsed template
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
n, m = raw_input().split()
n = int(n)
m = int(m)
temp = []
var = []
if n == 0:
print raw_input()
else:
for i in range(n):
var.append(raw_input())
var = dict(i.split('=') for i in var)
for i in range(m):
temp.append(raw_input())
x = temp[i]
counter = x.count('}}')
for i in range(counter):
end = x.find('}}')
begin = x.find('{{')
if end + 2 == len(x):
begin = x.rfind('{{')
x = x[:begin] + var[x[begin+2 : end]] + x[end+2:]
elif x[end+2] == '{':
begin = x.find('{{')
x = x[:begin] + var[x[begin+2 : end]] + x[end+2:]
else :
begin = x.rfind('{{')
x = x[:begin] + var[x[begin+2 : end]] + x[end+2:]
print x
| true |
ef53c04c4f7085a85906fd95c862136f40f3e1e4 | dzvigelsky/Anti_Mode | /AntiMode.py | 2,203 | 4.25 | 4 | import time
start_time = time.clock() # The clock function
def main():
frequencies = {}
text_file = input("What is the name of the text file you want to read? ")
File_object = open(text_file, 'r') # You can put in the name of the file here
lines = (File_object).readlines() # Read the file and sort it into a list
File_object.close()
for i in lines: # Adds the numbers from the text file to the dictionary
if float(i) in frequencies:
frequencies[int(i)] += 1
else:
frequencies[int(i)] = 1
def minimums(dictionary):
min_value = float("inf") # first lowest number must be the greatest possible entity to compare to
for k, v in dictionary.items():
if v < min_value: # If smallest value is less than the previous
min_value = v # Now you replace the smallest value
nums = '' # Create this string in order to store the smallest value(s)
for k, v in dictionary.items(): # Adds the smallest number(s) to a string
if v == min_value:
nums += str(k) + ', '
print("The number(s) that appeared the least amount of times is/are: " + nums.rstrip(
', ') + " with a frequency of: " + str(min_value)) # The final print statement
minimums(frequencies)
main() # Call the main function
print("the code runs for: " + str((time.clock() - start_time) * 1000) + " milliseconds") # Final statement printed out
# Advantages:
# On average, ran file1 and file2 faster compared to the other program
# Dictionaries are literally the ideal data structure in this case because you only need to deal with keys and values
# They don't require indexes unlike the other program
# This is why the program runs faster when dealing with larger text files
# Disadvatages:
# Requires more memory due to hashing process compared to the other program
# Essentially, all of the numbers in the text file are the "keys" and the amounts of time they appear are the hashes
# The hash function attributes all of the keys to their appropriate value
# When dealing with smaller text files, the hashing processes will cause this program to run slower
| true |
b80f78ad9e4e5771e748dbe9b4dac54e39f1f044 | fanj1/RobotTeamProject | /sandbox_motors_new/person3_motors.py | 2,677 | 4.625 | 5 | """
Functions for TURNING the robot LEFT and RIGHT.
Authors: David Fisher, David Mutchler and Jun Fan.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
# DONE: 2. Implment turn_left_seconds, then the relevant part of the test function.
# Test and correct as needed.
# Then repeat for turn_left_by_time.
# Then repeat for turn_left_by_encoders.
# Then repeat for the turn_right functions.
import ev3dev.ev3 as ev3
import time
def test_turn_left_turn_right():
"""
Tests the turn_left and turn_right functions, as follows:
1. Repeatedly:
-- Prompts for and gets input from the console for:
-- Seconds to travel
-- If this is 0, BREAK out of the loop.
-- Speed at which to travel (-100 to 100)
-- Stop action ("brake", "coast" or "hold")
-- Makes the robot run per the above.
2. Same as #1, but gets degrees and runs turn_left_by_time.
3. Same as #2, but runs turn_left_by_encoders.
4. Same as #1, 2, 3, but tests the turn_right functions.
"""
def turn_left_seconds(seconds, speed, stop_action):
"""
Makes the robot turn in place left for the given number of seconds at the given speed,
where speed is between -100 (full speed turn_right) and 100 (full speed turn_left).
Uses the given stop_action.
"""
def turn_left_by_time(degrees, speed, stop_action):
"""
Makes the robot turn in place left the given number of degrees at the given speed,
where speed is between -100 (full speed turn_right) and 100 (full speed turn_left).
Uses the algorithm:
0. Compute the number of seconds to move to achieve the desired distance.
1. Start moving.
2. Sleep for the computed number of seconds.
3. Stop moving.
"""
def turn_left_by_encoders(degrees, speed, stop_action):
"""
Makes the robot turn in place left the given number of degrees at the given speed,
where speed is between -100 (full speed turn_right) and 100 (full speed turn_left).
Uses the algorithm:
1. Compute the number of degrees the wheels should turn to achieve the desired distance.
2. Move until the computed number of degrees is reached.
"""
def turn_right_seconds(seconds, speed, stop_action):
""" Calls turn_left_seconds with negative speeds to achieve turn_right motion. """
def turn_right_by_time(degrees, speed, stop_action):
""" Calls turn_left_by_time with negative speeds to achieve turn_right motion. """
def turn_right_by_encoders(degrees, speed, stop_action):
""" Calls turn_left_by_encoders with negative speeds to achieve turn_right motion. """
test_turn_left_turn_right() | true |
c7ea01d08f8b054e1570ca82272c5731780fe9f9 | NV230/Stock-Market | /search.py | 1,012 | 4.125 | 4 | # Stock Market
"""
@authors: Keenan, Nibodh, Shahil
@Date: Feb 2021
@Version: 2.2
This program is designed to return the prices of stocks
Allows the user to input the number stocks they want to compare and asks for the ticker for each stock.
"""
# Calculate daily change from close - previous close
# yahoo finance library is where we get stock market information.
import yfinance as yf
# Creates an array to hold the inputted tickers
stocks = []
#Asks the user the amount of stocks they want to compare
numOfStocks = int(input("How many stocks do you want to compare? \n"))
#Loop that iterates for the number of stocks that the user wants to compare
for i in range(numOfStocks):
print("List the stock ticker (ex: WMT) and then the name (ex: Walmart)")
firstOne = input("Ticker: ")
secondOne = input("Name: ")
ticker = firstOne
table = yf.download(ticker)
print("")
print("")
print("")
print("")
print("Daily Change for " + secondOne)
print("")
print(table)
print(stocks)
| true |
447f2807b9e1fe0fb10f29ace5f2957080cf6f47 | chao-ji/LeetCode | /python/array/use_input_array_as_auxiliary_memory/lc27.py | 2,362 | 4.15625 | 4 | """27. Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
"""
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
# The Idea:
# LOOP INVARIANT:
# at any point,
#
# nums[0], ..., nums[i] contains numbers != `val`
# * * * * * * - - - - .
#
# 0 i j
# <=equal to `val`==> check if nums[j] != val
i = -1
for j in range(len(nums)):
# in each iteration, we check if we can extend the current streak of
# numbers NOT equal to `val` ending at `nums[i]`
if nums[j] != val:
# we CAN extend the current streak of number NOT equal to `val`
i += 1
nums[i] = nums[j]
# otherwise, we simply increment `j`, until we find the next number
# != `val`
return i + 1
| true |
3d057680982ace7ea0ab217be3c8667484f1d1f8 | SACHSTech/ics2o1-livehack-2-DanDoesMusic | /problem1.py | 678 | 4.34375 | 4 | ###this takes the 2 speeds the limit and the users speed###
speed = int(input("how fast was the diver: "))
limit = int(input("what is the speed limit: "))
###this chacks if they are above the speed limit it took me a bit but i got it working###
if (speed - limit) >= 1 :
print("your fine is 100$")
elif (speed - limit) >= 21 :
print("your fine is 270$")
elif (speed - limit) >= 31 :
print("your fine is 570$")
else :
print ("you are within the limit")
###it checks to see if you are above 1 u/h or unit per hour then it checks if you are 21 u/h above then 31 or more and determines your fine based on what you cross if you are below or at the limit you are safe### | true |
fcbf5247a1961337748b5181a30e1d55a451e201 | zar777/exercises | /chapter_one/unique_characters.py | 934 | 4.125 | 4 | """Implement an algorithm to determine if a string has all unique characters. What if you
can not use additional data structures? Exercises 1.1 """
class UniqueCharacters(object):
"""this class represents an empty dictionary dictionary"""
def __init__(self):
self.dictionary = {}
def unique(self, string):
"""this method is created to return the first child, given his parent"""
count = 0
numbers_occurrence = 0
if string != "":
for letter in string:
if letter not in self.dictionary:
self.dictionary[letter] = 0
else:
count += 1
self.dictionary[letter] = 1
return count
if __name__ == '__main__':
string = "parallelo"
unique_characters = UniqueCharacters()
print string
print unique_characters.unique(string)
print unique_characters.dictionary
| true |
5fdc21c50426bbeffd1fab5e53df23c7fe218cd3 | zar777/exercises | /Chapter_three/three_stacks.py | 2,384 | 4.21875 | 4 | """Describe how you could use a single array to implement three stacks. Exercises 3.1
I WRONG BECAUSE I USE A LIST AND NOT AN ARRAY"""
class ThreeStacks(object):
"""this class is created to represent an empty array which there are only two divisors used by
delimited the three stacks"""
def __init__(self):
self.array = ["Divisor_one", "Divisor_two"]
def push_first_stack(self, element):
"push element in the first stack"
self.array.insert(0, element)
def push_second_stack(self, element):
"push element in the second stack"
self.array.insert(self.array.index("Divisor_one") + 1, element)
def push_third_stack(self, element):
"push element in the third stack"
self.array.insert(self.array.index("Divisor_two") + 1, element)
def pop_first_stack(self):
"pop element in the first stack"
if self.array[0] != "Divisor_one":
self.array.pop(0)
def pop_second_stack(self):
"pop element in the second stack"
if self.array[self.array.index("Divisor_one") + 1] != "Divisor_two":
self.array.pop(self.array.index("Divisor_one") + 1)
def pop_third_stack(self):
"pop element in the third stack"
if self.array.index("Divisor_two") + 1 != len(self.array):
self.array.pop(self.array.index("Divisor_two") + 1)
if __name__ == '__main__':
three_stack = ThreeStacks()
three_stack.pop_first_stack()
three_stack.pop_second_stack()
three_stack.pop_third_stack()
print three_stack.array
three_stack.push_first_stack(2)
three_stack.push_first_stack(4)
three_stack.push_first_stack(8)
print three_stack.array
three_stack.push_second_stack(55)
three_stack.push_second_stack(33)
three_stack.push_second_stack(22)
three_stack.push_second_stack(1)
print three_stack.array
three_stack.push_third_stack(99)
three_stack.push_third_stack("A")
print three_stack.array
three_stack.pop_first_stack()
three_stack.pop_second_stack()
three_stack.pop_third_stack()
print three_stack.array
three_stack.pop_first_stack()
three_stack.pop_second_stack()
three_stack.pop_third_stack()
print three_stack.array
three_stack.pop_first_stack()
three_stack.pop_first_stack()
three_stack.pop_first_stack()
print three_stack.array
| true |
7f26fdf3884a01b784ac349de84b950039741d55 | thedrkpenguin/CPT1110 | /Week 4/list_modification4.py | 248 | 4.21875 | 4 | FOOD = ["Pizza", "Burgers", "Fries", "Burgers","Ribs"]
print("Here is the current food menu: ")
print(FOOD)
FOOD_ITEM = str(input("Which item would you like to remove? "))
FOOD.remove(FOOD_ITEM)
print("Here is the new food menu: ")
print(FOOD)
| true |
727d74cf441d3d1aa62a98c6b4a2b933b9ccaee0 | thedrkpenguin/CPT1110 | /Week 2/largestnumberCheckFOR.py | 202 | 4.21875 | 4 | num = 0
max_num = 0
for i in range(4):
num = int(input("Enter a value for number: "))
if num > max_num:
max_num = num
print("The largest number entered is ", max_num)
| true |
83b0b2e4b0eb8ae1db2074ee4d953198ae0eafb0 | learning-dev/46-Python-Exercises- | /ex19b.py | 516 | 4.3125 | 4 | """ The python way of checking for a string is pangram or not """
import string
def is_pangram(in_string, alphabet=string.ascii_lowercase): # function for checking pangram or not
alphaset = set(alphabet) # creating a set of all lower case
return alphaset <= set(in_string.lower()) # checking
while True:
in_str = raw_input("Enter a string to check :")
if in_str is None or in_str.isspace():
print "Error: Invalid input!"
continue
else:
break
print is_pangram(in_str)
| true |
dd16f246a0197d5e21e965bc0e8c3e1f4b4bc158 | dmoses12/python-intro | /pattern.py | 929 | 4.25 | 4 | def pattern(number):
"""Function to generate a pattern
syntax: pattern(number)
input: number
output: symmetrical pattern of _ and * according to number provided
return: 0 when complete
"""
print "Pattern for number: %s" % number
# complete this function
max_stars = 2 * number - 1 # max number of stars to print
num_ulines = number - 1; # number underscores for first line
# print to max_stars and fill with _
for i in range(1, max_stars, 2):
print "_ " * num_ulines + "* " * i + "_ " * num_ulines
num_ulines -= 1 # decrease underscores as we increase stars
# complete and reverse pattern
for i in range(max_stars, 0, -2):
print "_ " * num_ulines + "* " * i + "_ " * num_ulines
num_ulines += 1 # increase underscores as we decrease stars
return 0
if __name__ == "__main__":
pattern(1)
pattern(2)
pattern(3)
pattern(4)
| true |
efce03538801ff68cee65346772dff3dd078f35f | harshalkondke/cryptography-algorithm | /Multi.py | 533 | 4.125 | 4 | def encrypt(text, key):
result = ""
for i in range(len(text)):
char = text[i]
if char.isupper():
mychar = ord(char) - 65
ans = (mychar * key) % 26
result += chr(ans + 65)
else:
mychar = ord(char) - 97
ans = (mychar * key) % 26
result += chr(ans + 97)
return result
text = input("Enter your text: ")
key = int(input("Enter key: "))
print("Text : " + text)
print("key : " + str(key))
print("Cipher : " + encrypt(text, key))
| true |
7a74c15d52ff4840ea630060d12fde662cf476fc | Abraham-Lincoln-High-School-MESA/2020-2021-Python | /1.- Print statements, Variables, and Operators/2_Operators.py | 2,520 | 4.1875 | 4 | # 11/08/2020 @author: Giovanni B
""" Operators are symbols that tell the compiler to perform certain mathematical or logical manipulations.
For instance, arithmetic, comparison, boolean, etc. There are several operators, and they obviously
have a precedence order, this is, the order of "importance" to decide which one to perform first,
for which I added an image into the folder that explains it.
PD: In the image they forgot to add the parenthesis, which have the highest precedence
Most of the operators are used for integer and boolean operations, the only notable exception would
be that besides to sum integers, we can use the + operator to concatenate strings, this is, to
join them """
# String operators
print("Concatenating " + "strings") # Concatenating strings
# All of the following are integer operators
print(5 + 10) # 15; Summing
print(10 - 2) # 8; subtracting
print(30 / 3) # 10; dividing
print(7 * 9) # 63; multiplying
x = 8 # We can also use operators with variables
y = 17
print(x - y) # -9; subtracting
print(x + y) # 25; summing
print(9 % 4) # 1; reminder of the division
print(8 ** 2) # 64; to the power
# All of the following are boolean operators
print(5 == 5) # True; is 5 equal to 5?
print(6 == 0) # False; is 6 equal to 0?
print(4 != 0) # True; is 4 not equal to 0?
print(5 != 5) # False; is 5 not equal to 5?
print(10 > 10) # False; is 10 greater than 10?
print(10 >= 10) # True; is 10 greater than or equal to 10?
print(7 < 10) # True; is 7 less than 10?
print(7 <= 7) # True; is 7 less than or equal to 7?
# We can also "mix" integer and boolean operators
print(10 > (2 * 3)) # True; is 10 greater than 6 (2 * 3)?
print(10 == (5 * 2)) # True; is 10 equal to 10 (5 * 2)?
| true |
e645d502352b2169a169e6b07b08d143ba88e794 | Abraham-Lincoln-High-School-MESA/2020-2021-Python | /4.- Lists/z_Practice Problems from HW 3/0- Coffee_Machine.py | 1,463 | 4.5 | 4 | # Initializing variables
waterPerCup = 0
milkPerCup = 0
beansPerCup = 0
costPerCup = 0
# Inputting the resources
print("Enter the machine's resources")
water = int(input("ml of water: "))
milk = int(input("ml of milk: "))
beans = int(input("gr of coffee beans: "))
cups = int(input("cups: "))
money = int(input("How much do you have? $"))
# Selecting a coffee
print("What do you want to buy?")
print("1.- Espresso $4\n2.- Latte $7\n3.- Cappuccino $6")
option = int(input())
# Assigning the needed resources
if option == 1:
waterPerCup = 250
milkPerCup = 0
beansPerCup = 16
costPerCup = 4
elif option == 2:
waterPerCup = 350
milkPerCup = 75
beansPerCup = 20
costPerCup = 7
elif option == 3:
waterPerCup = 200
milkPerCup = 100
beansPerCup = 12
costPerCup = 6
# Inputting the number of cups
cupsOfCoffee = int(input("How many cups would you like? "))
# Calculating the maximum of coffee cups we can make
min = water // waterPerCup
if milkPerCup != 0 and milk // milkPerCup < min:
min = milk // milkPerCup
if beans // beansPerCup < min:
min = beans // beansPerCup
if money // costPerCup < min:
min = money // costPerCup
if cups < min:
min = cups
# Choosing what message to display
if min == cupsOfCoffee:
print("Here you go!")
elif min < cupsOfCoffee:
print("I can only make " + str(min) + " cups")
elif min > cupsOfCoffee:
print("I can even make " + str(min) + " cups")
| true |
e408ea0cafaad6313366c9fce5c523fbe758479c | max-zia/nand2tetris | /assembly language/multiply.py | 619 | 4.125 | 4 | # multiply integers a and b without multiplication
def multiply(a, b):
# for all n, n*0 = 0
if a == 0 or b == 0:
return 0
# operate on absolute values
product = abs(a)
# add a to itself b times and store in product
for i in range(1, abs(b)):
product += abs(a)
# if a or b < 0, product must be negative
# if a & b < 0, product must be positive
if (a < 0):
product = -product
if (a < 0):
product = -product
return product
# you can string multiply() together n times to multiply
# arbitrarily long combinations of numbers. Alternatively,
# you can change the function to accept any number of kwargs | true |
e358a76b696ef686576b746673732144d79d23d3 | sanashahin2225/ProjectEuler | /projectEuler1.py | 365 | 4.25 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.Find the sum of all the multiples of 3 or 5 below 1000.
def multipleOfThreeandFive(num):
sum = 0
for i in range(1,num):
if i%3 == 0 or i%5 == 0:
sum += i
return sum
print(multipleOfThreeandFive(1000)) | true |
9a7f00adcc48b8f31f768f495178aac5819f3b32 | mmlakin/morsels | /count_words/count.py | 483 | 4.28125 | 4 | #!/usr/bin/env python3
"""count.py - Take a string and return a dict of each word in the string and the number of times it appears in the string"""
from string import punctuation as punctuationmarks
import re
def count_words(line: str) -> dict:
""" Use re.findall to return a list of words with apostrophes included """
regex=r"[\w']+"
linewords = re.findall(regex, line.lower())
return {
word:linewords.count(word)
for word in set(linewords)
}
| true |
fedb1fb0c6cd6ec4bb814ae119317c47dae223ad | ZergOfSwarm/test | /otslegivaet_knopki_mishi22.py | 1,186 | 4.4375 | 4 | from tkinter import *
#initialize the root window
root = Tk()
#############################
# 7. Click action
#############################
# 1
def printHello():
print("Hello !")
# Once the button is clicked, the function will be executed
button_1 = Button(root, text="Click me !", command = printHello)
button_1.pack()
#BINDING FUNCTIONS
# http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
# 2
def callback(event):
print("clicked at", event.x, event.y)
# Binding just means that we bind a function to an event that happens with a widget
button_2 = Button(root, text="Click it")
button_2.bind("<Button-1>", callback)
button_2.pack()
def leftClick(event):
print("Left Click")
def rightClick(event):
print("Right Click")
def scroll(event):
print("Scroll")
def leftArrow(event):
print("Left Arrow key")
def rightArrow(event):
print("Right Arrow key")
# Set the window size
root.geometry("500x500")
root.bind("<Button-1>", leftClick)
root.bind("<Button-2>", scroll)
root.bind("<Button-3>", rightClick)
root.bind("<Left>", leftArrow)
root.bind("<Right>", rightArrow)
# Keep the window runing until user closes it
root.mainloop()
| true |
8957d8156bc7f65ea0df95bab71c205aa3978262 | OscarH00182/Python | /Stack.py | 1,067 | 4.34375 | 4 | """
Stack:
This is how we create a stack, we create a simple class for it
and create its functions to handle values being pass to it
"""
class Stack:
def __init__(self):#constructor
self.stack = [] #we create an array named stack to handle the stack
self.size = -1
def Push(self,datavalue):#This is what adds values to the stack
self.stack.append(datavalue)#we add the value to the stack
self.size +=1
def Pop(self):
print("Value that was popped: ",self.stack.pop())
self.size -=1
if(self.size == -1 ):
print("The stack is empty")
def Peek(self):#We create peek to look at the first value of the stack
return self.stack[0]
def Size(self):
return self.size
stackOne = Stack()
stackOne.Push(66)
stackOne.Push(77)
stackOne.Push(88)
stackOne.Push(99)
print("First Value of stack: ",stackOne.Peek())
stackOne.Pop()
stackOne.Push(11)
print("Size of Stack: ",stackOne.Size())
print("\nPopping Entire Stack")
for i in range(stackOne.Size()+1):
stackOne.Pop()
| true |
b6fadc89174f195651271f86522c39c9d0ec444b | OscarH00182/Python | /ChapterTwo.py | 2,094 | 4.5625 | 5 | name = "Oscar Hernandez"
print(name.title())
print("Upper Function: ",name.upper())
print("Lower Function: ",name.lower())
firstName = "Oscar"
lastName = "Hernandez"
fullName = firstName + " " +lastName
print("Combinding Strings: ",fullName)
#rstrip Function
languagee = "Python "
language = "Python "#Notice: "Python " has a space vs "Python"
#rstrip function drops the extra space
print("\nReducing Space",language.rstrip()+"|")
print("No Reducing Space",language+"|")
print("\nExcerises 2-3 to 2-7")
"""
Store a person’s name in a variable, and print a message to that person.
Your message should be simple, such as, “Hello Eric, would you like to
learn some Python today?”
"""
name = "Eric"
print("2-3")
print("Hello " + name +",would you like to learn some Python today?")
"""
Store a person’s name in a variable, and then print that person’s name
in lowercase, uppercase, and titlecase
"""
print("\n2-4")
name = "Jack"
print(name.lower())
print(name.upper())
print(name.title())
"""
Find a quote from a famous person you admire. Print the quote and the
name of its author. Your output should look something like the following,
including the quotation marks:
Albert Einstein once said, “A person who never made a
mistake never tried anything new.”
"""
print("\n2-5")
print("Albert Einstein once said, “A person who never made a mistake never tried anything new.”")
#Skipped 2-6: Too easy
""""
Store a person’s name, and include some whitespace characters at the beginning
and end of the name. Make sure you use each character combination, "\t" and "\n",
at least once. Print the name once, so the whitespace around the name is displayed.
Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip()
"""
print("\n2-7")
name = " Oscar "
print(name)
print("\n",name)#new space
print("\t",name)#tab
print(name.lstrip())#left whitespace
print(name.rstrip())#right whitespace
print(name.strip())#both whitespace
#str():converts int/float/etc to string so accept into another string
age = 21
message = "Happy " + str(age) + "st birthday!"
print(message)
| true |
9a5dd11136eb707a020db2e3dc97f0b03e91c891 | jpbayonap/programs | /py_prog/decimals1.py | 2,195 | 4.21875 | 4 | #the objective of this programm is to compkute the division of one by a random integer given by the user
#for repeated decimals the programm will print the repeated digits after reaching the first repetition
from time import sleep # used for defining the intervals of time between each operation
d= int(input("Input a denominator:"))
print(f"1/{d} is computed")
myli =[0]*(d+1) #this array will play a critical role in the computation
#for any integer d , when we compute the division of it with one by recusion .
mel =[0]*(d+1)
count= 0 # tell us the number of operations carried out
done = False # condition for finishing the computation
x=1 # first step of the division i.e. how many times is d contained in one 0
e = d//10
s = ""
while not done:
x= x*10 #because the first quotient is zero we increase it by multiplying it by ten
quotient= x//d #how many integer times can d fit in the increased value of x
remainder= x%d # units needed to add to the product of quotient and d for getting x
print(quotient)
myli[count]= quotient #fill the array with the computed quotient
mel[count] =remainder
count += 1 #tells the program to move towards the next operation
print(f"{count}:{quotient}({remainder})") #show the user the result of the operation
sleep(0.5)
# convert the array into a string in order to get the appropiate enviroment for printing the repeated decimals anwers
if remainder ==0: # if there is no units needed to add in the computation , the division is over and it yields a finite answer
done= True # stop the computation
else: # for other case bring the computation proccess to the next step by changing the value of the expanded value with the remainder of the
#previous step
x =remainder
if any([b == remainder for b in mel[:count] ]) : #when computing the division of one and an integer the values admitted for quotient are restricted
#to 1,...,d . hence if in the computation there is two values of quotient which coincide the entries of myli between them will be repeated
done= True
my= [str(a)for a in myli]
print("the result is")
print(''.join(my[:count]) + '('+''.join(my[my.index(my[count-1]):count])+')')
| true |
b0679af54f904e6f16b72b0dbe786875b55c9778 | martinvedia/app-docs | /codedex/enter_pin.py | 243 | 4.21875 | 4 | # This program accept a correct Bank pink value 1234
print("BANK OF CODÉDEX")
pin = int(input("Enter your PIN: "))
while pin != 1234:
pin = int(input("Incorrect PIN. Enter your PIN again: "))
if pin == 1234:
print("PIN accepted!") | true |
ee31c03c140160d5ec47e21eccfa56388aa93343 | Nduwal3/Python-Basics-II | /soln10.py | 926 | 4.34375 | 4 | # Write a function that takes camel-cased strings (i.e. ThisIsCamelCased), and converts them to snake case (i.e. this_is_camel_cased).
# Modify the function by adding an argument, separator, so it will also convert to the kebab case (i.e.this-is-camel-case) as well.
def snake_case_to_camel_case(camel_cased_string):
snake_cased = camel_cased_string
for char in camel_cased_string:
if(char.isupper()):
snake_cased = snake_cased.replace(char , '_' + char.lower())
print(snake_cased.strip('_'))
snake_case_to_camel_case('ThisIsSnakeCased')
def case_convert(input_string , separator):
result_string = input_string
for char in input_string:
if (char.isupper()):
result_string = result_string.replace(char , separator + char.lower())
result_string = result_string.strip(separator)
return result_string
print(case_convert("ThisIsKebabCased", '-'))
| true |
2dd2cffad194197ca43e70ed7ea2bd26a802ddf3 | Nduwal3/Python-Basics-II | /soln14.py | 719 | 4.40625 | 4 | # Write a function that reads a CSV file. It should return a list of dictionaries, using the first row as key names, and each subsequent row as values for those keys.
# For the data in the previous example it would
# return: [{'name': 'George', 'address': '4312 Abbey Road', 'age': 22}, {'name': 'John', 'address': '54 Love Ave', 'age': 21}]
import csv
def read_csv(filename):
try:
with open (filename, 'r') as csv_file:
data = csv.DictReader(csv_file, delimiter= ',')
my_list = []
for row in data:
my_list.append(row)
return (my_list)
except FileNotFoundError:
print("file not found")
print(read_csv('files/test.csv'))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.