blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
cbd93b0aa443018eefced3bfd2a768cf860a8f4a | Darshnadas/100_python_ques | /DAY10/day10.31.py | 234 | 4.21875 | 4 | """
Define a function which can print a dictionary where the keys are numbers between 1 and 20
(both included) and the values are square of keys.
"""
def dict_sq():
num = {i : i**2 for i in range(1,21) }
print(num)
dict_sq() | true |
16bba2ce2b61972e64dd2b26dd094c69c6cc7b38 | Darshnadas/100_python_ques | /DAY9/day9.29.py | 550 | 4.375 | 4 | """
Define a function that can accept two strings as input and print the string with maximum length in
console. If two strings have the same length, then the function should print all strings line by line.
"""
def length(l1,l2):
if len(l1) > len(l2):
print("The maximum length is of this string: ",l1)
if len(l1) < len(l2):
print("The maximum length is of this string: ",l2)
elif len(l1) == len(l2):
print("Same length:", l1, l2)
l1 = input("Enter a line-")
l2 = input("Enter 2nd line- ")
print(length(l1,l2)) | true |
6a8ff06a7fed2e3b96cac23bef503f3b690d3dd5 | Darshnadas/100_python_ques | /DAY2/day2.6.py | 640 | 4.21875 | 4 | """
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 _ C _ D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.For
example Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
"""
from math import sqrt
C, H = 50, 30
def calc(D):
return sqrt((2 * C * D)/ H)
D = input().split(",")
D = [str(round(calc(float(i)))) for i in D]
print(",".join(D))
| true |
d97813b66c9c127c86752098bbbdf23e772bf7a6 | VitorNovaisV/Algoritmos-em-Python | /ex059.py | 1,072 | 4.15625 | 4 | num1 = int(input('Digite um número: '))
num2 = int(input('Digite mais um número: '))
menu = 0
while menu !=5:
print('escolha uma opção do menu:')
menu=int(input('''
[ 1 ]: para soma
[ 2 ]: para multiplicar
[ 3 ]: para ver qual e o maior
[ 4 ]: para escolher novos numeros
[ 5 ]: para sair do programa
Digite aqui: '''))
if menu == 1:
op1 = num1 + num2
print(f'a soma entre {num1} e {num2} é {op1}')
if menu ==2:
op2 = num1 * num2
print(f'a multiplicação entre {num1} e {num2} é {op2}')
if menu == 3:
if num1 > num2:
print(f'O Número maior é {num1}')
elif num2 > num1:
print(f'O Número maior é {num2}')
else:
print(f'Os valores {num1} e {num2} são iguais.')
if menu == 4:
num1 = int(input('Digite o novo 1° número: '))
num2 = int(input('Digite o novo 2° número: '))
if menu == 5:
print('Finalizando...')
if menu == 0 or menu <0 or menu >5:
print('opção invalida')
print('End')
| false |
d2a826ee6844f53775f64012a2adb233eaceee09 | hoangreal/ChuVietHoang-Fundamentals-C4T2 | /Lesson 3/Homework Lesson 3/Homework_4.py | 584 | 4.25 | 4 | #Create a random list of tuples with random item in each tuples
nTuple = int(input("Enter your number of Tuple: "))
nItem = int(input("Enter your number of Tuple's item: "))
TupleList=[() for x in range(nTuple)]
for i in range(nTuple):
for j in range(nItem):
add = int(input("Enter your item: "))
TupleList[i] += (add,)
#Change the last Tuple's item of a list to a random number
n = int(input("Your desired number: "))
for i in range(nTuple):
Object_List = list(TupleList[i])
Object_List[-1] = n
TupleList[i] = tuple(Object_List)
print(TupleList)
| true |
1e04d7b528c03b8cb8201b58ffc6d97cf1aca8b0 | hoangreal/ChuVietHoang-Fundamentals-C4T2 | /Lesson 3/Homework Lesson 3/Homework_5.py | 437 | 4.15625 | 4 | def selection_sort(list): #Find the minimum number in each stage of a list
for i in range(len(list)):
min = list[i]
for j in range(i+1,len(list)):
if list[j] < list[i]:
list[i],list[j] = list[j],list[i]
return list
n = int(input("Enter your number of item in a list: "))
list = []
for i in range(n):
list.append(int(input("Enter your number: ")))
a = selection_sort(list)
print(a) | true |
ffdbfe77756edb27d75f4cdb3608f7188f379bad | andrescerv/BEDU-pilot-class | /code-guide/02_subsetting_lists.py | 1,239 | 4.34375 | 4 | # ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
# 1. Subset and conquer
# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Print out second element from areas
print(areas[1])
# Print out last element from areas
print(areas[-1])
# Print out the area of the living room
print(areas[5])
# ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
# 2. Subset and calculate
# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Sum of kitchen and bedroom area: eat_sleep_area
eat_sleep_area = areas[3] + areas[7]
# Print the variable eat_sleep_area
print(eat_sleep_area)
# ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
# 3. Slicing and dicing
# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Use slicing to create downstairs
downstairs = areas[:6]
# Use slicing to create upstairs
upstairs = areas[6:]
# Print out downstairs and upstairs
print(downstairs, upstairs) | true |
602aabfe49fb8b9bcbf3798686d1b3327c6bb2d3 | ditsuke/cs50_2021_psets | /pset6/mario/more/mario.py | 266 | 4.1875 | 4 | from cs50 import get_int
# Get height from user, keep asking until 1 <= h >= 8
while True:
h = get_int("Height: ")
if h >= 1 and h <= 8:
break
# Print staircase
for r in range(h):
print(" " * (h - r - 1) + "#" * (r + 1) + " " + "#" * (r + 1))
| true |
73a644f9b4b698d9302a33aa55dfa75017e8ec51 | katyagovorkova/algorithms | /sorting/mergesort.py | 1,235 | 4.1875 | 4 | from check_sorted import check_sorted
def merge(A, B):
"""
Takes as an input two sorted lists and returns merged sorted list.
"""
i, k = 0, 0 # reserve incidences to loop over A and B
merged = [] # initialize merged list
while i < len(A) and k < len(B):
if A[i] <= B[k]:
merged.append(A[i])
i += 1
else:
merged.append(B[k])
k += 1
# now we might have leftovers in either A or B
while i < len(A):
merged.append(A[i])
i += 1
while k < len(B):
merged.append(B[k])
k += 1
return merged
def mergesort(l):
"""
Takes as an input a list and returns it sorted with Mergesort algorithm.
"""
n = len(l)
if n <= 1:
return l
middle = n//2
left = l[:middle]
right = l[middle:]
mergesort(left)
mergesort(right)
sorted_l = merge(left, right)
for i in range(n):
l[i] = sorted_l[i]
return l
if __name__=='__main__':
# tests
check_sorted(mergesort([]))
check_sorted(mergesort([0]))
check_sorted(mergesort([1,2,3,4,0]))
check_sorted(mergesort([1,2,3,4,0,0,1,2,3,4]))
check_sorted(mergesort(list(range(100,-1,-1)))) | true |
73054499b9c4d9a5bb445e701dfbf18650859a72 | geekdudeAndrew/Python-Crash-Course | /238ch5 caseInsensitive.py | 518 | 4.1875 | 4 | #case Insensitive
# page 238 in Python crash course chapter 5 page 77 in pdf
# ignoring case when checking for equality
# when you want to check a value irregardless of its capitalization you can
# check the the capitalized version of the name, or lowercase, uppercase, or titlecase for that matter.
myname = 'andrew'
print('my name is ' + myname)
print('Did I forget to capatalize my name?')
print(myname.title() == 'Andrew')
print('Am i still the same person?')
myname= 'Andrew'
print(myname.title() == 'Andrew')
| true |
909d020f53b3541514aa10519bc556f1688c79f4 | geekdudeAndrew/Python-Crash-Course | /pg 77ch5 if apples.py | 1,031 | 4.21875 | 4 | #if Apples
# pg77 ch5 Checking for Inequality
# displaying use of an if statement to display a list
# and using the inequality operator in order to conditionaly change case of list elements.
apples = ['granny smith', 'red delicious', 'golden delicious', 'fuji',
'jonathan', 'jonagold', 'koru', 'pink lady', 'honneycrisp', 'imac', 'Mac Classic',
'macbook pro', 'emac', 'preforma', 'g3', 'g4','g5', 'apple IIgs', 'lisa']
for apple in apples:
# if apple.lower() == 'imac': #every time it finds the word imac or emac
# print(apple.lower()) #it will print it in lowercase
# else:
# if apple.lower() == 'emac': #I understand the second letter is susposed
# print(apple.lower()) #to be capatilized but idk how to do that yet
# else: #rewrote this part to make it simpler
# print(apple.title())
if apple.lower() != 'imac':
if apple.lower() != 'emac':
print (apple.title())
else:
print(apple.lower())
| true |
5dd4b8b74cbd5c950ae334d7f1329ec676d0e4ef | geekdudeAndrew/Python-Crash-Course | /ch7 users functionized.py | 1,772 | 4.25 | 4 | #made the users script from chapter 7 into a function to practice
#to practice function info from chapter 8.
#users Again
#ch7 filling a dictionary with user input pg 130 (windows)
# when presented with a new username the script adds the user to the list.
# the user list and dictionary is probably redundnat but whatever.
# compiled all the person names I have used in my scripts
def users7(username):
users = ["Admin","Bob","Larry","Harley","Fluff","Jack","Adam","Kirk","Opensesme",'bob','jimmy','jerry','lisa','linda','casey','colby', 'zendarr', 'Bloaty', 'harles','bob','john','Andrew','joe','jim','george','aiden','jill','tom']
greetings = {
"Admin": "Good morning Dave",
"Bob": 'How do you use a computer with no hands?',
"Larry": 'Larrycomputer 3000 tracking crime',
"Harley": 'No you cant go into moms room',
"Fluff": 'Stop walking across the keyboard',
"Jack": 'No you cannot reset the system clock 500 years in the past',
"Adam": 'we have given you access. Dont ruin it for us.',
"Kirk": 'Good morning Captian',
"Opensesme": 'Debug mode activated',
}
username = username.title();
print ("Hello " + username);
if username not in users:
messsage = input("\nwhat message would you like to be greeted with when you log in?")
greetings[username] = messsage;
users.insert(0,username);
else:
if username in greetings:
print (greetings[username]);
else:
print("you allready have a user");
on = True;
while on:
username = input ("what is your username?");
if username.title() == ("Quit"):
on = False;
continue
users7(username);
| true |
a5cb7bec132c3d957b35398956efee48e024b15d | Erkin97-zz/python-examples | /ep1/1st-term/calculator.py | 859 | 4.1875 | 4 | # calculator
# plus , minus, multiply, divide
def plus(a = 0, b = 0): # default
return a+b
def minus(a, b):
return a-b
def multiply(a, b):
return a*b
def divide(a, b = 1):
return a/b
def calculate(a, b, operation):
if (operation == "+"):
return plus(b = b, a = a)
elif (operation == "-"):
return minus(a, b)
elif (operation == "*"):
return multiply(a, b)
elif (operation == "/"):
return divide(b = b , a = a * 1.0)
else:
return "Incorrect operation"
while(True): # infinite loop, because always true
first = float(input("Enter first number: "))
second = float(input("Enter second number: "))
operation = input("Enter operation: ")
if (operation == "end"):
break # escape infinite loop when operation equal to end
print("Your calculation:", calculate(first, second, operation))
print("Good bye") | true |
f7ccd68c7fb8c18c7a9f4c1521a5e12ecda4ef19 | DonYeh/python-while-loop-exercises | /blastoff.py | 395 | 4.125 | 4 | import time
user_input = int(input("Choose a number to start counting from: "))
while user_input >= 0:
if user_input > 20:
print("Number too large!")
user_input = int(
input("Choose a number SMALLER than 20 to start counting from: "))
continue
else:
print(user_input)
time.sleep(1)
user_input -= 1
else:
print("the end")
| true |
f10cb027369dfb0bf8484296e5c9e7cf90854f5f | DonYeh/python-while-loop-exercises | /triangle.py | 364 | 4.125 | 4 | user_input = int(input("please enter number of rows: "))
row = 0
while (row < user_input):
row += 1
spaces = user_input - row
spaces_counter = 0
while(spaces_counter < spaces):
print(" ", end='')
spaces_counter += 1
num_stars = 2*row-1
while(num_stars > 0):
print("*", end='')
num_stars -= 1
print()
| true |
c9f8612714f71d133e99894228ab899e5a56817d | Chukwuyem/IdrisWork1 | /red-black-smart.py | 2,408 | 4.21875 | 4 | #!/usr/bin/env python3
# Node representation is a record (v, b, l, r) and we use None to represent
# empty. Black height (bh) is the number of black nodes on any simple path from
# a node x (not including it) to a leaf. We'll use False for red and True for
# black.
def is_empty(node):
return node is None
def is_black(node):
if is_empty(node):
return True
else:
(_, black, _, _) = node
return black
def get_left(node):
assert not is_empty(node)
(_, _, left, _) = node
return left
def get_right(node):
assert not is_empty(node)
(_, _, _, right) = node
return right
def get_value(node):
assert not is_empty(node)
(value, _, _, _) = node
return value
# Max number of black nodes on any path from node (not including it) to a leaf.
def black_height(node):
if is_empty(node):
return 0
else:
hl = inclusive_black_height(get_left(node))
hr = inclusive_black_height(get_right(node))
return max(hl, hr)
def inclusive_black_height(node):
if is_empty(node):
return 1
else:
h = black_height(node)
if is_black(node):
h += 1
return h
# Smart constructor that flags any violations of tree invariants.
def make_node(value, black=True, left=None, right=None):
node = (value, black, left, right)
if not black:
assert is_black(left), "Red-Red on left: %s" % (node,)
assert is_black(right), "Red-Red on right: %s" % (node,)
hl = inclusive_black_height(left)
hr = inclusive_black_height(right)
assert hl == hr, "Mismatched heights:\n left=%d: %s\n right=%d: %s" % (
hl,
left,
hr,
right,
)
return node
def update_color(node, black=True):
return make_node(get_value(node), black, get_left(node), get_right(node))
def insert_recursive(root, value):
if is_empty(root):
return make_node(value, black=False)
else:
if value < get_value(root):
new_left = insert_recursive(get_left(root), value)
return make_node(get_value(root), is_black(root), new_left, get_right(root))
else:
new_right = insert_recursive(get_right(root), value)
return make_node(get_value(root), is_black(root), get_left(root), new_right)
def insert(root, value):
return update_color(insert_recursive(root, value))
| true |
5f23d1c7fba4869a3c1caaccd8091e0e58a44a1e | Sahha2001000/1LabForParadigmsProgramming | /Lab1__part2/IPZR18K__Vasyliev__Lab1__3__individual.py | 2,582 | 4.25 | 4 | def meet__user():
messageForUser = "Hello user, this progam you helped find the maximum and minimum value of two different fractional numbers.\n";
print(messageForUser)
return 1
def input__user():
userNum = int(input())
return userNum
def fraction(num_1, num_2):
fractionUser = num_1 / num_2
return fractionUser
meet__user()
exitForProgram = 1
while (exitForProgram == 1):
if exitForProgram == 1:
print("Enter top part for first fractiom")
numTopFraction_1 = input__user()
print("Enter bottom part for first fractiom")
numBottomFraction_1 = input__user()
print("Enter top part for second fractiom")
numTopFraction_2 = input__user()
print("Enter bottom part for second fractiom")
numBottomFraction_2 = input__user()
numFraction_1 = fraction(numTopFraction_1, numBottomFraction_1)
numFraction_2 = fraction(numTopFraction_2, numBottomFraction_2)
if numFraction_1 > numFraction_2:
print("numFraction_1 > numFraction_2")
numFraction_1f = str("{:.3f}".format(numFraction_1))
numFraction_2f = str("{:.3f}".format(numFraction_2))
print(f"First Fraction == MAX --> {numFraction_1f}\nSecond Fraction == MIN --> {numFraction_2f}")
print("If you want exit this program enter any number else don't exit program enter 1 ")
exitForProgram = input__user()
elif numFraction_1 < numFraction_2:
print("numFraction_1 < numFraction_2")
numFraction_1f = str("{:.3f}".format(numFraction_1))
numFraction_2f = str("{:.3f}".format(numFraction_2))
print(f"First Fraction == Min--> {numFraction_1f} \nSecond Fraction == MAX First --> {numFraction_2f}")
print("If you want exit this program enter any number else don't exit program enter 1 ")
exitForProgram = input__user()
elif numFraction_1 == numFraction_2:
print("numFraction_1 == numFraction_2")
numFraction_1f = str("{:.3f}".format(numFraction_1))
numFraction_2f = str("{:.3f}".format(numFraction_2))
print(f"First Fraction --> {numFraction_1f} == Second Fraction --> {numFraction_2f}")
print("If you want exit this program enter any number else don't exit program enter 1 ")
exitForProgram = input__user()
else:
print("If you want exit this program enter any number else don't exit program enter 1 ")
exitForProgram = input__user()
else:
exit()
| true |
fda532281e947a35bd64d60ca32d998be5c4c2c7 | bgarrisn/python_fundamentals | /02_basic_datatypes/1_numbers/02_05_convert.py | 529 | 4.4375 | 4 | '''
Demonstrate how to:
1) Convert an int to a float
2) Convert a float to an int
3) Perform floor division using a float and an int.
4) Use two user inputted values to perform multiplication.
Take note of what information is lost when some conversions take place.
'''
example= 6
x= float(example)
y= int(example)
print(x)
print(y)
floor= 6//4.5
print(floor)
val1=input("Give me a number between 1 and 10: ")
val2=input("Give me another number between 1 and 10: ")
val3=int(val1)*int(val2)
print(val3)
| true |
1390fdc8c411560956f666863825b06da52bff6b | bgarrisn/python_fundamentals | /04_conditionals_loops/04_01_divisible.py | 338 | 4.46875 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
num1=input('Give me a number between 1 and 1,000,000,000: ')
if int(num1) % 3==0:
print('Look it is divisible by 3!')
else:
print('sorry not divisible by 3') | true |
83c87aac267a1e855692ba4d9b793e053a4a5649 | memdreams/Python_Learning | /RegularExpression/BasicReUsage.py | 1,791 | 4.4375 | 4 | """
2018.07.09 Jie
Practice Basic Regular Expression Operation.
"""
import re
# 1. check if a string contains only a certain set of characters (in this case a-z, A-Z and 0-9)
def is_allowed_special_symbol(s):
p = re.compile(r'\W') # the same as: p = re.compile(r'[^a-zA-Z0-9]')
s = p.search(s)
return not bool(s)
# 2. matches a string that has an 'a' followed by 0 or more 'b''s.
# 3. an 'a' followed by one or more b's
# 4. an 'a' followed by zero or one 'b'
# 5. an 'a' followed by 3 'b's
# 6. an 'a' followed by 2 to 3 'b's
# 7. find sequences of lowercase letters joined with a underscore
# 8. find sequences of one upper case letter followed by lower case letters.
# 9. a string that has an 'a' followed by anything, ending in 'b'.
# 10. matches a word at the beginning of a string.
# 11. matches a word at end of string, with optional punctuation.
# 12. matches a word containing 'z'.
# 13. a word containing 'z', not start or end of the word.
# 14: match a string that contains only upper and lowercase letters, numbers, and underscores.
# 16: remove leading zeros from an IP address.
def is_matched(s):
p = r'ab*?' # 2
p = r'ab+?' # 3
p = r'ab?' # 4
p = r'ab{3}?' # 5
p = r'ab{2,3}?' # 6
p = r'^[a-z]+_[a-z]+$' # 7
p = r'^[A-Z][a-z]+$' # 8
p = r'a.*?b$' # 9 Q: difference between r'a.*?b$' and r'a.*b$'
p = r'^\w+' # 10
p = r'\w+\S*$' # 11
p = r'\w*z\w*?' # 12 '\w*z.\w*' why?
p = r'\Bz\B' # 13
p = r'^[a-zA-z_\d]*$' # 14
m = re.search(p, s)
return bool(m)
# A good example for delete the repeated word
re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') #'cat in the hat'
s1 = '[ab[ ASDGw245ew3.'
s2 = '-=-]['
s3 = 'Abbb_ba3bbbbbbbb'
print(is_matched(s1))
print(is_matched(s3))
| true |
393f00f11eaa1be424697c8bc1ffd612f5f824e5 | Balakumar5599/Intern-s_assignmentTW | /pachai_assignment/debug_program.py | 793 | 4.4375 | 4 | #Debugged program
'''
def f(x):
def g(y):
return y
return g(y)
a=5
b=1
h=f(a)
h(b)
'''
#Modified program
def f(x):
def g(y):
return y
return g
a=5
b=1
h=f(a)
print(h(b))
'''Explanation:-
In modified program,the function f(x) return the inner function reference.
Thus,h=f(a) is used to assign the g(inner func reference) to h and now it is act like function
So it accept argument and thus we can call and print the called output using print.
In debugged program,the function f(x) return the g(y) function.thus
h=f(a),its is used to store the returned value of f(x) which is nothing but inner function
so we cannot call it and also we are able to assign value for y.thus it shows error.
'''
| true |
6916c9af1c8908389fe6e3d4802c89dd1b8c1b1d | akhilnarang/CollegeStuff | /py/n_queen.py | 1,452 | 4.28125 | 4 | #!/usr/bin/env python3
n = int(input("Enter number of queens: "))
left_diagonal = [0] * (n ** 2)
right_diagonal = [0] * (n ** 2)
column = [0] * (n ** 2)
""" A recursive utility function to solve n
Queen problem """
def solve_recursive(board, column):
# If all of the queens have been placed already, its done
if column >= n:
return True
for i in range(n):
if (
left_diagonal[i - column + n - 1] != 1 and right_diagonal[i + column] != 1
) and column[i] != 1:
# Place this queen in board[i][column]
board[i][column] = 1
left_diagonal[i - column + n - 1] = right_diagonal[i + column] = column[
i
] = 1
# recur to place rest of the queens
if solve_recursive(board, column + 1):
return True
# If placing queen in board[i][column] doesn't lead to a solution, then remove queen from board[i][column]
board[i][column] = 0
left_diagonal[i - column + n - 1] = right_diagonal[i + column] = column[
i
] = 0
# If the queen cannot be placed in any row in this colum column then return False
return False
def solve():
if n < 4:
print(f"Solution for n < 4 doesn't exist!")
board = [[0 for _ in range(n)] for _ in range(n)]
solve_recursive(board, 0)
print(*board)
if __name__ == "__main__":
solve()
| true |
0adf188d84210f6cce00501f786c7d1077953a30 | akhilnarang/CollegeStuff | /py/preprocessing.py | 1,333 | 4.3125 | 4 | #!/usr/bin/env python3
def list_operations():
# List, mutable
x = [1, 2, 3, 4, 5]
print(x)
# Reverse
print(x[::-1])
x = [3, 4, 5, 2, 1]
# Sort
x.sort()
print(x)
# Slicing
print(x[1:5:2])
# List with different data types
y = [1, "two", 3, 4, "5"]
print(y)
# Append to a list
y.append("Test")
print(y)
# Nested lists
z = [1, [2, 3], 4]
print(z)
def dictionary_operations():
# Dictionary
d = {"name": "Akhil", "roll": 34, "class": "DWDM"}
d["attendance"] = 90.0
print(d.keys())
print(d.values())
print(d)
def tuple_operations():
# Tuple - immutable list
t = (1, 2, 3, 4, 5)
print(t)
def set_operations():
# Set - ordered list with no duplicates
s = {2, 1, 4, 5, 3, 5}
print(s)
# Duplicates will be ignored
s.add(2)
print(s)
# Check whether the elements are a part of the set
print(5 in s)
print(2 in s)
print(6 in s)
def string_operations():
paragraph = """Hello, this is the start of a paragraph. In this case, it will simply be a very long string. Consisting of many sentences.
And some newlines too.
"""
for s in paragraph.split("."):
print(s.strip())
def power(base, power):
return base ** power
def square(x):
return power(x, 2)
| true |
03b7d898147909ec33faa117fb29abd47397b27d | michedomingo/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 658 | 4.1875 | 4 | #!/usr/bin/python3
"""
This is the "5-text_indentation" module.
This module supplies one function - text_identation()
"""
def text_indentation(text):
"""
Prints a text with 2 new lines after characters . ? :
"""
if type(text) is not str:
raise TypeError('text must be a string')
new_line = text.replace('.', '.\n\n')
new_line = new_line.replace('?', '?\n\n')
new_line = new_line.replace(':', ':\n\n')
split_strings = new_line.split('\n')
for string in range(len(split_strings)):
print('{}'.format(split_strings[string].strip()),
end=('' if (string == (len(split_strings) - 1)) else '\n'))
| true |
111491c00b1679659941df641803ede9e752d521 | tranquilswan/Recursion | /Palindrome.py | 312 | 4.15625 | 4 | #check if a given word is a palindrome
def checkPalin(word):
if(len(word) <= 1):
print("YES SEY")
return True
elif(word[0] != word[len(word)-1]):
print("NO ON")
return False
else:
return checkPalin(word[1:-1])
word = input("enter a word:")
checkPalin(word) | false |
c59a158a1a609dbf97cfcc99d165fbb42d009923 | rodrigoclira/introducao-programacao | /turma20221/agenda.py | 1,615 | 4.3125 | 4 | #adicionar
#remover
#editar
#lista tudo
#procurar nome
menu ="""\nEscolha uma opção:
1 - Adicionar contato
2 - Remover contato
3 - Editar Contato
4 - Procurar Contato
5 - Lista Toda Agenda
6 - Sair
Opção:
"""
agenda = {}
while True:
op = int(input(menu))
print(op)
if op == 1:
nome = input("Informe o nome do contato: ")
numero = input(f"Informe o número de {nome}: ")
#{"pessoal": ...., "email": ...}
if nome not in agenda:
agenda[nome] = numero
print("Adicionado com sucesso!")
else:
print(f"{nome} já existe na agenda. Edite-o.")
elif op == 2:
nome = input("Informe o nome do contato: ")
if nome in agenda:
del agenda[nome]
print(f"{nome} removido da agenda")
else:
print(f"{nome} não está na agenda!")
elif op == 3:
nome = input("Informe o nome do contato: ")
if nome in agenda:
novo_numero = input("Informe o novo numero: ")
agenda[nome] = novo_numero
print(f"numero de {nome} atualizado!")
else:
print(f"{nome} não está na agenda!")
elif op == 4:
nome = input("Informe o nome do contato: ")
if nome in agenda:
print(f"O {nome} tem o número {numero}")
else:
print(f"{nome} não está na agenda!")
elif op == 5:
print ("Imprimindo toda a agenda..")
for pos, nome in enumerate(agenda):
print(f"{pos} - {nome} - {agenda[nome]}")
if op == 6:
break
| false |
3157f8a55dee320c47bd3da79324bb67a636e7e5 | rodrigoclira/introducao-programacao | /turma20221/while1.py | 215 | 4.125 | 4 |
quantidade = int(input("Quantidade de números: "))
cont = 1
num = 0
soma = 0
while cont <= quantidade:
#print(cont)
num = int(input(f"Informe o número ({cont}): "))
soma+=num
cont+=1
print(soma)
| false |
24846d4ea62a7e3662cdba9fb4d936e67eac5531 | mushgrant/dsi-MarshallGrant | /week-01/instructor-contributions/LA/week_01 DiceOdds Class Exercise.py | 2,832 | 4.28125 | 4 | '''
Question:
There are 36 possible combinations of two dice.
A simple pair of loops over range(6)+1 will enumerate all combinations.
The sum of the two dice is more interesting than the actual combination.
Create a dict of all combinations, using the sum of the two dice as the key.
Each value in the dict should be a list of tuples; each tuple has the value of two dice.
The general outline is something like the following:
Run the code in jupyter notebook or ipython in terminal (hint: "%paste" will copy
your clipboard directly into the terminal in ipython)
PSEUDO CODE:
dice_dict = {}
Loop with d1 from 1 to 6
Loop with d2 from 1 to 6
newTuple ← ( d1, d2 ) # create the tuple
oldList ← dictionary entry for sum d1+d2
newList ← oldList + newTuple
replace entry in dictionary with newList
Loop over all values in the dictionary
print the key and the length of the list
SAMPLE OUTPUT
#key: value == {1: [(0,1), (1,0)]}
A. Create the dictionary
B. Print the dictionary: values, keys, values and keys
C. BONUS: With the dictionary that you created (dice_dict),
create a new dictionary of dice combination and probabilities associated with each of these combinations.
The new dictionary should have have key: value == {1: 0.0556}
'''
dice_dict = {} #create empty dictionary
for d1 in range(1,7):
for d2 in range(1,7):
comboTuple = ( d1, d2 ) # create the tuple
key_sum = d1 + d2
if key_sum is not in dice_dict.keys():
dice_dict[key_sum] = comboTuple
else:
dice_dict[key_sum].append(comboTuple)
# SECTION A. CREATE THE DICTIONARY
#1. Creating dictionary you may have encountered a "KEY ERROR"
# Except to get an error for
dice_dict = {} #initialize
for d1 in range(1,7): #loops over value of first dice
for d2 in range (1,7): #loops over value of second dice
newTuple = (d1, d2)
key_sum = d1 + d2
dice_dict[key_sum].append(newTuple) #KEY ERROR for not initializing dict
#2. First elements, initializing variables are important
# Even dictionary and lists to create the final dictionary
dice_dict = {} #initialize
for d1 in range(1, 7): #loops over value of first dice
for d2 in range (1, 7): #loops over value of second dice
newTuple = (d1, d2)
key_sum = d1 + d2
if not key_sum in dice_dict:
dice_dict[key_sum] = [(newTuple)]
else:
dice_dict[key_sum].append(newTuple)
'''
SECTION B. After creating the dictionary, print out elements of the dictionary
'''
#print the dictionary keys in a loop
for keys in dice_dict.keys():
print keys
#print the dictionary values in a loop
for value in dice_dict.values():
print value
#print the dictionary values and in a loop
for key,value in dice_dict.iteritems():
print key,":",value
| true |
058fb75b2a747416fcf165bcc99b682a4feb7779 | GustavoGarciaPereira/Topicos-Avancados-em-Informatica-I | /exercicios_strings/exe8.py | 266 | 4.25 | 4 | '''
Ler uma string e um número inteiro, que representa o
número de caracteres. Eliminar n caracteres
do início da string e apresentar a string resultante.
'''
string = input('Informe uma palavra: ')
num = int(input('Informe um numero: '))
print(string[:num]) | false |
66e0c14288d0c5f34c0b7c6b6e5b15329c683e92 | CharlesAtchison/telco_churn_project | /evaluate.py | 2,535 | 4.34375 | 4 | import pandas as pd
def replace_obj_cols(daf: pd.DataFrame, dropna=False) -> (pd.DataFrame, dict, dict):
'''Takes a DataFrame and will return a DataFrame that has
all objects replaced with int values and the respective keys are return
and a revert key is also generated.
Parameters
----------
df : pandas DataFrame
Will take all object/str based column data types and convert their values
to integers to be input into a ML algorithm.
dropna: bool
If this is True, it will drop all rows with any column that has NaN
Returns
-------
DataFrame
The returned DataFrame has all the str/object values replaced with integers
dict - replace_key
The returned replace_key shows what values replaced what str
dict - revert_key
The returned revert_key allows it to be put into a df.replace(revert_key)
to put all the original values back into the DataFrame
Example
-------
>>>dt = {'Sex':['male', 'female', 'female', 'male', 'male'],
'Room':['math', 'math', 'gym', 'gym', 'reading'],
'Age':[11, 29, 15, 16, 14]}
>>>test = pd.DataFrame(data=dt)
>>>test, rk, revk = replace_obj_cols(test)
Sex Room Age
0 0 0 11
1 1 0 29
2 1 1 15
3 0 1 16
4 0 2 14,
{'Sex': {'male': 0, 'female': 1},
'Room': {'math': 0, 'gym': 1, 'reading': 2}},
{'Sex': {0: 'male', 1: 'female'},
'Room': {0: 'math', 1: 'gym', 2: 'reading'}}
>>>test.replace(revk, inplace=True)
Sex Room Age
0 male math 11
1 female math 29
2 female gym 15
3 male gym 16
4 male reading 14
'''
# Copy DataFrame so it doesn't alter inital DataFrame
df = daf.copy(deep=True)
# Set replace and revert keys
replace_key = {}
revert_key = {}
# Fetch all column names
col_names = df.select_dtypes('object').columns
if dropna:
df.dropna(inplace=True)
for col in col_names:
uniques = list(df[col].unique())
temp_dict = {}
rev_dict = {}
for each_att in uniques:
temp_dict[each_att] = uniques.index(each_att)
rev_dict[uniques.index(each_att)] = each_att
replace_key[col] = temp_dict
revert_key[col] = rev_dict
df.replace(replace_key, inplace=True)
return df, replace_key, revert_key | true |
6a14ea067e367c83406bbd7a6fbbeaa642450eca | emaillalkrishna/05may2019_Python_Practical_Examples_prepaired_by_LK | /2.Collections/1.List/2.Problems/3. Print_FirstHalf_from_left_to_rght_and_secondHalf_from_right_to_left.py | 1,814 | 4.59375 | 5 | # # # # Python program to print
# # # The first half from left to right
# # # The second half from right to left
# # # -----------------------------------Method 1 --------------------------------
my_list = [5, 4, 6, 2, 1, 3, 8, 9, 7]
my_list_length = len(my_list)
# printing first half in ascending order
print("first half in ascending order")
i = 0
while i < (my_list_length / 2):
print(my_list[i])
i = i + 1
# printing second half in descending order
print("second half in descending order")
j = my_list_length - 1
while j >= my_list_length / 2:
print(my_list[j])
j = j - 1
# # # --------------------------Same with in a function
# def printOrder(my_list, n):
# # sorting the array
# my_list.sort()
#
# # printing first half in ascending order
# print("Printing the first half from left to right")
# i = 0
# while (i < (n / 2)):
# print(my_list[i])
# i = i + 1
#
# # printing second half in descending order
# print("Printing the second half from right to left")
# j = n - 1
# while j >= n / 2:
# print(my_list[j])
# j = j - 1
#
#
# my_list = [5, 4, 6, 2, 1, 3, 8, 9, 7]
# n = len(my_list)
# printOrder(my_list, n)
# # # ----------------------------------------Method 2 ------------------------------------------
# def printOrder(arr, n):
# # sorting the array
# arr.sort()
#
# # printing first half in ascending order
# for i in range(n // 2):
# print(arr[i], end=" ")
#
# # printing second half in descending order
# for j in range(n - 1, n // 2 - 1, -1):
# print(arr[j], end=" ")
#
# # Driver code
# if __name__ == "__main__":
# arr = [5, 4, 6, 2, 1, 3, 8, 9]
# n = len(arr)
# printOrder(arr, n)
| true |
f771a97351f68439fbaef16348de3feaac9cac3a | emaillalkrishna/05may2019_Python_Practical_Examples_prepaired_by_LK | /1.Variables/1.Numbers/2.Practical Questions and Answers/1.Check_whether_the_input_number_is_Even_or_Odd.py | 391 | 4.34375 | 4 | # # # Case 1: Numbers → Check whether the input number is Even or Odd
# # # Method 1
# num = int(input("Enter a number: "))
# if num % 2 == 0:
# print("This is an even number")
# else:
# print("This is an odd number")
#
# # # Method 2
# num = int(input("Enter a number: "))
# if (num % 2) == 0:
# print("{} is Even".format(num))
# else:
# print("{} is Odd".format(num))
| true |
9f647a5d2b779f8fe878d753172998dbbcdd524c | emaillalkrishna/05may2019_Python_Practical_Examples_prepaired_by_LK | /1.Variables/1.Numbers/2.Practical Questions and Answers/3.check_various_conditions.py | 1,487 | 4.59375 | 5 | # # # Question 3 : Numbers →
# # # Write a python program to
# # # accept three numbers from a user and identify and print the greatest among them,
# # # If the first number is the greatest value then check whether it is even or odd
# # # If it is even, check that the number is greater than 10 or not
# # # If it is odd check that the number is less than 20 or not
#
# num1 = float(input(" Please Enter the First number: "))
# num2 = float(input(" Please Enter the Second number: "))
# num3 = float(input(" Please Enter the third number: "))
#
# if (num1 > num2) and (num1 > num3):
# print("The largest number among the three numbers ", num1)
#
# if num1 % 2 == 0:
# print(num1, "This is an even number")
#
# if num1 > 10:
# print(num1, "is greater than 10")
#
# elif num1 < 10:
# print(num1, "is less than 10")
#
# else:
# print(num1, "is equals to 10")
#
# else:
# print(num1, "This is an odd number")
#
# if num1 < 20:
# print(num1, "is less than 20")
#
# elif num1 > 20:
# print(num1, "is greater than 20")
#
# else:
# print(num1, "is equals to 20")
#
# elif (num2 > num1) and (num2 > num3):
# print("The largest number among the three numbers ", num2)
#
# elif (num3 > num1) and (num3 > num2):
# print("The largest number among the three numbers ", num3)
#
# else:
# print("All the three numbers are equal")
| true |
8d7b72041ec1069aaf1fde67faf23998531449c9 | amarti5/Python-Projects | /Guess The Number.py | 1,251 | 4.28125 | 4 | import random
print "Hello, welcome to Guess The Number!\n\n"
# You must use a for loop in order for the user to guess the number in 3 tries.
print "As the title suggest, a number between 1-10 is generated and you must guess what it is in 3 tries.\n\n"
while True:
choice = raw_input("Do you want to play?(y/n): ", )
if choice not in ('y', 'n'):
print "Please enter in a valid choice: \n",
continue
elif choice == 'y':
print "Enter your name:"
name = raw_input()
break
elif choice == 'n':
print "I understand, well have a great day!"
break
while choice == "y":
min = 1
max = 10
guess = random.randint(min, max)
# This is where for loops comes in
for i in range(1,4):
print "\nTry # %d \n" % i
guess_1 = int(raw_input("Enter in your guess: "))
if guess_1 == guess:
print "That is the right number %s!" % name
break
elif guess_1 > guess:
print "You are high.\n"
elif guess_1 < guess:
print "You are low.\n"
else:
continue
print guess
choice = raw_input("Do you want to play again?(y/n): ",)
if choice not in ('y', 'n'):
print "That is not a valid input. \nPlease enter 'y' or 'n': ",
continue
elif choice == 'y' or 'n':
print "Thank you for playing!"
continue | true |
0885d9eafc40c6adac4ed201207ef7f445f168af | Vizzyy/euler-problems | /p20.py | 712 | 4.28125 | 4 | #
#
# n! means n × (n − 1) × ... × 3 × 2 × 1
#
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#
# Find the sum of the digits in the number 100!
import datetime
start = datetime.datetime.now()
print(start)
def factorial(number):
result = number
for i in range(1, int(number)):
result *= (number - i)
return result
factorial_result = factorial(100)
factorial_digits = [int(digit) for digit in str(factorial_result)]
print(factorial_result)
print(factorial_digits)
print(f"sum of digits: {sum(factorial_digits)}")
print(f"FINISHED")
end = datetime.datetime.now() - start
print(end)
| true |
fb5dc97df639a4fef3a6f981bc2b78018c74e68f | Vizzyy/euler-problems | /p4.py | 736 | 4.21875 | 4 | #
#
# A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
def is_palindrome(input):
string_input = str(input)
start_ptr = 0
end_ptr = len(string_input) - 1
while start_ptr <= end_ptr:
if string_input[start_ptr] is not string_input[end_ptr]:
return False
else:
start_ptr += 1
end_ptr -= 1
return True
largest = 0
for x in range(1, 999):
for y in range(1, 999):
mult = x * y
if is_palindrome(mult):
if mult > largest:
largest = mult
print(largest)
| true |
8452b72aef8728e1f12aba964bb6ee00c0ba408a | justinjoco/coding_interview_practice | /group_shifted_strings.py | 1,360 | 4.15625 | 4 | """
Group Shifted Strings
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
Example:
Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
Time complexity: O(nk) ; n = num of strings, k = max length of string
Memory complexity: O(k)
Algorithm:
For each each string
Get the circular differences between each adjacent character in string
Map tuple of the circular differences to a list of strings
Return the map's values
"""
from collections import defaultdict
class Solution:
def groupStrings(self, strings: List[str]) -> List[List[str]]:
map = defaultdict(list)
for string in strings:
if len(string) <=1:
map[(27)].append(string)
else:
diffs = []
for i in range(len(string)-1):
diff = (ord(string[i]) - ord(string[i+1])) %26
diffs.append(diff)
map[tuple(diffs)].append(string)
return list(map.values()) | true |
c99c87b8ddf2542ef3f98ff4ab71c4e0ba56a97f | Abu-Sayad-Hussain/visual-studio-projects | /loanCalculator.py | 1,038 | 4.4375 | 4 | # initializing the variables
monthlyPayment = 0
loanAmount = 0
interestRate = 0
loanDurationInYear = 0
numberOfPayments = 0
# Asking the user to provide necessary information to calculate monthly payment
strLoanAmount = input("Enter the loan you want to borrow- \n")
strInterestRate = input("Enter the interest rate you have to give- \n")
strLoanDurationInYear = input("Enter how many years later you'll back the loan- \n")
# Converting string values to float values
loanAmount = float(strLoanAmount)
interestRate = float(strInterestRate)
loanDurationInYear = float(strLoanDurationInYear)
# monthly payment will be once in a month so number of payments in a year will be multipy by 12
numberOfPayments = loanDurationInYear*12
# Calculate monthly payment based on the formula
monthlyPayment = loanAmount * interestRate * (1+interestRate) * numberOfPayments \
/ ((1+interestRate) * numberOfPayments -1)
# Printing the result to the user
print("\n your monthly payment will be %.2f " % monthlyPayment)
| true |
a36d13b2e19b2847f0deabad61a528a93373d6c5 | danielsunzhongyuan/project_euler | /longest_collatz_sequence_14.py | 1,345 | 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?
'''
import math
import time
def term(x, length=0): # it uses about 41 seconds
if x == 1:
length += 1
return length
if x % 2 == 0:
length += 1
return term(x/2, length)
else:
length += 1
return term(3*x + 1, length)
def collatz(x): # it uses about 24 seconds
count = 1
while x>1:
count += 1
if x % 2 == 0:
x /= 2
else:
x = x * 3 + 1
return count
def main():
print collatz(13)
start = time.time()
max_chain = [0, 0]
for i in range(10, 1000000):
tmp = collatz(i)
if tmp > max_chain[1]:
max_chain = [i, tmp]
print max_chain
print "It costs:", time.time() - start, "seconds."
if __name__ == "__main__":
main()
| true |
2f4e1cf253a244b199f07af3978671161e98205f | danielsunzhongyuan/project_euler | /spiral_primes_58.py | 1,815 | 4.3125 | 4 | '''
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ~ 62%.
8 = count(3, 5, 7, 17, 31, 37, 43)
13 = count(1, 3, 5, 7, 9, 13, 17, 21, 25, 31, 37, 43, 49)
If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
'''
import math
import time
import profile
def is_prime(n):
if n < 2: return False
if n == 2 or n == 3: return True
for i in xrange(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def main():
'''sss'''
start = time.time()
print __doc__
odd_squares_count = 1
prime_count = 0
spiral_length = 1
while True:
spiral_length += 2
odd_squares_count += 4
squares = [spiral_length * spiral_length - (spiral_length - 1), spiral_length * spiral_length - (spiral_length - 1) * 2, spiral_length * spiral_length - (spiral_length - 1) * 3]
for square in squares:
if is_prime(square):
prime_count += 1
ratio = 1.0 * prime_count / odd_squares_count
if ratio < 0.1:
print spiral_length, ratio
break
print "It costs:", time.time() - start, "seconds"
if __name__ == "__main__":
profile.run("main()")
| true |
f0d3318691f262e6761277c04272a6493005e211 | NYCGithub/LC | /binarySearch.py | 2,887 | 4.125 | 4 | def binarySearch(nums, target):
"""
Invariant is that the target aleays exists inside [start,end-1] ( same as [start,end), right exclusive )
Initial condition is therefore: start = 0, end = len(nums)
If start == end, then there's no element left.
"""
start,end=0,len(nums)
while (start < end):
mid = start + (end - start) // 2 #Treat mid as offset from start, not absolute index.
if nums[mid] == target:
return mid
elif nums[mid] > target:
end = mid #Don't do mid-1 because end is right exclusive.
else:
start = mid+1
return None
def searchLeftBoundary(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
Time O(log N)
Space: O(1)
In ascending array, find the position of the last element that's < target OR first element that's = target.
This is the left boundary
"""
start, end = 0, len(nums)
while start < end:
mid = start + (end - start) // 2
if target <= nums[mid]:
end = mid
elif target > nums[mid]:
start = mid + 1
return start
def searchRightBoundary(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
Time O(log N)
Space: O(1)
In ascending array, find the position of the first element that's > target OR last element that's = target.
This is the RIGHT boundary.
"""
start, end = 0, len(nums)
while start < end:
mid = start + (end - start) // 2
if target >= nums[mid]:
start = mid + 1
elif target < nums[mid]:
end = mid
return start
print (searchLeftBoundary([1,3,3,3,5,7],4))
print (searchLeftBoundary([1,3,3,3,5,7],3))
print (searchLeftBoundary([3],3))
print (searchLeftBoundary([2],3))
print (searchLeftBoundary([4],3))
print (searchRightBoundary([1,3,3,3,5,7],4))
print (searchRightBoundary([1,3,3,3,5,7],3))
print (searchRightBoundary([3],3))
print (searchRightBoundary([2],3))
print (searchRightBoundary([4],3))
print (searchRightBoundary([],3))
# [1,3,3,3,5,7], target = 4 will return 1 (2nd element)
# [1,3,3,3,5,7], target = 3 will return 1 (2nd element)
# [3], target = 3 will return 0 (1st element)
# [2], target = 3 will return 0 (1st element)
# [4], target = 3 will return 1 (an out of bound element, as such a boundary does not exist)
#
# s=[1,2,3,4,5,6,7]
# print (binarySearch(0,len(s)-1,s,5))
# s=[1,2,3,4,5]
# print (binarySearch(0,len(s)-1,s,5))
# s=[1,5,1]
# print (binarySearch(0,len(s)-1,s,5))
# s=[5]
# print (binarySearch(0,len(s)-1,s,5))
# s=[5,1]
# print (binarySearch(0,len(s)-1,s,5))
# s=[1,5]
# print (binarySearch(0,len(s)-1,s,5))
#
# s=[1,2,3]
# print (binarySearch(0,len(s)-1,s,5))
# s=[1]
# print (binarySearch(0,len(s)-1,s,5))
# s=[]
# print (binarySearch(0,len(s)-1,s,5)) | true |
580167faf6deff1b337ef858d7f04b173494d694 | skwirowski/algorithms | /Python/01_selection_sort.py | 1,256 | 4.5 | 4 | from helpers import create_array_of_random_numbers
example_array = create_array_of_random_numbers(5)
def find_smallest_element(array):
""" Finds smallest element in the given array
Args:
array: array of numbers
Returns:
index of the smallest element from the array
"""
smallest = array[0] # holds the smallest value
smallest_index = 0 # holds index of the smallest value
for i in range(1, len(array)):
if array[i] < smallest:
smallest = array[i]
smallest_index = i
return smallest_index
def selection_sort(array):
""" Sorts array of numbers
Args:
array: array of numbers
Retruns:
sorted array of numbers
"""
auxiliary_array = []
for _ in range(len(array)):
# finds index of the smallest element in an array
smallest = find_smallest_element(array)
# removes the smallest element from the array and appends it to the end of auxiliary_array
auxiliary_array.append(array.pop(smallest))
return auxiliary_array
print("SELECTION SORT ALGORITHM")
print("Example unsorted array of numbers: ", example_array)
print("Sorted array of numbers: ", selection_sort(example_array))
| true |
dd7c465c2046ac131450b5c6beab3d1842f2e3d5 | laughouw10/stanCode | /complement.py | 908 | 4.53125 | 5 | """
File: complement.py
----------------------------
This program uses string manipulation to
tackle a real world problem - finding the
complement strand of a DNA sequence.
THe program asks uses for a DNA sequence as
a python string that is case-insensitive.
Your job is to output the complement of it.
"""
def main():
"""
TODO:
input DNA sequence
output the complement of the entered DNA sequence
"""
build_complement()
pass
def build_complement():
k = input("please enter: ")
k = k.upper() # case-insensitive
ans = ""
for i in range(len(k)): # match the DNA sequence
if k[i] == "A":
ans += "T"
if k[i] == "T":
ans += "A"
if k[i] == "G":
ans += "C"
if k[i] == "C":
ans += "G"
print(ans)
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == '__main__':
main()
| true |
a86edbe944bd469c1f9e997924dd10d9f8636986 | Nathansbud/PythonNonsense | /Misc/dict_flip.py | 219 | 4.125 | 4 | def flip(d):
flipped = {}
for elem in d:
if d[elem] not in flipped: flipped[d[elem]] = [elem]
else: flipped[d[elem]].append(elem)
return flipped
print(flip({"a":"b", "b":"b", 1:"b", 2:"b"})) | true |
86ccef42367301c8d76a91ff1a861607a91bc62d | WillNetsky/dsp | /python/markov.py | 2,236 | 4.40625 | 4 | #!/usr/bin/env python
# Write a Markov text generator, [markov.py](python/markov.py). Your program should be called from the
# command line with two arguments: the name of a file containing text to read, and the number of words
# to generate. For example, if `chains.txt` contains the short story by Frigyes Karinthy, we could run:
# ```bash
# ./markov.py chains.txt 40
# ```
# A possible output would be:
# > show himself once more than the universe and what I often catch myself playing our well-connected game
# went on. Our friend was absolutely correct: nobody from the group needed this way. We never been as the
# Earth has the network of eternity.
# There are design choices to make; feel free to experiment and shape the program as you see fit.
# Jeff Atwood's [Markov and You](http://blog.codinghorror.com/markov-and-you/) is a fun place to get started
# learning about what you're trying to make.
import sys
import random
import string
def build_markov_dict(filename):
d = {}
f = open(filename)
for line in f:
line = line.translate(string.maketrans("",""),string.punctuation).split()
if len(line) < 3: continue
for i in range(len(line)-3):
tupkey = (line[i], line[i+1])
try:
d[tupkey].append(line[i+2])
except KeyError:
d[tupkey] = list()
d[tupkey].append(line[i+2])
return d
def generate_markov_text(d, words):
prefix = random.choice(list(d.keys()))
result = prefix[0] + " " + prefix[1] + " "
while len(result.split()) < words:
try:
d[prefix]
except KeyError:
prefix = random.choice(list(d.keys()))
result += prefix[0] + " " + prefix[1] + " "
word = random.choice(d[prefix])
result += word + " "
prefix = new_prefix(prefix, word)
print(result)
def new_prefix(prefix, word):
return (prefix[1], word)
def main(argv):
markov = build_markov_dict(argv[1])
generate_markov_text(markov, argv[2])
if __name__ == '__main__':
try:
sys.argv[2] = int(sys.argv[2])
except IndexError:
print('Usage: markov.py <input file> <# words to generate>')
sys.exit(1)
main(sys.argv)
| true |
9cb0114c821cf1ac00b5b70c67d03d834db81403 | 2862120466/MyCode | /List and Tuples/List/ListOperations.py | 603 | 4.46875 | 4 | # 修改列表:给元素赋值
print()
x = [1,2,3]
x[1] = 4
print(x[1])
# 删除元素
print()
names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
del names[2] #从列表中删除元素也很容易,只需使用del语句即可
print(names[:])
#给切片赋值
print()
name = list('Perl')
print(name)
name[2:] = list('ar')
print(name)
name[1:] = list('ython') #通过使用切片赋值,可将切片替换为长度与其不同的序列。
print(name)
print()
numbers = [1,5] #使用切片赋值还可在不替换原有元素的情况下插入新元素
numbers[1:1] = [2,3,4]
print(numbers)
| false |
5c6a634bbed4a7510e2dc58a80d1e0c7096b6a14 | YaninaLili/practica2 | /ejercicio1.py | 346 | 4.1875 | 4 |
import math
print("Ingresar coordenada ")
x=float(input("Ingrese coordenada en X"))
y=float(input("Ingrese coordenada en Y"))
distancia=(x-y)
if distancia<0:
distancia=distancia*(-1)
dis0=math.sqrt(x**2+y**2)
print()
print("la distancia entre ambos puntos es: ",distancia)
print("la distancia de la coordenada al punto 0,0 es:",dis0)
| false |
3de400ff1c34c028ffc169374be0d8930cc8852f | adamayd/Python | /Learn_To_Program_w_Python/stringfunctionexam1.py | 355 | 4.3125 | 4 | # Allow user to enter string
user_string = str(input("Enter a string: "))
# Clear out extra white space
user_string = user_string.strip()
# Create list of words
words_list = user_string.split()
# Convert String to Acronym
acronym_string = ""
for i in words_list:
acronym_string += i[0]
# Print Acronym in Uppercase
print(acronym_string.upper())
| true |
c1940823418fe092d746b84c866d29bec7f28984 | snehapatil1/100-days-of-code | /Code Files/factorial.py | 441 | 4.25 | 4 | def factorial(a):
fact = 1
for i in range(1, a+1):
fact = fact*i
return(fact)
n = int(input("Please enter the number: \n"))
print(f"Factorial of {n} is {factorial(n)}")
print("===========================")
print("Finding factorial using recursion")
def rec_fact(b):
if b == 1:
return b
else:
return b*rec_fact(b-1)
c = int(input(f"Please enter the number: \n"))
print(f"Factorial of {c} using recurssion is {rec_fact(c)}") | true |
8b73eeac4601b5f337399a630968b11a29b784b7 | manmohitgrewal1/CS50X | /pset6:Python/mario/more/mario.py | 409 | 4.15625 | 4 | from cs50 import get_int
# take user input
while True:
height= get_int("Height: ")
if height>0:
break
# making hash figure using nested for loop
for row in range (1, height+1):
for spc in range (0, height-row):
print(" ", end="")
for col in range (0, row):
print("#", end="")
print(" ", end="")
for col2 in range (0, row):
print("#",end="")
print() | true |
5766d929069ab8a6b7497ab692a095cea020b5fd | stephenkyle/PythonProjects | /OakfordStephenM06_Ch6_Ex6+9.py | 1,129 | 4.3125 | 4 | # This program takes numbers from the file
# numbers.txt and calculates the average of all
# the numbers stored on the file
# The main function
def main():
try:
# Open the file to get the numbers
file = open('numbers.txt', 'r')
# Intitialize accumulator
total = 0
lineNumber = 0
info = file.readline()
while info != "":
# Add to the amount of numbers for each pass
lineNumber += 1
# Read the values from the file
# and accumulate them
total += int(info)
info = file.readline()
# Calculate average by taking total divided
# amount of numbers
average = total/lineNumber
except IOError:
print('An error occured trying to read the file.')
except ValueError:
print('Non-numeric data found in this file.')
else:
# Print the average
print('The average is', average)
# Close the file
file.close()
# Call the main function
main()
print('Stephen Oakford')
| true |
7ededf6ff994be449d98f509a4d9ae25e5a9394c | stephenkyle/PythonProjects | /OakfordStephenM05_Ch5_Ex2.py | 1,747 | 4.21875 | 4 | # This program calculates total cost of item with
# state and county taxes.
# Named constants fot taxes
stateSalesTaxAmount = 0.05
countySalesTaxAmount = 0.025
# The main function
def main():
# Get the user's amount of purchase
amount = float(input('What is the amount of the purchase? '))
# Call calculate state tax function
stateTax = calculate_stateTax(amount)
#Call calculate county tax function
countyTax = calculate_countyTax(amount)
#Call calculate total tax function
totalTax = calculate_totalTax(stateTax, countyTax)
#Call calulate total function
total = calculate_total(amount, totalTax)
# Call output_total function
output_total(amount, stateTax, countyTax, totalTax, total)
def calculate_stateTax(amount):
# Calculate state taxes
return amount*stateSalesTaxAmount
# Calculate county taxes
def calculate_countyTax(amount):
return amount*countySalesTaxAmount
# Calculate total amount of taxes
def calculate_totalTax(stateTax, countyTax):
return stateTax+countyTax
# Calculate total cost with taxes added
def calculate_total(amount,totalTax):
return amount+totalTax
# The output_total function displays the total with taxes
def output_total(amount, stateTax, countyTax, totalTax, total):
print('Amount of purchase\t $',format(amount, '.2f'), sep='')
print('State Sales Tax\t\t $',format(stateTax, '.2f'), sep='')
print('County Sales Tax\t $',format(countyTax, '.2f'), sep='')
print('Total Sales Tax\t\t $',format(totalTax, '.2f'), sep='')
print('Total Amount\t\t $',format(total, '.2f'), sep='')
# Call the main function
main()
print('Stephen Oakford')
| true |
3d4819f91254252d74ef9ced5a73e423f30c3da9 | intelliflovrk/SpareTime | /pat/utils/dictionary/dict.py | 1,601 | 4.125 | 4 | import json
print("Select any food item to pick up where it is stored apple, banana, berry, milk, kiwi, coffee,jam")
user_value_1 = input("Provide a vaule from the above list of food items, it will print the correct key associated: ").lower()
def general_dict(find_value_1):
''' This Funcation will return the key aginst the value given from the preset dictionary '''
dictionary = {"item1": "apple", "item2": "banana", "item3": "berry", "item4": "milk", "item5": "kiwi", "item6": "coffee", "item7": "jam"}
with open('food.json', 'w') as json_file:
json.dump(dictionary, json_file)
print("JSON file saved on local to use")
for key, value in dictionary.items():
if food == find_value_1:
print("User entered " + find_value_1, "it's stored in " + key)
break
else:
print("Something went wrong")
# Function called for testing
general_dict(user_value_1)
user_value = input("Provide a vaule from the above list of food items, it will print the correct key associated: ").lower()
#Below load_json will get the item from food.json file and display the key against the value entered
def load_json(find_value):
''' This Funcation will return the key aginst the value given from the json file it's loaded '''
with open('food.json') as file:
data_store = json.load(file)
for key, value in data_store.items():
if value == find_value:
print("User entered " + find_value, " it's stored in " + key)
break
else:
print("You entered something wrong")
load_json(user_value)
| true |
bc295f2ba2565e3f2b5edbfab2bdad3b33d00ae3 | metalpizza123/UniversityWorkPython | /TPOP PRAC 2/SPPPPPPPPEEEEEEEEED.py | 369 | 4.1875 | 4 | initiald=float(input('What speed was teh vehicle at? '))
itsdapolice=int(input('What is the speed limit here?'))
if initiald>=90:
print ('Fine that boi 300 pounds')
elif initiald<=itsdapolice:
print ("He's/She's/It's/They are below the speed limit.")
else :
overthelimit=int(initiald-itsdapolice)
fine=overthelimit*5
print("Fine the driver $",fine)
| true |
f050e6046663dfdaf88a87aa80f1b9e707ede52b | metalpizza123/UniversityWorkPython | /TPOP PRAC 2/3 number sort.py | 1,132 | 4.28125 | 4 | firstnumber=int(input('Please enter the first number '))
secondnumber=int(input('Please enter the second number '))
thirdnumber=int(input('Please enter the third number '))
statement="the largest number is"
#print (type(firstnumber))
#if (type(firstnumber)!=int or type(secondnumber)!=int or type(thirdnumber)!=int):
# print ('integer numbers only PLEEEEEEASE')
else:
if firstnumber==secondnumber:
if firstnumber==thirdnumber:
print('there is no largest number')
elif firstnumber<thirdnumber:
print (statement,thirdnumber)
else:
print (statement,firstnumber)
elif firstnumber>secondnumber:
if firstnumber==thirdnumber:
print (statement,firstnumber)
elif firstnumber>thirdnumber:
print (statement,firstnumber)
else:
print(statement,thirdnumber)
else:
if secondnumber==thirdnumber:
print (statement,secondnumber)
elif secondnumber>thirdnumber:
print (statement,secondnumber)
else:
print (statement,thirdnumber)
| true |
556020cc044ca00d58e87422a52a1131ad7e85a3 | Leslie-Fang/python_asyncio | /main2.py | 940 | 4.125 | 4 | import asyncio
import time
async def do_some_work(x):
'''
with the async directivate, we would define a coroutine
when call this function, it would not be implemented, but return a coroutine object
the coroutine object need to be registered into the loop
'''
print('Waiting: ', x)
if __name__ == "__main__":
print("Hello world!")
now = lambda : time.time()
start = now()
#create a coroutine object
coroutine = do_some_work(2)
#create a loop
loop = asyncio.get_event_loop()
#use the coroutine object to create a task
#asyncio.ensure_future(coroutine) and loop.create_task(coroutine), both could be used to create the task
task =loop.create_task(coroutine)
print(task)#should be pending state
#add the coroutine object into the loop, and start the loop
loop.run_until_complete(task)
print(task) # should be finished state
print('TIME: ', now() - start)
| true |
972cbede637634e62a6365c3a16422a09515afd4 | valievav/python-design-patterns | /factory/factory.py | 914 | 4.21875 | 4 | from math import cos, sin
class Point:
"""
Use PointFactory for cartesian or polar coordinates.
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return f"1st coordinate: {self.x}, 2nd coordinate: {self.y}"
# create separate class with methods for initialization
class PointFactory:
@staticmethod # not necessarily static (if Factory holds some state)
def new_cartesian_point(x, y): # x, y explicit naming for cartesian coordinates
return Point(x, y)
@staticmethod
def new_polar_point(rho, theta): # rho, theta explicit naming for polar coordinates
return Point(rho * cos(theta), rho * sin(theta))
# discoverability is a question here, better to specify that Point factory exists in Point desc
pf = PointFactory()
p1 = pf.new_cartesian_point(2,3)
p2 = pf.new_polar_point(2,3)
print(p1, p2, sep='\n')
| true |
305877b59ce00e95a3dd63f9ce5e7a9b55e12b52 | Pieterjaninfo/TicTacToe | /src/sortingalgorithms.py | 1,857 | 4.21875 | 4 | # Implementing sorting algorithms using pseudo code from Wikipedia
# Simple sort: Insertion sort, Selection sort
# Efficient sort: Merge sort, Heapsort, Quicksort
# Bubble sort and variants: Bubble sort, Shellsort, Comb sort
# Distribution sort: Counting sort, Bucket sort, Radix sort
array = [5, 4, 8, 7, 9, 0, 1, 3, 6, 2]
# Insertion sort
def insertion_sort(a):
for i in range(1, len(a)):
j = i
while j > 0 and a[j - 1] > a[j]:
a[j], a[j - 1] = a[j - 1], a[j]
j -= 1
return a
def insertion_sort_faster(a):
for i in range(1, len(a)):
x = a[i]
j = i - 1
while j >= 0 and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
return a
# Selection sort
def selection_sort(a):
n = len(a)
for j in range(0, n - 1):
i_min = j
for i in range(j + 1, n):
if a[i] < a[i_min]:
i_min = i
if i_min != j:
a[j], a[i_min] = a[i_min], a[j]
return a
# Merge sort
def merge_sort(m):
if len(m) <= 1:
return m
left = []
right = []
for i, x in enumerate(m):
if i <= len(m)//2:
left.append(x)
else:
right.append(x)
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
def merge(left, right):
result = []
while left and right:
if left[0] <= right[0]:
result.append(left[0])
left.pop(0)
else:
result.append(right[0])
right.pop(0)
while left:
result.append(left[0])
left.pop(0)
while right:
result.append(right[0])
right.pop(0)
return result
# print(insertion_sort(array))
# print(insertion_sort_faster(array))
# print(selection_sort(array))
# print(merge_sort(array)) | false |
2fadc0fe450d671c36086fc6f4384764359f1227 | Icantthinkofanything1/HW070172 | /L03/Exercise9.py | 340 | 4.34375 | 4 | #convert.py
#An algorithm to convert Fahrenheit temps into Celsius
def main():
print("This program converts the temperature from ")
print("Fahrenheit into Celsius")
fahrenheit = eval(input("What is the temperature in Fahrenheit "))
celsius = ((fahrenheit - 32) * 5)/9
print("The temperature is", celsius, "degrees Celsius.")
main() | true |
0ee9ef43e93fcac93399e260d0c6da9ecf06def8 | flaviasilvaa/ProgramPython | /78.CompareNumbersList.py | 1,103 | 4.34375 | 4 | ##this program is going to read 5 numbers in a list and then compare the smallest and the biggest number
listnum = []
small = big = 0
for c in range(0, 5):
listnum.append(int(input(f"type a number for position {c}\n")))
if c == 0:
small = big = listnum[c] ##I don't know which one is the smallest or the biggest
else:
if listnum[c] > big: ##checking the biggest value
big = listnum[c]
if listnum[c] < small: ##checking for the smallest value
small = listnum[c]
print('-=' * 30)
print(f'you typed the numbers{listnum}')
print(f'The biggest number is {big} in the position', end=' ')
##I need to swipe my whole list to check the position of the biggest and smallest
for i, v in enumerate(listnum):#I have the indice and value
if v == big:
print(f'{i}...', end= ' ')# is going to check the position of the biggest number
print()
print(f' The smallest number is {small} in the position', end=' ')
for i, v in enumerate(listnum): ##I can use the same 'variable' i and v
if v == small:
print(f'{i}...', end=' ')
print()
| true |
ec5d0a78818bbc7d3d2e7c822f7540ce362fe430 | flaviasilvaa/ProgramPython | /60.Factorial.py | 500 | 4.34375 | 4 | # this program is going to read a number and show the factorial
from math import factorial
number = int(input('Enter a number to be factored?\n'))
f = factorial(number)
print(f'The factorial of {number}! is {f}')
###another way####
number = int(input('Enter a number to be factored?\n'))
count = number
f = 1
print(f'Calculating {number} ! =', end= ' ')
while count > 0:
print(f'{count}', end= ' ')
print('x' if count > 1 else ' = ', end= '')
f *= count
count -= 1
print(f'{f}')
| true |
912fc9e7b7f1c536105d59105bfca25dffcf9f4d | flaviasilvaa/ProgramPython | /76.PriceList.py | 975 | 4.3125 | 4 | ##this program is going to show a price list using tuple
school_list = ('Pen', 2,
'Notebook', 5.45,
'Book', 15.87,
'Pencil', 3.23,
'Ruler', 1,
'Backpack', 30.43,
'eraser', .45,
'Pencil Case', 3.12,)
print('-'*40)
print("""
_ _ _ _
| | | | | |(_) _
___ ____| |__ ___ ___ | | | | _ ___ _| |_
/___)/ ___) _ \ / _ \ / _ \| | | || |/___|_ _)
|___ ( (___| | | | |_| | |_| | | | || |___ | | |_
(___/ \____)_| |_|\___/ \___/ \_) \_)_(___/ \__)
""")
print('-'*40)
for position in range(0, len(school_list)):##it is going to go until the size of the list
if position % 2 == 0: # that means is in the left it is the name of the product
print(f'{school_list[position]:.<30}', end= ' ')
else:
print(f'{school_list[position]:>7.2f} Euros')
print('-'*40)
| false |
22f816acfb596128f93e7703e87065b2716eb9fb | flaviasilvaa/ProgramPython | /CalculatingAmountPaint.py | 711 | 4.46875 | 4 | ##this program is going to get the wall information such height and width to calculate the amount of paint needed to paint the wall
print("""
___
,--[___]--,
/ \
|,.--'```'--.,|
|'-.,_____,.-'|
|'-.,_____,.-'|
| |
| P A I N T |
| |
|'-.,_____,.-'|
`'-.,_____,.-''
""")
width = float(input("insert the width of the wall?\n"))
height = float(input("insert the height of the wall?\n"))
area = width * height
print('Your wall have a size of {} x {} the total area is {}m2'.format(width, height, area))
paint = area / 2
print('To paint that wall you need {:.3f}liters of paint'.format(paint)) | false |
9df9703d3ee33a5494dd97f5401652c66faf0cce | flaviasilvaa/ProgramPython | /63.FibonacciSequence.py | 774 | 4.46875 | 4 | ##this program is going to read a number and show the fibonacci sequence that means we need to sum the 2 previous terms to get the next term
print('-'*30)
print("Fibonacci Sequence")
print('-'*30)
number = int(input("How many terms do you want to show?\n"))
t1 = 0 #this is default
t2 = 1 #this is default
###t1 and t2 are default because they will be in ever single fibonacci sequence does not matter the quantity of terms
print('-'*30)
print(f'{t1} -> {t2}', end= '')
count = 3 ##my counter is going to start in 3 because I do have my 3 default values
while count <= number:
t3 = t1 + t2
print(f' -> {t3}', end= ' ')
t1 = t2 ##t1 is going to be t2 and t2 is going to be t3 when starts to execute my while
t2 = t3
count += 1
print(f'-> End'
f'')
| true |
37455a40b595497e2cafdb5e6f04aa5502dae83e | flaviasilvaa/ProgramPython | /17.hypotenuse.py | 942 | 4.53125 | 5 | ####this program is going to calculate the hypotenuse the formule is a2+ b2 =c2###
##where a= side of a right triangle, b= side of a right triangle and c= hypotenuse, we are going to calculate the lenght
a_opossite = float(input("Type the size of an opposite side of a triangle?\n"))
b_adjacent = float(input("Type the size of an adjacent side of a triangle?\n"))
hypotenuse = (a_opossite ** 2 + b_adjacent ** 2) ** (1/2) ##(1/2) to calculate the square root
print(f'The hypotenuse size is {hypotenuse:.3f}')
###################there is another way to solve it ############################
import math
a_opossite = float(input("Type the size of an opposite side of a triangle?\n"))
b_adjacent = float(input("Type the size of an adjacent side of a triangle?\n"))
hypotenuse = math.hypot(a_opossite, b_adjacent)# this function calculates the hypotenuse just add the a and b variables
print(f"The size of the hypotenuse is {hypotenuse:.2f}")
| true |
a412d099986f79f8a6dcc577bf60c57652cc2e01 | julianhasse/Python_course | /24_accesing_items.py | 558 | 4.28125 | 4 | letters = ["a", "b", "c", "d"]
print(letters[0])
letters[0] = "Julian"
for item in range(len(letters)):
print(letters[item])
# slicing a string
print(letters[0:3]) # returns 3 first items
print(letters[:3]) # zero is assumed
print(letters[0:]) # from first to the final item are returned
print(letters[:]) # a copy of the list is returned
print(letters[::2]) # returns every other element on the list
print(letters[::-1]) # returns every element on the list in reversed order
numbers = list(range(20))
print(numbers[::2])
print(numbers[::-1])
| true |
8b4a928a62a181c20f9fea5ec8c7a361537e93f9 | BushraImtiaz/quarter-1 | /even_odd1.py | 317 | 4.375 | 4 | """10. Write a Python program to find whether a given number (accept from the user) is even or odd,
print out an appropriate message to the user."""
print("**** EVEN OR ODD ****")
user_input=int(input("Enter a number : "))
if user_input%2!=0:
print("Number is odd")
else:
print("Number is even") | true |
9ced3719b4db8955199205e07a9185e81498b28d | BushraImtiaz/quarter-1 | /leapyear1.py | 322 | 4.21875 | 4 | def is_leap (year):
# print(year)
if (year %4 == 0 or year % 400== 0):
print(" true, the year is evenly divided by 4, 400")
elif (year % 100 == 0):
print(" false, the year is divided by 100 is not a leap year")
# return year
years = int(input("enter the year :"))
is_leap(years) | true |
486181e6581076b17eea3f29195f878417c7b18a | BushraImtiaz/quarter-1 | /dictionary.py | 2,614 | 4.3125 | 4 | # PYTHON ASSIGNMENT:
#ALIEN TASK:
# Python Program that display meaning of word said by alien in English Language:
# Python Program that display meaning of word said by human in alien language:
alien_dictionary ={
"hi" : "ha",
"are" : "ary",
"you" : "yaa",
"destroying" : "doodoo",
"earth" : "ee",
"what" : "woe",
"do" : "da",
"want" : "wanna",
"revenge" : "reve",
"from" : "far",
"take" : "hake",
"to" : "tu",
"we" : "woe"
}
human_dictionary = {
"woe" : "we",
"ary" : "are",
"he" : "here",
"tu" : "to",
"hake" : "take",
"reve" : "revenge",
"far" : "from",
"yaa" : "you",
"ha" : "hi",
"wo" : "who",
"da" : "do",
"wanna" : "want",
"woe" : "what"
}
print("==================== ENGLISH / ALIEN TRANSLATOR=========================")
while True:
print("SELECT ANY ONE OPTION :")
print("Enter 1 if you wanna know the meaning of word in english language!")
print("Enter 2 if you wanna add new word in english dictionary!")
print("Enter 3 if you wanna know the meaning of word in alien language:")
print("Enter 4 if you wanna add new word in alien dictionary!")
print("Enter 5 to exit!")
choice = int(input("Enter your choice:"))
if choice == 1:
alien_input = input("Enter the word you wanna change in english language:")
try:
for word,values in human_dictionary.items():
if word == alien_input:
print("The meaning of this word in alien language is:",values)
except:
print("This word currently doesn't exist is our dictionary!")
if choice == 2:
new_word = input("Enter the word you want to Add in human dictionary!")
human_dictionary[new_word] = input("Enter the meaning of this word which doesn't exist before!")
print(human_dictionary)
if choice == 3:
human_input = input("Enter the word you wanna change in alien language:")
try:
for word,values in alien_dictionary.items():
if word == human_input:
print("the meaning of this word in alien language is:",values)
except:
print("This word currently doesn't exist is our dictionary!!")
if choice == 4:
new_word = input("Enter the word you wanna add in alien dictionary:")
alien_dictionary[word] = input("Enter the meaning of this word which doesn't exist before!!")
print(alien_dictionary)
if choice == 5:
break | false |
d4e43ef9582fb927e2a4baf433ecc3e768f67651 | rarezhang/leetcode | /math/009.PalindromeNumber.py | 1,506 | 4.125 | 4 | """
Determine whether an integer is a palindrome. Do this without extra space.
palindrome: a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
x = str(x)
return x == x[::-1]
s = Solution()
s.isPalindrome(0)
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
x = str(x)
left, right = 0, len(x)-1
while left < right:
if x[left] != x[right]:
return False
else:
left += 1
right -= 1
return True
# top solution
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if (x < 0) or (x!=0 and x%10==0):
return False
reverse = 0
while x > reverse:
reverse = reverse*10 + x%10
x = x//10
#print(x, reverse)
return x==reverse or x==reverse//10
# if len(x) is even: test x==reverse
# e.g., 12332 1
# 1233 12
# 123 123
# return True
# --------------------------
# if len(x) is odd: test x==reverse//10
# 1232 1
# 123 12
# 12 123
# True
s = Solution()
r = s.isPalindrome(123321)
print(r) | true |
3342b4c93f87d4a9dea75698272fc0d5bca05af1 | rarezhang/leetcode | /tree/Tree.py | 2,859 | 4.125 | 4 | # Definition for a binary tree node.
from collections import deque
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree:
"""
class TreeNode(object):
def __init__(self, x=None):
self.val = x
self.left = None
self.right = None
"""
def __init__(self):
self.root = None
def add(self, val):
"""
balance, ignore value
"""
if self.root is None:
self.root = TreeNode(val)
else:
self._add(val, self.root)
def _add(self, val, node):
"""
breadth first
"""
queue = deque()
queue.append(self.root)
while len(queue) != 0:
node = queue.popleft()
if node.left is None:
node.left = TreeNode(val)
break
else:
queue.append(node.left)
if node.right is None:
node.right = TreeNode(val)
break
else:
queue.append(node.right)
def add_sorted(self, val):
"""
sorted, based on value
"""
if self.root is None:
self.root = TreeNode(val)
else:
self._add_sorted(val, self.root)
def _add_sorted(self, val, node):
if val < node.val: # add left
if node.left is not None:
self._add_sorted(val, node.left)
else:
node.left = TreeNode(val)
else: # add right
if node.right is not None:
self._add_sorted(val, node.right)
else:
node.right = TreeNode(val)
def __str__(self):
result = ''
tree = self.breadth_first()
for level in tree:
result += str(level) + '\n'
return result
def breadth_first(self):
tree = []
if self.root is None:
return tree
queue = deque()
queue.append(self.root) # queue.push
while len(queue) != 0:
level = []
size = len(queue)
while size > 0:
tree_node = queue.popleft() # queue.dequeue
if tree_node.left is not None:
queue.append(tree_node.left)
if tree_node.right is not None:
queue.append(tree_node.right)
level.append(tree_node.val)
size -= 1
tree.append(level)
return(tree)
'''
t = Tree()
for i in range(10):
t.add(i)
r = t.breadth_first()
print(r)
'''
| true |
94b9545b30ee9ea590ff7990341068b9af65b18c | rarezhang/leetcode | /string/125.ValidPalindrome.py | 1,519 | 4.125 | 4 | """
palindrome: a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
"""
'''
punctuation_space = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ '
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = [cha.lower() for cha in list(s) if cha not in punctuation_space]
rs = list(reversed(s))
return s == rs
'''
# top solution: in place two pointers
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left, right = 0, len(s)-1
while left < right:
while left < right and not s[left].isalnum() :
left += 1
while left < right and not s[right].isalnum() :
right -= 1
if s[left].lower() != s[right].lower():
return False
else:
left += 1
right -= 1
return True
solution = Solution()
test = "A man, a plan, a canal: Panama"
test = ".,"
print(solution.isPalindrome(test)) | true |
35ca53e28b96e232c4effcbf537a322fa95fa367 | rarezhang/leetcode | /array/118.PascalsTriangle.py | 1,602 | 4.1875 | 4 | """
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
"""
# top solution
# Any row can be constructed using the offset sum of the previous row. Example:
# 1 3 3 1 0
# + 0 1 3 3 1
# = 1 4 6 4 1
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
result = [[1]]
for i in range(1, numRows):
result += [list(map(lambda x, y: x+y, result[-1]+[0], [0]+result[-1]))]
return result[:numRows]
s = Solution()
s.generate(5)
# top solution
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
all_rows, row = [], []
for i in range(numRows):
row = [1] + row # left append
for j in range(1, len(row)-1):
row[j] = row[j] + row[j+1]
all_rows.append(row)
return all_rows
# top solution
# two loops, one go through the row, one go through the column
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
all_rows = [None] * numRows
for i in range(numRows):
all_rows[i] = [None] * (i+1)
all_rows[i][0] = all_rows[i][i] = 1
for j in range(1, i):
all_rows[i][j] = all_rows[i-1][j-1] + all_rows[i-1][j]
return all_rows | true |
be0e2731f371fd6afc72bd461a0f7e65ba0a0775 | divakarpatil51/competitive-programming | /sorting_algo/insertion_sort.py | 466 | 4.25 | 4 | # Time Complexity:
# Worst case: O(n ^ 2)
# Space Complexity: O(1) --> Since we are doing sorting in place
# We are moving elements from unsorted array to sorted array.
def insertion_sort(arr: list):
for i in range(1, len(arr)):
j = i
while j > 0 and arr[j] < arr[j - 1]:
temp = arr[j]
arr[j] = arr[j - 1]
arr[j - 1] = temp
j -= 1
return arr
op = insertion_sort([10, 2, 1, 3, 2])
print(op)
| true |
74cc0e301f13c65f868f158ea20fdcfc70234ec3 | bmk316/daniel_liang_python_solutions | /4.21.py | 1,619 | 4.15625 | 4 | #4.21 Zeller's formula to calculate day of the week
# h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday 4: Wednesday, 5: Thursday, 6: Friday).
# q is the day of the month.
# m is the month (3: March, 4: April, ..., 12: December). January and February are counted as months 13 and 14 of the previous year.
# j is the century (i.e. year/100).
# k is the year of the century (i.e., year % 100).
import math
saturday = "Saturday"
sunday = "Sunday"
monday = "Monday"
tuesday = "Tuesday"
wednesday = "Wednesday"
thursday = "Thursday"
friday = "Friday"
year = eval(input("Enter the year (e.g., 2007): "))
j = math.floor(year/100)
k = year % 100
m = eval(input("Enter the month: 1-12: ")) #Which month?
q = eval(input("Enter the day of the month: 1-31: ")) #Day of the month
h = (q + math.floor(26 * (m - 2) / 10) + k + math.floor(k / 4) + math.floor(j / 4) + 5 * j) % 7
if m == 1:
m += 12
year -= 1
h = (q + math.floor(26 * (m - 2) / 10) + k + math.floor(k / 4) + math.floor(j / 4) + 5 * j) % 7
if m == 2:
m += 12
year -= 1
h = (q + math.floor(26 * (m - 2) / 10) + k + math.floor(k / 4) + math.floor(j / 4) + 5 * j) % 7
print(h)
if h == 0:
print("Day of the week is:", saturday)
elif h == 1:
print("Day of the week is:", sunday)
elif h == 2:
print("Day of the week is:", monday)
elif h == 3:
print("Day of the week is:", tuesday)
elif h == 4:
print("Day of the week is:", wednesday)
elif h == 5:
print("Day of the week is:", thursday)
elif h == 6:
print("Day of the week is:", friday)
| false |
9e77fdbe49fcc00ef82dcbe571f8c3fad3337840 | bmk316/daniel_liang_python_solutions | /5.19.py | 830 | 4.25 | 4 | #Display a pyramid
# for i in range(1, num+1):
# for j in range(1, i+1):
# print(j, end=' ')
# print()
num = int(input("Enter the number of rows:"))
for i in range(1, num+1):
for j in range(1, num-i+1):
print(end=" ")
for j in range(i, 0, -1):
print(j, end="")
for j in range(2, i+1):
print(j, end="")
print()
# UserInput = int(input("Enter number of lines: "))
#
# NumberOfIterationsinaline = UserInput * 2
#
# for i in range(1, UserInput + 1):
# s = UserInput + NumberOfIterationsinaline
# sp = str(s) + "s"
# print(format(" ", sp), end='')
# for j in range(i, 0, -1):
# print(j, end=' ')
# for j in range(2, i + 1):
# print(j, end=' ')
#
# print(format(" ", sp))
# NumberOfIterationsinaline -= 3 | false |
1b99306ae37639c2c1f20ad62fa909c1fe4e0fa4 | bastianposey/ML | /ml_classification_exercise.py | 2,360 | 4.15625 | 4 | # The Iris dataset is referred to as a “toy dataset” because it has only 150 samples and four features.
# The dataset describes 50 samples for each of three Iris flower species—Iris setosa, Iris versicolor and Iris
# virginica. Each sample’s features are the sepal length, sepal width, petal
# length and petal width, all measured in centimeters. The sepals are the larger outer parts of each flower
# that protect the smaller inside petals before the flower buds bloom.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt2
#EXERCISE
# load the iris dataset and use classification
# to see if the expected and predicted species
# match up
iris = load_iris()
# display the shape of the data, target and target_names
#print("iris data shape")
#print(iris.data.shape)
#print("iris target shape")
#print(iris.target.shape)
#print(iris.target_names)
# display the first 10 predicted and expected results using
# the species names not the number (using target_names)
data_train, data_test, target_train, target_test = train_test_split(
iris.data, iris.target, random_state=11)
#print(data_train.shape)
#print(target_train.shape)
#print(data_test.shape)
#print(target_test.shape)
knn = KNeighborsClassifier()
knn.fit(X=data_train , y=target_train)
predicted = knn.predict(X=data_test)
expected = target_test
#print("iris predicted")
#print(predicted[:10])
#print("iris expected")
#print(expected[:10])
predicted = [iris.target_names[x] for x in predicted]
expected = [iris.target_names[x] for x in expected]
#print("iris predicted")
#print(predicted[:10])
#print("iris expected")
#print(expected[:10])
# display the values that the model got wrong
wrong = [(p,e) for (p,e) in zip(predicted, expected) if p != e]
#print("wrong values")
#print(wrong)
# visualize the data using the confusion matrix
confusion = confusion_matrix(y_true=expected, y_pred=predicted)
confusion_df = pd.DataFrame(confusion, index=iris.target_names, columns=iris.target_names)
figre = plt2.figure()
axes = sns.heatmap(confusion_df,
annot=True, cmap=plt2.cm.nipy_spectral_r)
plt2.xlabel('Expected')
plt2.ylabel('Predicted')
plt2.show()
| true |
ad1641c9a82225c8580d65730e382ebf3abf9c3e | pioneer-pi/Alogrithms_and_data_structure | /Lab5/Question3.py | 722 | 4.15625 | 4 | '''
Suppose that there are n jobs that need to use a meeting room,
the ith job occupies the meeting room in the time interval [si, fi).
please make an optimal schedule to arrange jobs as much as possible for the meeting room using a greedy approach.
You are asked to give which jobs can be arranged in the meeting room compatibly and the maximum number of these jobs.
'''
# a is list of jobs, which are presented by time intervals.
def job_selection(a):
Choose = []
length = len(a)
Choose.append(a[0])
k = 0
for i in range(1,length):
if a[i][0] >= a[k][1]:
Choose.append(a[i])
k = i
return Choose
a = [(1, 4), (3, 5), (4, 6), (5, 7), (6, 9)]
print(job_selection(a)) | true |
5fa375fc8677c2ab6476a1bfba4aab8a67331fcd | OctavioCoronaHernandez95/prctica | /BucleFor.py | 1,224 | 4.3125 | 4 | #Un bucle for es un bucle que repite el bloque de instrucciones un número
#predeterminado de veces. El boque de instrucciones,
print("Comienzo")
for i in [3, 4, 5]:
print("Hola. Ahora i vale", i, "y su cuadrado", i ** 2)
print("Final")
#Los valores de la variable no son importantes. Lo que importa es que
#tiene tres elementos, por tanto el bucle se ejecutara tres veces.
#La variable de control i puede ser una valiable empleada antes del bicle.
#El valos que tenga no afecta la ejecucion del bucle, pero al terminar el
#bucle, i conserva el último valor asignado.
i = 10
print("El bucle no ha comenzado. Ahora i vale", i)
for i in [0, 1, 2, 3, 4]:
print(i, "*", i,"=", i ** 2)
print("El bucle ha terminado. Ahora i vale", i)
#Se puede usar una cadena y la variable tomará el valor de cada uno de Los
#carácteres
for i in "AMIGO":
print("Dame una ", i)
print("¡AMIGO!")
#imprime tres veces Hola
print("Comienzo")
for i in range(3):
print("Hola ", end="")
print()
print("Final")
#el num de iteraciones lo elige el usuario
veces = int(input("¿Cuántas veces quiere que le salude? "))
for i in range(veces):
print("Hola ", end="")
print()
print("Adios")
| false |
303296e3290e76420fcf0d5bf3becd2cec0dd344 | OctavioCoronaHernandez95/prctica | /Listas.py | 1,153 | 4.28125 | 4 | # Primera manera de declarar una lista
primera_lista = list()
# Otra manera de declarar una lista
segunda_lista = ['x', 'y', 'z']
# Tercera manera de declarar una lista
tercera_lista = []
# Agregar valores a la lista
primera_lista.append('a')
primera_lista.append('b')
primera_lista.append('c')
primera_lista.append('d')
primera_lista.append('e')
print primera_lista
# ['a', 'b', 'c', 'd', 'e']
# Seleccionar un elemento de la lista
print primera_lista[0]
# 'a'
# Seleccionar varios elementos de una lista
print primera_lista[2:]
# ['c', 'd', 'e']
# Seleccionar un rango de elementos de una lista
print primera_lista[1:3]
# ['b', 'c']
#Seleccionar ciertos elementos de la lista
print primera_lista[0::2]
# ['a','c']
# Eliminar un elemento de la lista
del primera_lista[4]
print primera_lista
# print ['a', 'b', 'c', 'd']
#Otra manera de eliminar un elemento
primera_lista.remove('d')
print primera_lista
# print ['a', 'b', 'c']
#Cambiar elementos de una lista
primera_lista[0:2]=[2,5]
print primera_lista
# print ['2', 'b', '5']
# Obtener el indice de un elemento
primera_lista.index('b')
| false |
df5b03efb7c7309eda75c9298aa6856244924920 | vikmreddy/D04 | /HW04_ch07_ex02.py | 1,496 | 4.6875 | 5 | #!/usr/bin/env python
# HW04_ch07_ex02
# The built-in function eval takes a string and evaluates it using the Python
# interpreter.
# For example:
# >>> eval('1 + 2 * 3')
# 7
# >>> import math
# >>> eval('math.sqrt(5)')
# 2.2360679774997898
# >>> eval('type(math.pi)')
# <type 'float'>
# Write a function called eval_loop that iteratively prompts the user, takes
# the resulting input and evaluates it using eval, and prints the result.
# It should continue until the user enters 'done', and then return the value of
# the last expression it evaluated.
###############################################################################
# Imports
import pdb
# Body
def eval_loop():
result = ""
while True:
# Prompt user
prompt = ("Please type some Python code to evaluate or type 'done' to finish:\n")
user_input = input(prompt)
# Evaluate result
if user_input != "done":
try:
result = eval(user_input)
except (SyntaxError, NameError) as e:
print("Please check if there are any syntax errors or undefined variables in your code.", e)
print(result)
else:
return result
###############################################################################
def main():
eval_loop()
# Uncomment to test the return value of the last evaluated expression
# print(eval_loop())
if __name__ == '__main__':
main()
| true |
2e31a6bc26ac25045a84aa00e05c5e987662ee8a | jjkoretoff/udacity | /programming-foundations-with-python/rename.py | 873 | 4.28125 | 4 | # the objective of this function is to take a set of files in a folder and
# rename them without numbers attached to their names
# access os files in py
import os
# define an empty function that has the same name as this file
def rename ():
#(1) get file names from a folder
file_list = os.listdir("/Users/johnkoretoff/code/udacity/programming-foundations-with-python/prank")
#print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir("/Users/johnkoretoff/code/udacity/programming-foundations-with-python/prank")
#(2) for each file, rename file
for file_name in file_list:
print("Old Name - " + file_name)
print("New Name - " + file_name.translate(None, "0123456789"))
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
rename()
| true |
22efd34b0555a0de51143644d326d920027612a4 | ChanceDurr/Practice | /Hackerrank/string_manipulation/alternating_characters.py | 578 | 4.21875 | 4 | '''
You are given a string containing characters A and B only. Your task is to
change it into a string such that there are no matching adjacent characters.
To do this, you are allowed to delete zero or more characters in the string.
Your task is to find the minimum number of required deletions.
'''
import sys
def alternatingCharacters(s):
s = list(s)
count = 0
for i in range(len(s)-1, 0, -1):
if s[i] == s[i-1]:
count += 1
del s[i]
return count
s = sys.argv[1]
print('Characters to remove: ', alternatingCharacters(s)) | true |
71525b455d0d0899ebfbc733173e172689f61de0 | biswadeepdatta77/Treasure-Island-Game | /Treasure_Island.py | 897 | 4.28125 | 4 | print("Welcome to Treasure Island!! Your mission is to find the treasure ")
choice = input("Do you want to go left or right? Type 'left' to go left or type 'right' to go right ")
if choice=='right':
print("Game Over ")
if choice=='left':
choice2= input("You have reached a lake. Do you want to swim or wait for boat? Type 'swim' to swim or type 'wait' to wait for the boat ")
if choice2=='swim':
print("Game Over")
if choice2=='wait':
choice3 = input("You have reached in front of thee houses- red, blue and yellow unharmed. Choose which house you want to go? Type 'red' to go to red house or 'yellow' to go to yellow house or 'blue' to go to blue house ")
if choice3=='blue':
print("Game Over")
if choice3=='red':
print("Game Over")
if choice3=='yellow':
print("Congratulations! You Won.") | true |
fb17e8e6f50ece59d8d46aa87a6fd4bfcf90b05e | Edceebee/python_practice | /creditLimitCalculator.py | 1,443 | 4.46875 | 4 | # (Credit Limit Calculator) Develop a python application that determines whether any of
# several department-store customers has exceeded the credit limit on a charge account. For each customer,the
# following facts are available: (a) account number (b) balance at the beginning of the month (c)total of all
# items charged by the customer this month (d) total of all credits applied to the customer’s account this
# month (e) allowed credit limit.The program should input all these facts as integers, calculate the new balance
# (= beginning balance+ charges – credits), display the new balance and determine whether the new balance exceeds
# the customer’s credit limit. For those customers whose credit limit is exceeded, the program should dis-play the
# message "Credit limit exceeded".
def creditLimitCalculator():
acctNumber = int(input("Enter account number: "))
balance = int(input("Enter balance at the beginning of the month :"))
totalItemsCharged = int(input("total of all items charged by the customer this month: "))
creditApplied = int(input("total of all credits applied to the customer’s account this month: "))
allowedCredit = int(input("allowed credit limit: "))
newBalance = balance + totalItemsCharged - allowedCredit
if newBalance > allowedCredit:
print(f'new balance is {newBalance}')
else:
print('Credit limit has been Exceeded')
creditLimitCalculator()
| true |
7d37d5f038c68e703f24aa38b5302065016f1c24 | 24rochak/GeeksforGeeks | /Searching/InterpolationSearch.py | 1,699 | 4.15625 | 4 | def interpolation_search(arr: [int], key: int, low: int, high: int) -> int:
"""
Performs Interpolation Search over given array. Works best when elements are uniformly distributed.
Time complexity : O(log(log(n))), worst case : O(n)
:param arr: Sorted Input Array.
:param key: Value to be searched for.
:param low: Starting index of target array.
:param high: Ending index of target array.
:return: Index of key if it is present in the array else -1.
"""
# Check if array is valid or not.
if low <= high:
# If corners are reached, to avoid division by 0 error, check here itself.
if low == high:
if arr[low] == key :
# Return index of low if key is present.
return low;
return -1;
# Calculate location of pos.
pos = low + int(((key - arr[low]) * (high - low)) / (arr[high] - arr[low]))
if arr[pos] == key:
# Return index of pos if key is present.
return pos;
elif arr[pos] > key:
# Perform interpolation_search on left sub-array.
return interpolation_search(arr, key, low, pos - 1)
else:
# Perform interpolation_search on right sub-array.
return interpolation_search(arr, key, pos + 1, high)
else:
return -1
if __name__ == '__main__':
# Test array
arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]
key = 33
# Perform interpolation_search
loc = interpolation_search(arr, key, 0, len(arr) - 1)
# Display the index of key
print("Key is present at index : ", loc)
| true |
a7105e926a8337c78e61625143a69f3eca8cec46 | InnovativeCoder/Innovative-Hacktober | /Data Structures and Algorithms/Stack and queue/Reversing a queue.py | 942 | 4.3125 | 4 | """
Give an algorithm for reversing a queue Q. Only following standard operations are allowed on queue.
1.enqueue(x) : Add an item x to rear of queue.
2.dequeue() : Remove an item from front of queue.
3.empty() : Checks if a queue is empty or not."""
# Python3 program to reverse a queue
from queue import Queue
# Utility function to print the queue
def Print(queue):
while (not queue.empty()):
print(queue.queue[0], end = ", ")
queue.get()
# Function to reverse the queue
def reversequeue(queue):
Stack = []
while (not queue.empty()):
Stack.append(queue.queue[0])
queue.get()
while (len(Stack) != 0):
queue.put(Stack[-1])
Stack.pop()
# Driver code
if __name__ == '__main__':
queue = Queue()
queue.put(10)
queue.put(20)
queue.put(30)
queue.put(40)
queue.put(50)
queue.put(60)
queue.put(70)
queue.put(80)
queue.put(90)
queue.put(100)
reversequeue(queue)
Print(queue)
# This code is contributed by PranchalK
| true |
00c561da282ff85a14c37cf63b2e53ddb5f84842 | SoumilDhiman/Guessing-Game | /GuessingGame.py | 437 | 4.125 | 4 | import random
randomNumber = random.randint(1,9)
chance = 0
while chance <5:
guess = int(input("Enter Your Guess: "))
if guess==randomNumber:
print("You Win")
elif guess<randomNumber:
print("Your Guess Was Too Low Try a Highr Number")
else :
print("Your Guess Was Too High Try a lower Number")
chance = chance+1
if not chance<5:
print("YOU LOSE,the number was: ",randomNumber) | true |
8312c42438e1c72740548966916818a0b56cc698 | dsparr1010/COP2030 | /06_shipping_charges/shipping_charges.py | 1,676 | 4.71875 | 5 | #2/23/2021
#Debra Sparr
#Assignment 6 - shipping rates
"""
The Fast Freight Shipping Company charges the following rates:
Weight of Package
Rate per Pound
$1.50 - 2 pounds or less
$3.00 - Over 2 pounds but not more than 6 pounds
$4.00 - Over 6 pounds but not more than 10 pounds
$4.75 - Over 10 pounds
"""
class ViolatesLawsOfPhysics(Exception):
pass
def shipping_rates():
"""asks the user to enter the weight of a package and then displays the shipping charge"""
try:
# turn input into a float
weight = float(input('Enter the weight of your package in pounds to get the shipping charge : '))
# if weight entered is < or = to 0, raise error
if weight <= 0:
raise ViolatesLawsOfPhysics
# Check weight value, display shipping rate for that weight, and look forward to switch statements
if weight <= 2 and weight > 0 :
print(f'The shipping charge for a {weight}lb package is $1.50')
if weight > 2 and weight <= 6 :
print(f'The shipping charge for a {weight}lb package is $3.00')
if weight > 6 and weight <= 10 :
print(f'The shipping charge for a {weight}lb package is $4.00')
if weight > 10 :
print(f'The shipping charge for a {weight}lb package is $4.75')
# catch inputs that cannot be converted to a float
except ValueError :
print('You must enter a number to get the shipping weight.')
# catch input that is less 0
except ViolatesLawsOfPhysics :
print('Unless the laws of physics cease to exist in package, your package must have a weight.')
if __name__ == '__main__' :
shipping_rates() | true |
2deae9301c087580666ffae5b30d82a1a1519d82 | dsparr1010/COP2030 | /08_lotto_numbers/lotton_numbers.py | 836 | 4.25 | 4 | # Debra Sparr
# 3/13/2021
# Assignment 8 - Lotto Numbers
import random
def lotto_number():
""" Program generates lotto numbers based on the number of tickets the user supplies """
try :
ticket_number = int(input('How many lotto tickets do you want?'))
if ticket_number <1 or ticket_number > 8:
raise ValueError
master_list = []
while len(master_list) != ticket_number*6 :
number = random.randint(1,53)
if number not in master_list:
master_list.append(number)
for i in range(0, len(master_list), 6):
chunk = master_list[i:i + 6]
print('Your lotto numbers are :')
print(chunk)
except ValueError:
print('You must enter a number between 1 and 8')
if __name__ == '__main__':
lotto_number()
| true |
70ce0afb9b7e93f53b8f2b88c19b01334849ddf6 | DritiTannk/python-challanges | /strstr_solution.py | 926 | 4.125 | 4 | """
Your task is to implement the function strstr. The function takes two strings as arguments (s,x) and locates the occurrence of the string x in the string s. The function returns and integer denoting the first occurrence of the string x in s.
Example:
Input
2
GeeksForGeeks Fr
GeeksForGeeks For
Output
-1
5
"""
if __name__ == '__main__':
usr_input1 = input("Enter The Sentence: ").lower()
usr_input2 = input("Enter The Word To Be Found: ").lower()
if usr_input1 == '' or usr_input2 == '': # If empty values are entered
print("\n *** You Have Entered the Empty Value. ***")
else:
find_operation = lambda s1, s2: s1.find(s2) # Lambda function for searh operation.
pos = find_operation(usr_input1, usr_input2)
if pos == -1:
print(f'Word \'{usr_input2}\' NOT Found.')
else:
print("Position Of \'{0}\' Word Is: {1} ".format(usr_input2, pos))
| true |
62c7cb9e5a479c766c250620c1049b575419e07b | yazhisun/HPM573S18_SUN_HW1 | /hw1_q3.py | 514 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 21 19:22:00 2018
@author: Administrator
"""
#. Write an iterative function and a recursive
#function that computes the sum of all numbers from 1 to n, where n is given as parameter. Test both
#functions for n = 100
#iterative function
def sumiter(n):
sum=0
for i in range(1, n+1):
sum +=i
return sum
print(sumiter(100))
#recursion function
def sumrec(n):
if n==1:
return 1
else:
return n+sumrec(n-1)
print(sumrec(100)) | true |
765228e13c6022ed043cdc45a32a5d2194929d2f | BJNick/APCS-Practice | /unit2_lesson10_11/turtle_polygon.py | 1,384 | 4.40625 | 4 | """
Mykyta S.
turtle_polygon.py
Draws a polygon, based on number of sides n
"""
import turtle
def draw_square(my_turtle, size):
my_turtle.pendown()
for move in range(4):
my_turtle.forward(size)
my_turtle.left(360/4)
my_turtle.penup()
def draw_pentagon(my_turtle,size):
my_turtle.pendown()
for move in range(5):
my_turtle.forward(size)
my_turtle.left(360/5)
my_turtle.penup()
def draw_triangle(my_turtle,size):
my_turtle.pendown()
for move in range(3):
my_turtle.forward(size)
my_turtle.left(360/3)
my_turtle.penup()
def draw_hexagon(my_turtle,size):
my_turtle.pendown()
for move in range(6):
my_turtle.forward(size)
my_turtle.left(360/6)
my_turtle.penup()
def draw_polygon(my_turtle,size,n):
my_turtle.pendown()
for move in range(n):
my_turtle.forward(size)
my_turtle.left(360/n)
my_turtle.penup()
window = turtle.Screen() # Creates a window for bob so play
bob = turtle.Turtle() # creates a turtle named bob
bob.speed(5) #speed(0) is fastest
bob.shape("turtle") # Makes bob look like a turtle
bob.penup()
bob.backward(200)
draw_square(bob,30)
bob.forward(80)
draw_pentagon(bob,30)
bob.forward(80)
draw_triangle(bob, 30)
bob.forward(80)
draw_hexagon(bob, 30)
bob.forward(80)
draw_polygon(bob, 30, 7)
window.exitonclick()
| false |
a5e0de7984d376a2a399e08cdd09dab99ced12f2 | BJNick/APCS-Practice | /unit2_lesson3_4/hw/leap_years.py | 371 | 4.3125 | 4 | """
Mykyta S.
leap_years.py
Returns whether the entered year is a leap year
"""
def is_a_leap_year(year):
"""Print whether a given year is a leap year"""
result = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
print(year, "is", "a leap year." if result else "not a leap year.")
entered_year = int(input("Enter year: "))
is_a_leap_year(entered_year)
| false |
81cde668ff660caa927aaa813f7bf0a0e822f4ed | BJNick/APCS-Practice | /unit5_lesson4/math_recursion.py | 948 | 4.3125 | 4 | """
Mykyta S.
math_recursion.py
Contains some of the recursive sequence algorithms (Fibonacci, sums, factorial)
"""
def fibonacci(n):
"""Returns a number in the Fibonacci sequence"""
if n <= 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
def factorial(n):
"""Returns the factorial of a number"""
if n <= 1:
return 1
return n * factorial(n-1)
def sum(n):
"""Recursive sum of the numbers up to n"""
if n <= 1:
return n
return n + sum(n-1)
if __name__ == "__main__":
# Print out the number sum sequence
print("Number sum:")
for i in range(1, 10):
print(sum(i), end=" ")
print()
# Print out the Fibonacci sequence
print("Fibonacci:")
for i in range(1, 10):
print(fibonacci(i), end=" ")
print()
# Print out the factorial sequence
print("Factorial:")
for i in range(1, 10):
print(factorial(i), end=" ")
print() | true |
4d24009fc46413749b84939308e077f301765347 | Aanandi03/15Days-Python-Django-Summer-Internship | /Day-2/basics.py | 1,945 | 4.28125 | 4 | # COMMENTS IN PYTHON
# Hash is used to comment in the Python
''' Inverted comma are also used to comment in python '''
# This is a single line comment!
"""
This is a multi-line comment.
Generally, used to show documentation.
"""
# VARIABLES IN PYTHON
week_days = 7 # declaration of varaible
day_hours = 24
week_hours = (week_days * day_hours)
print(week_hours) # print values of variable
# DATATYPES IN PYTHON
#Int Str Float Bool
x = 10
y = "10"
z = 10.1
sum1 = x+x
sum2 = y+y
print(sum1,sum2)
print(type(x),type(y),type(z))
#Complex
n=10 + 2j
print(type(n))
#List
#Represent arrays of values that may change during the course of the program:
student_grades = [3.0, 5.0, 4.5]
print(student_grades)
print(type(student_grades))
#Creating a complex list
rainfall = [10.1, 9, "no data", [1,2,3]]
print(rainfall)
print(type(rainfall))
#Range
#To specify the list boundaries
print(list(range(1, 10, 2)))
#Dictionary
#Represent pairs of keys and values:
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
volcano_elevations = {"Glacier Peak": 3213.9, "Rainer": 4392.1}
phone_numbers.keys()
phone_numbers.values()
# Tuples
# Represent arrays of values that are not to be changed during the course of the program:
vowels = ('a', 'e', 'i', 'o', 'u')
one_digits = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(vowels)
print(one_digits)
# Set
# Used to store multiple items in a single variable and it's iterable,
# mutable and no duplicate values:
s={4,5,6,90,110,0}
print(s)
# Slice/Split
# Used to access elements in it:
#List
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(days)
print(days[1:4])#In a list, the 2nd, 3rd, and 4th items can be accessed with
print(days[:3])#First three items of a list:
print(days[-3:])#Last three items of a list:
print(days[:-1]) #Everything but the last:
| true |
5f34c4b74a4d498effa92176c6735a58be3a2aeb | lgqfhwy/thinkcspy3 | /count_letter_in_text.py | 1,262 | 4.46875 | 4 | import string
def remove_punctuation(s):
ss = ""
for letter in s:
if letter not in string.punctuation:
ss += letter
return ss
def count_letter_in_text(text, letter):
count_word = 0
count_letter = 0
text_remove_punctuation = remove_punctuation(text).split()
for ch in text_remove_punctuation:
count_word += 1
for le in ch:
if le == letter:
count_letter += 1
break
print("Your text contains {0} worlds, of which {1} ({2:.1f}%) contain an \"{3}\""
.format(count_word, count_letter, count_letter * 1.0 / count_word * 100, letter))
return (count_word, count_letter)
text = """
In the following examples, input and output are distinguished by
the presence or absence of prompts (>>> and ...): to repeat the
example, you must type everything after the prompt, when the prompt
appears; lines that do not begin with a prompt are output from the
interpreter. Note that a secondary prompt on a line by itself in
an example means you must type a blank line; this is used to end
a multi-line command.
"""
count_letter_in_text(text, 'e')
| true |
3b9da589cbbbebb56af95516efea68a35f31f897 | aamathur02/LeetcodeGrind | /Sorting_Algorithms/BinarySearch/BinarySearch.py | 1,040 | 4.125 | 4 | from typing import List
def iterative_binary_search(array: List[int], target: int) -> int:
first = 0;
last = len(array) - 1;
mid = 0;
while (first <= last):
mid = first + (last - first) // 2
if (array[mid] == target):
return mid
if (array[mid] > target):
last = mid - 1
else:
first = mid + 1
return -1
def recursive_binary_search(array: List[int], target: int, low: int, high: int) -> int:
if (low <= high):
mid = low + (high - low) // 2
if (array[mid] == target):
return mid
if (array[mid] > target):
return recursive_binary_search(array, target, low, mid - 1)
else:
return recursive_binary_search(array, target, mid + 1, high)
return -1
def main():
list = [1,2,3,4,5,6,7,8,9]
print(iterative_binary_search(list, 8))
print(recursive_binary_search(list, 8, 0, (len(list) - 1)))
if __name__ == "__main__":
main() | false |
73f347cf3afde711f02a8db747b3f90b0bbba7aa | AndreiR01/Recursion-Practise | /recusion sum_to_one.py | 1,142 | 4.3125 | 4 | #We are building our recursive funtion which takes an integer as an input and returns the sum of all numbers from the input down to 1
#the functiuon will look like so if we were to write it iteratively:
#------------
#def sum_to_one(n):
# result = 0
# for num in range(n, 0, -1):
# result += num
# return result
#------------
#sum_to_one(4)
#num is set to 4, 3, 2, and 1
#10
#------------
#However we can think of each recursive call as an iteration of the loop above
#recursive_sum_to_one(4)
#recursive_sum_to_one(3)
#recursive_sum_to_one(2)
#recursive_sum_to_one(1)
#------------------
# Every recursive method does need a base case when the function does not recurse and a recursive step, when the recursing fuction mmoves toward the base step
#Base case:
#The integer given as input is 1.
#---------------
#Recursive step:
#The recursive function call is passed an argument 1 less #than the last function call.
def sum_to_one(n):
#setting up our base case
if n == 1:
return n
print("Recursing with input: {0}".format(n))
#setting up our recursive step
return n + sum_to_one(n-1)
print(sum_to_one(4))
| true |
036c56ef43451dd31bdb6c5928f87bd01b89dfa8 | vaniparidhyani/Pythonic | /Sandbox/Easy/primeFactorization.py | 984 | 4.28125 | 4 | #!/usr/bin/python
#"Prime Factorization" is finding which prime numbers multiply together to make the original number.
''' Return an array containing prime numbers whose product is x
Examples:
primeFactorization(6) == [2,3]
primeFactorization(5) == [5]
primeFactorization(12) == [2,2,3]'''
def primeFactorization(x):
factors = []
i = 2
if x > 0:
while x > 1:
while x % i == 0:
factors.append(i)
x = x/i
i = i + 1
return factors
def doTestsPass():
testVals = [6, 5, 12, 1, -1]
testAnswers = [[2, 3], [5], [2, 2, 3], [], None]
for value, answer in zip(testVals, testAnswers):
if primeFactorization(value) != answer:
print ("Test failed for %d" % value)
return False
return True
if __name__ == "__main__":
if doTestsPass():
print ("All tests pass")
else:
print ("Not all tests pass")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.