blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
067dc51bc622e4e7514fc72c0b8b4626db950da5 | amitp29/Python-Assignments | /Python Assignments/Assignment 3/question12.py | 1,237 | 4.34375 | 4 | '''
Read 10 numbers from user and find the average of all.
a) Use comparison operator to check how many numbers are less than average and print them
b) Check how many numbers are more than average.
c) How many are equal to average.
'''
num_list = []
sum_of_num = 0
for i in range(10):
while True:
try:
i = int(raw_input("Enter the numbers : "))
break
except:
print "You entered incorrectly, Please eneter integers "
continue
sum_of_num += i
num_list.append(i)
average = sum_of_num/float(len(num_list))
print "Average of the numbers is :", sum_of_num/float(len(num_list))
smaller_num_list =[]
equal_num_list= []
bigger_num_list= []
for j in num_list:
print j
if(j<average):
smaller_num_list.append(j)
if(j==average):
equal_num_list.append(j)
if(j>average):
bigger_num_list.append(j)
print " Total %s number/numbers are greater than average, they are: %s"%(len(bigger_num_list),bigger_num_list)
print " Total %s number/numbers are equal than average, they are: %s"%(len(equal_num_list),equal_num_list)
print " Total %s number/numbers are lesser than average, they are: %s"%(len(smaller_num_list),smaller_num_list)
| true |
45bcaf8e7ddb54e50dc916ee8ae1604345c27072 | amitp29/Python-Assignments | /Python Assignments/Assignment 3/question20.py | 835 | 4.34375 | 4 | '''
Write a program to generate Fibonacci series of numbers.
Starting numbers are 0 and 1, new number in the series is generated by adding previous two numbers in the series.
Example : 0, 1, 1, 2, 3, 5, 8,13,21,.....
a) Number of elements printed in the series should be N numbers, Where N is any +ve integer.
b) Generate the series until the element in the series is less than Max number.
'''
a=0
b=1
n=int(raw_input("Enter the number of terms needed "))
list1 = [a,b]
while(n-2):
c=a+b
a=b
b=c
list1.append(c)
n=n-1
for integer in list1:
print integer
m=int(raw_input("Enter the number until which the series is to be printed "))
a=0
b=1
list1 = [a,b]
while(m-2):
c=a+b
if(c>m):
break
a=b
b=c
list1.append(c)
m=m-1
for integer in list1:
print integer
| true |
874f3d5621af8a3cd128bd2d06e30cfe6bb3f0c5 | amitp29/Python-Assignments | /Python Assignments/Assignment 3/question7.py | 430 | 4.21875 | 4 | '''
Create a list with at least 10 elements in it :-
print all elements
perform slicing
perform repetition with * operator
Perform concatenation wiht other list.
'''
#perform repetition with * operator
list1 = [1]*7
list2 = [4,5,6]
#Perform concatenation with other list
list3 = list1+list2
print list3
#print all elements
for i in list3:
print i
#perform slicing
print "Sliced list",list3[2:]
| true |
7545be7a5decce69dd33717fc7a77ca5848e6a3d | amitp29/Python-Assignments | /Python Assignments/Assignment 2/question3.py | 942 | 4.15625 | 4 | '''
4. Given a list of strings, return a list with the strings in sorted order, except
group all the strings that begin with 'x' first.
e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
['xanadu', 'xyz', 'aardvark', 'apple', 'mix'].
Hint: this can be done by making 2 lists and sorting each of them before combining them.
i. ['bbb', 'ccc', 'axx', 'xzz', 'xaa']
ii. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
'''
list1 = ['bbb', 'ccc', 'axx', 'xzz', 'xaa']
list2 = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
super_list = [list1, list2]
#Iterating through both lists
for lists in super_list:
lst = []
lst2 = []
#Sorting the list
lists = sorted(lists)
for word in lists:
if(word[0]=='x'):
lst.append(word)
else:
lst2.append(word)
#Combining the lists
lists = lst+lst2
print lists
| true |
1dca7820586525dcd22cebeb2d851eb1d2bf8c42 | SJasonHumphrey/DigitalCrafts | /Python/Homework004/word_histogram.py | 958 | 4.3125 | 4 | # 2. Word Summary
# Write a word_histogram program that asks the user for a sentence as its input, and prints a dictionary containing
# the tally of how many times each word in the alphabet was used in the text.
wordDict = {}
sentence = input('Please enter a sentence: ')
def wordHistogram(sentence):
for word in sentence:
if word not in wordDict:
wordDict[word] = 1
else:
wordDict[word] += 1
return wordDict
sentence = sentence.upper().split()
result = wordHistogram(sentence)
print(result)
# collections module
from collections import Counter
# 3. Sorting a histogram
# Given a histogram tally (one returned from either letter_histogram or word_histogram), print the top 3 words or letters.
def histogramTally():
counter = Counter(result)
# 3 highest values
top = counter.most_common(3)
print("The top 3 words are:")
for i in top:
print(i[0]," : ",i[1]," ")
histogramTally() | true |
615c76f289b017a1c7a9b8a9f956a594f17ab727 | LucianoBartomioli/-EDU-IRESM_AEDI_2020 | /clase_7_clases_busqueda/clases.py | 1,042 | 4.21875 | 4 | class Empleado:
def __init__(self, nombre, apellido, dni, legajo, puesto, salario_por_hora, cantidad_hs_trabajadas):
self.nombre = input("Ingrese el nombre")
self.apellido = input("Ingrese el apellido")
self.dni = input("Ingrese el DNI")
self.legajo = input("Ingrese el N° de legajo")
self.puesto = input("Ingrese el puesto")
self.salario_por_hora = float(input("Ingrese el salario p/ hora"))
self.cantidad_hs_trabajadas = 0
def mostrar_datos(self):
print(f"Nombre: {self.nombre}")
print(f"Apellido: {self.apellido}")
print(f"DNI: {self.dni}")
print(f"Legajo: {self.legajo}")
print(f"Puesto: {self.puesto}")
print(f"Salario p/hora: {self.salario_por_hora}")
print(f"Cantidad de hs trabajadas: {self.cantidad_hs_trabajadas}")
print(f"Sueldo calculado: ${self.cantidad_hs_trabajadas*self.salario_por_hora}")
def ingresar_cantidad_de_horas(self, cantidad_hs):
self.cantidad_hs_trabajadas = cantidad_hs | false |
f37f41087fd970146217e4b32a16f0d3af7d9b5e | naolwakoya/python | /factorial.py | 685 | 4.125 | 4 | import math
x = int(input("Please Enter a Number: "))
#recursion
def factorial (x):
if x < 2:
return 1
else:
return (x * factorial(x-1))
#iteration
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
def factorial(p):
if p == 0:
return 1
else:
return p * factorial(p-1)
x = dict ()
def cachedfactorial(num):
#if the number is in key we return to the value
if num in x:
return x[num]
elif num == 0 or num == 1:
#i assume that the number >=1 but just in case the number is zero
return 1
else:
x[num] = num*cachedfactorial(num -1)
return x[num]
print(factorial(x))
| true |
05bf4280a7750cf207609ae63ed15f1cee96843f | jkfer/Codewars | /logical_calculator.py | 1,602 | 4.40625 | 4 | """
Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50.
Links referring to logical operations: AND, OR and XOR.
You should begin at the first value, and repeatedly apply the logical operation across the remaining elements in the array sequentially.
First Example:
Input: true, true, false, operator: AND
Steps: true AND true -> true, true AND false -> false
Output: false
Second Example:
Input: true, true, false, operator: OR
Steps: true OR true -> true, true OR false -> true
Output: true
Third Example:
Input: true, true, false, operator: XOR
Steps: true XOR true -> false, false XOR false -> false
Output: false
"""
from collections import Counter
def logical_calc(array, op):
if op == "AND":
return False if False in array else True
elif op == "OR":
return True if True in array else False
else:
# op == "XOR"
if len(array) == 1:
return array[0]
else:
stack = []
i = 0
while i < len(array):
if stack == []:
if array[i] != array[i+1]:
stack.append(True)
else:
stack.append(False)
i += 1
else:
stack.append(True) if stack[0] != array[i] else stack.append(False)
stack.pop(0)
i += 1
return stack[0]
x = logical_calc([True, False], "XOR")
print(x)
# alternate is use operator module .and_ .or_ feature | true |
b3a0608ad6899ac13e9798ecf4e66c597f688bd1 | jkfer/Codewars | /valid_paranthesis.py | 1,071 | 4.3125 | 4 | """
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
Constraints
0 <= input.length <= 100
Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as parentheses (e.g. [], {}, <>).
"""
def valid_parentheses(string):
stack = []
i = 0
while i < len(string):
if string[i] == "(":
stack.append(string[i])
elif string[i] == ")":
if len(stack) > 0 and stack[-1] == "(":
stack.pop()
else:
stack.append(string[i])
i += 1
#print(stack)
return True if len(stack) == 0 else False
x = valid_parentheses("hi())(")
print(x)
| true |
ad16030fe65ac0005b1d07d56957fb66737f5d72 | yvlian/algorithm | /python/继承.py | 1,460 | 4.40625 | 4 | '''
继承的优点:提升代码的复用程度,避免重复操作。
继承的特点:
1、 同时支持单继承与多继承,当只有一个父类时为单继承,当存在多个父类时为多继承。
2、子类会继承父类所有的属性和方法,子类也可以覆盖父类同名的变量和方法。
3、在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。有别于C#
4、在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数
5、Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。
(先在本类中查找调用的方法,找不到才去基类中找)。
'''
class A(object):
def __init__(self):
print('A')
def display(self):
print('A dis')
class B(object):
def __init__(self):
print('B')
def display(self):
print('B dis')
class C(A,B):
def __init__(self):
# A.__init__(self)
# B.__init__(self)
super(A,self).__init__()
super(B,self).__init__()
print('C')
def dis(self):
A.display(self)
B.display(self)
c = C()
print('++++++++++++++++++++++++++++++++++++++++++')
c.display()
print('++++++++++++++++++++++++++++++++++++++++++')
c.dis()
| false |
da88cd5960d8aeb8fd8a0717714cf88dcd5b707a | Mario97popov/Python-Advanced | /Tuples and Sets excercise/Battle_of_Names.py | 858 | 4.125 | 4 | n = int(input())
even__numbers_set = set()
odd_numbers_set = set()
for current_iteration_count in range(1, n+1):
name = input()
current_sum = sum([ord(el) for el in name]) // current_iteration_count
if current_sum % 2 == 0:
even__numbers_set.add(current_sum)
else:
odd_numbers_set.add(current_sum)
sum_evens = sum(even__numbers_set)
sum_odd = sum(odd_numbers_set)
if sum_evens == sum_odd:
modified_set = [str(el) for el in even__numbers_set.union(odd_numbers_set)]
print(f"{', '.join(modified_set)}")
elif sum_odd > sum_evens:
modified_set = [str(el) for el in odd_numbers_set.difference(even__numbers_set)]
print(f"{', '.join(modified_set)}")
else:
modified_set = [str(el) for el in even__numbers_set.symmetric_difference(odd_numbers_set)]
print(f"{', '.join(modified_set)}")
| false |
f6d7508e322f3248106378483dd377e9ee7ac9e8 | YaserMarey/algos_catalog | /dynamic_programming/count_factors_sets.py | 1,410 | 4.15625 | 4 | # Given a number 'n'
# Count how many possible ways there are to express 'n' as the sum of 1, 3, or 4.
# Notice that {1,2} and {2,1} are two methods and not counted as one
# Pattern Fibonacci Number
def CFS(Number):
dp = [0 for _ in range(Number + 1)]
dp[0] = 1 # if number = 0 then there is only set of factors which the empty set
dp[1] = 1 # if number = 1 then there is only set of factors {1}
dp[2] = 1 # if number = 2 then there is only set of factors {1,1}
dp[3] = 2 # if number = 2 then there is only set of factors {1,1,1} & {3}
# Now starting from third step, until the end we calculate the number of possible sets of steps
# by summing the count of the possible sets of steps
for i in range(4, Number + 1):
dp[i] = dp[i - 1] + dp[i - 3] + dp[i - 4]
return dp[Number]
def main():
Number = 4
print(" Number {0}, possible factors 1,3,4 , Test case {1} "
"since it has calculated possible set of factors to {2} {3}"
.format(Number, 'Pass' if CFS(Number) == 4 else 'Fail', CFS(Number), ' and it is 4'))
Number = 6
print(" Number {0}, possible factors 1,3,4 , Test case {1} "
"since it has calculated possible set of factors to {2} {3}"
.format(Number, 'Pass' if CFS(Number) == 9 else 'Fail', CFS(Number), ' and it is 9'))
if __name__ == '__main__':
main()
| true |
5871c7a813bddf1480a681d08b2ee5d1d76c52d7 | YaserMarey/algos_catalog | /dynamic_programming/count_of_possible_way_to_climb_stairs.py | 1,035 | 4.1875 | 4 | # Given a stair with ‘n’ steps, implement a method to count how many
# possible ways are there to reach the top of the staircase,
# given that, at every step you can either take 1 step, 2 steps, or 3 steps.
# Fib Pattern
def CS(S):
T = [0 for i in range(S + 1)]
T[0] = 1
T[1] = 1
T[2] = 2
for i in range(3, S + 1):
T[i] = T[i - 1] + T[i - 2] + T[i - 3]
return T[S]
def main():
S = 3
print("Testcase 1 is {0} for a stairs of {1}, since it is calculated as {2} and it should be {3}"
.format('Pass' if CS(S) == 4 else 'Fail', S, CS(S), '4'))
S = 4
print("Testcase 1 is {0} for a stairs of {1}, since it is calculated as {2} and it should be {3}"
.format('Pass' if CS(S) == 7 else 'Fail', S, CS(S), '7'))
S = 5
print("Testcase 1 is {0} for a stairs of {1}, since it is calculated as {2} and it should be {3}"
.format('Pass' if CS(S) == 13 else 'Fail', S, CS(S), '13'))
if __name__ == '__main__':
main()
| true |
5d671a339e350f8a3c039ed153667496f6f5850c | burnbrigther/py_practice | /ex15_2.py | 687 | 4.46875 | 4 | # imports the argv feature from the sys package
from sys import argv
# Takes input values from argv and squishes them together (these are the two command line items)
# then unpacks two arguments sent to argv and assigns them to script and filename
script, filename = argv
# Takes the value from the command line argument (filename), open reads what's in filename
# and assigns the value to the variable txt
txt = open(filename)
# Print the string and value of the variable substitution given from filename above.
print "Here's your file %r:" % filename
print txt.read()
print "Here is your file again:"
file_again = open(filename)
txt_again = open(file_again)
print txt_again.read() | true |
f65244692ce1cdcb5357529ee11fb9bb344f4ae9 | saranya258/python | /3.py | 250 | 4.1875 | 4 | char=input()
if char.isalpha():
if(char=='A'or char=='E'or char=='I'or char=='O'or char=='U'or char=='a'or char=='e'or char=='i'or char=='o'or char=='u'):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
| false |
978a2fdf4c8dd6ec10b53d88591c18b452ec29ca | OluchiC/PythonLab1 | /Lab1.py | 925 | 4.21875 | 4 | sentence = 'I can’t wait to get to School_Name! Love the idea of meeting new Noun and making new Noun! I know that when Number years pass, I will be Age and I will have a degree in Profession. I hope to make my family proud! Am I done with this MadLib Yet?: Boolean.'
school_name = input('What\'s the school name?')
meeting = input('What\'s the thing you\'re meeting at school?')
making = input('What\'s the thing you\'re making at school?')
number = str(input('What\'s the number?'))
age = str(input('What\'s the Age?'))
dream = input('What\'s you\'r dream profession?')
decision = str(input('What\'s Are you done (True/False)?'))
print('I can’t wait to get to ',school_name,'! Love the idea of meeting new ',meeting,' and making new ',making,'! I know that when ',number,' years pass, I will be ',age,' and I will have a degree in ',dream,'. I hope to make my family proud! Am I done with this MadLib Yet?:',decision) | true |
9bf71c7546e14fcade018ff905880acd633547e9 | rainakdy1009/Prog11 | /dragon games.py | 2,525 | 4.21875 | 4 | import random
import time
def displayIntro(): #Explain the situation
print('''You are in a land full of dragons. In front of you,
you see two caves. In one cave, the dragon is friendly
and will share his treasure with you. The other dragon
is greedy and hungry, and will eat you on sight.''')
print()
def chooseWay(): #Choose one among 2 choices (Choose the way you'll go)
way = ''
while way != '1' and way != '2':
print('Which way do you want to choose? (1 or 2)')
way = input()
return way
def checkWay (chosenWay): #It checks the way you chose
print('You are walking down the street...')
time.sleep(2)
print('Now you can see the door of the entrance...')
time.sleep(2)
print('You are trying to open the door...')
time.sleep(2)
GoodWay = random.randint (1, 2)
if chosenWay == str(GoodWay): #First option: The door doesn't open
print('Oh No! The door is not open!')
playAgain = input('Do you want to play again? (yes or no): ')
if playAgain == 'yes' or playAgain == 'y':
displayIntro()
wayNumber = chooseWay()
checkWay(wayNumber)
caveNumber = chooseCave()
checkCave(caveNumber)
playAgain = input()
else:
exit()
else: #Second option: The door opens
print('Great! You opened the door!')
def chooseCave(): #Choose one cave among two
cave = ''
while cave != '1' and cave != '2':
print('There are two caves!')
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave): #It checks the cave you chose
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave): #friendly cave
print('Gives you his treasure!')
else:
print('Gobbles you down in one bite!') #You're eaten
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
wayNumber = chooseWay()
checkWay(wayNumber)
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
| true |
ce503a9b5367381fa3774fc0187a506ea0fa3dd6 | rainakdy1009/Prog11 | /Mad libs Dayoung.py | 1,528 | 4.1875 | 4 | noun1 = input("Enter a noun: ")
noun2 = input("Enter a noun: ")
adjective1 = input("Enter an adjective: ")
verb1 = input("Enter a verb: ")
plural_noun1 = input("Enter an plural noun: ")
plural_noun2 = input("Enter an plural noun: ")
number1 = input("Enter a number: ")
adjective2 = input("Enter an adjective: ")
adjective3 = input("Enter an adjective: ")
noun3 = input("Enter a noun: ")
exclamation = input("Enter an exclamation: ")
noun4 = input("Enter a noun: ")
noun5 = input("Enter a noun: ")
noun6 = input("Enter a noun: ")
noun7 = input("Enter a noun: ")
number2 = input("Enter a number: ")
noun8 = input("Enter a noun: ")
noun9 = input("Enter a noun: ")
noun10 = input("Enter a noun: ")
print("Hi! This is " + noun1 + ", speaking to you from the broadcasting " + noun2 + " at the " + adjective1 + " forum. In case you " + verb1 + " in late, the score between the Los Angeles " + plural_noun1 + " and the Boston " + plural_noun2 + " is a squeaker, 141 to " + number1 + ". This has been the most " + adjective2 + " game these " + adjective3 + " eyes have seen in years. First, one team scores a " + noun3 + ", then " + exclamation + "! -the other team comes right back. Okay. Time-out is over. Los Angeles brings in the ball at mid-" + noun4 + ". " + noun5+ " dribbles down the " + noun6 + ", fakes the defender out of his " + noun7 + " and shoots a " + number2 + "-handed shot. It goes right through the " + noun8 + ". He beat the " + noun9 + "! The game is over just as the " + noun10 + " goes off.")
| false |
342ca3b9f92f9adf562bf6fd4b5278305e466255 | jessegtz7/Python-Learning-Files | /Strings.py | 1,018 | 4.15625 | 4 | name = 'Ivan'
age = 29
#**Concateante**
'''
print('His name is ' + name + ' and he is ' + age) -- this will result as a "TypeError: can only concatenate str (not "int") to str"
age mus be cast in to a str
'''
print('His name is ' + name + ' and he is ' + str(age))
#**String format**
#1.- Arguments by position.
print('His name is {nombre} and he is {edad}'.format(nombre=name, edad=age))
#2.- F-Strings (On Python 3.6+)
print(f'His name is {name} and he is {age}')
#**String methods**
g = 'blue printer'
print(g)
#Capitalize string
print(g.capitalize())
#All Uppercase
print(g.upper())
#All Lower
print(g.lower())
#Swap case
print(g.swapcase())
#Get length
print(len(g))
#Replace
print(g.replace('blue', 'orange'))
#Count
sub = 'p'
print(g.count(sub))
#Starts with
print(g.startswith('printer'))
#Ends with
print(g.endswith('r'))
#Split into a last
print(g.split())
#Find position
print(g.find('e'))
#Is all alphanumeric
print(g.isalpha())
#Is all numeric
print(g.isnumeric())
#Look for the outputs | true |
76ab13972c5734bc324efb8b53482705ae990746 | irtefa/bst | /simple_bst.py | 1,142 | 4.1875 | 4 | from abstract_bst import AbstractBst
class SimpleBst(AbstractBst):
# A simple compare method for integers
# @given_val: The value we are inserting or looking for
# @current_val: Value at the current node in our traversal
# returns an integer where
# -1: given_val is less than current_val
# 1: given_val is greater than current_val
# 0: given_val and current_val are equal
def compare(self, given_val, current_val):
if given_val < current_val:
return -1
elif given_val > current_val:
return 1
return 0
if __name__ == "__main__":
simple_bst = SimpleBst()
root = simple_bst.insert(None, 10)
for i in [5, 15, 1, 7, 12, 20]:
simple_bst.insert(root, i)
print "A balanced tree:"
simple_bst.level_order(root)
root = simple_bst.insert(None, 10)
insert_these = [20, 5, 15, 22, 1, 7, 6, 23, 25, 30]
for i in insert_these:
simple_bst.insert(root, i)
print "A sparse tree which is heavier on the right:"
simple_bst.level_order(root)
root = simple_bst.insert(None, 15)
for i in [12,11,10,9,8,1]:
simple_bst.insert(root, i)
print "A sparse tree which is heavier on the left:"
simple_bst.level_order(root)
| true |
c1ad1d4d22f1edfe5bd439118e7c79fc67d7567d | romanticair/python | /basis/Boston-University-Files/AllAnswer/Assignment_9_Answer/a3_task1.py | 2,967 | 4.125 | 4 | # Descriptive Statistice
# Mission 1.
def mean(values):
# Take as a parameter a list of numbers, calculates4
# and returns the mean of those values
sumValues = 0
for value in values:
sumValues += value
return sumValues / len(values)
# Mission 2.
def variance(values):
# Take as a parameter a list of numbers, calculated
# and returns the population variance of the values
# in the list. which was defined as :
# o² = (1 / N) * ∑(Xi - u)²
u = mean(values)
deviation = 0
for value in values:
deviation += (value - u) ** 2
return deviation / len(values)
# Mission 3.
def stdev(values):
# Takes as parameter a list of numbers, calculates
# and returns the popution standard deviation of the
# values in the list, which was the square-root of the
# population variance.
return variance(values) ** 0.5
# Mission 4.
def covariance(x, y):
# Takes as parameters two lists of values, calculates
# and returns the population covariance for those two
# list, which was defined as :
# Oxy = (1 / N) * ∑(Xi - Ux)(Yi - Uy)
assert len(x) == len(y), print("Two lists length is'nt equal")
Ux = mean(x)
Uy = mean(y)
twoDeviation = 0
for i in range(len(x)):
twoDeviation += (x[i] - Ux) * (y[i] - Uy)
return twoDeviation / len(x)
# Mission 5.
def correlation(x, y):
# Takes as parameters two lists of values,calculates
# and returns the correlation coefficient between
# these data series, which was defined as:
# Pxy = Oxy / (Ox * Oy)
Ox = stdev(x)
Oy = stdev(y)
Oxy = covariance(x, y)
return Oxy / (Ox * Oy)
# Mission 6.
def rsq(x, y):
# Takes as parameters two lists of values,calculates
# and returns the square of the coefficient between
# those two data series, which is a measure of the
# goodness of fit measure to explain variation in
# y as a function of variation of x
return correlation(x, y) ** 2
# Mission 7
def simple_regression(x, y):
# Take as parameters two lists of values, calculate
# the regreesion coefficients between these data series,
# and return a list containing two values: the intercept
# and regression coefficients, A and B
# Bxy = Oxy / Ox², Axy = Uy - Bxy * Ux
Oxy = covariance(x, y)
Ox = stdev(x)
Oy = stdev(y)
Ux = mean(x)
Uy = mean(y)
Bxy = Oxy / (Ox ** 2)
Axy = Uy - Bxy * Ux
return [Axy, Bxy]
def Test():
x = [4, 4, 3, 6, 7]
y = [6, 7, 5, 10, 12]
print(mean(x))
print(variance(x))
print(stdev(x))
print(covariance(x, y))
print(correlation(x, y))
print(correlation(list(range(10)), list(range(10, 0, -1))))
print(rsq(x, y))
print(simple_regression(x, y))
"""
Test :
import random
a = list(range(30))
b = list(range(30))
random.shuffle(a)
random.shuffle(b)
print(correlation(a, b))
print(rsq(a, b))
"""
| true |
5bba7d2cf4162e8cb4be68b0eec0c2c698843073 | ivenabc/algorithm_examples | /basic/queue.py | 808 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Queue
# 先进先出队列(FIFO)
class Queue(object):
def __init__(self):
self.__list = []
# 添加一个元素
def en_queue(self, item):
self.__list.append(item)
# 删除最近添加的元素
def de_queue(self):
self.__list.pop()
def is_empty(self):
return bool(self.__list)
def size(self):
return len(self.__list)
def __iter__(self):
self.__iter_index = 0
return self
def __next__(self):
if len(self.__list) <= self.__iter_index:
raise StopIteration
else:
value = self.__list[self.__iter_index]
self.__iter_index += 1
return value
if __name__ == '__main__':
pass | false |
dff8367263ee46866a30dd2fcb8e241d07968d21 | chsclarke/Python-Algorithms-and-Data-Structures | /coding_challenge_review/array_practice.py | 885 | 4.28125 | 4 |
def mergeSorted(arr1, arr2):
#code to merge two sorted arrays
sortedArr = [None] * (len(arr1) + len(arr2))
i = 0
j = 0
k = 0
#iterate through both list and insert the lower of the two
while(i < len(arr1) and j < len(arr2)):
# <= allows function to support duplicate values
if (arr1[i] <= arr2[j]):
sortedArr[k] = arr1[i]
i += 1
k += 1
else:
sortedArr[k] = arr2[j]
j += 1
k += 1
#merge the leftovers of the larger list
while i < len(arr1):
sortedArr[k] = arr1[i]
i += 1
k += 1
while j < len(arr2):
sortedArr[k] = arr2[j]
j += 1
k += 1
return sortedArr
if __name__ == '__main__':
arr1 = [1,3,5,7,9]
arr2 = [2,4,6,7,7,8,10,12,13,14]
print(mergeSorted(arr1,arr2))
| true |
589ff4948bafda92c5f6007c693dd42b4ec5853c | Abel237/automate-boring-stuffs | /automate_boring_stuffs/automate.py | 1,384 | 4.15625 | 4 | # This program says hello and asks for my name.
# print('Hello, world!')
# print('What is your name?') # ask for their name
# myName = input()
# print('It is good to meet you, ' + myName)
# print('The length of your name is:')
# print(len(myName))
# print('What is your age?') # ask for their age
# myAge = input()
# print('You will be ' + str(int(myAge) + 1) + ' in a year.')
# print(int(99.99))
# name = input("what is your name:")
# age = int(input("How old are you?: "))
# if name == 'Alice':
# print('Hi, Alice.')
# elif age < 12:
# print('You are not Alice, kiddo.')
# elif age > 2000:
# print('Unlike you, Alice is not an undead, immortal vampire.')
# elif age > 100:
# print('You are not Alice, grannie.')
# spam = 0
# while spam < 5:
# print('hi', spam, '')
# spam += 1
# name = ''
# while name != 'your name':
# print('Please type your name.')
# name = input()
# if name == 'your name':
# break
# print('Thank you!')
# name = ''
# while True:
# print('Who are you?')
# name = input()
# if name != 'Joe':
# continue
# print('hello Joe! What is your password? it is a fish')
# password = input()
# if password == 'swordfish':
# break
# print('acces granted.')
total = 0
for num in range(101):
total = total + num
print(total)
| true |
db31469c2a0a7810db6d65c47229d489188687db | evgeniikotliarov/python_example | /method_user_add.py | 1,161 | 4.21875 | 4 | # pizza = ['pipperoni', 'chilli', 'mozarella']
# print(pizza)
# for piz in pizza:
# print(piz + " I like it")
#
# for pis in pizza:
# print("Do you like " + pis.title() + ".\n")
# print("Bla bla bla")
#
# for value in range(1,21):
# print(value)
#
# for value in range(1,9):
# print(value)
#
# numbers = list(range(1,6))
# print(numbers)
#
# even_number = list(range(0,21,5))
# print(even_number)
#
# squares = []
# for value in range(1,10):
# squar = value**2
# squares.append(squar)
# print(squares)
#
# squares_1 = []
# for value in range(1,11):
# squares_1.append(value**3)
# print(squares_1)
# nymbers = list(range(1, 1000001))
# for value in nymbers:
# print(value)
# numbers_1 = list(range(1,1000001))
# a = min(numbers_1)
# b = max(numbers_1)
# c = sum(numbers_1)
# print(b)
# print(a)
# print(c)
#
# numbers = list(range(-20, 0))
# for count in numbers:
# print(count)
# numb = list(range(3,31,3))
# for value in numb:
# print(value)
squar = []
numbers = list(range(1,11))
for value in numbers:
val = value**3
squar.append(val)
print(squar)
squares = [value**3 for value in range(1,11)]
print(squares) | false |
d8326d7dd0f2ea05957104c482bacf2776968aff | optionalg/HackerRank-8 | /time_conversion.py | 987 | 4.125 | 4 | '''
Source: https://www.hackerrank.com/challenges/time-conversion
Sample input:
07:05:45PM
Sample output:
19:05:45
'''
#!/bin/python
import sys
def timeConversion(s):
meridian = s[-2]
time = [int(i) for i in s[:-2].split(':')] # Converting each time unit to integer and obtaining
# each unit by splitting it using ':'
hour = time[0]
minute = time[1]
second = time[2]
if meridian == 'P':
if hour == 12:
final_time = str(hour) + ':'
else:
hour += 12
final_time = str(hour) + ':'
else:
if hour == 12:
hour -= hour
final_time = '0' + str(hour) + ':'
else:
final_time = '0' + str(hour) + ':'
if minute < 10:
minute = '0' + str(minute)
if second < 10:
second = '0' + str(second)
final_time += str(minute) + ':' + str(second)
return final_time
s = raw_input().strip()
result = timeConversion(s)
print(result)
| true |
9bc2d5011ccdacbf7e172ab4c0245c8b5f437f3f | harrowschool/intro-to-python | /lesson3/task2.py | 620 | 4.3125 | 4 | # Task 2a
# Add comments to the code to explain:
# What will be output when the code is run?
# In what circumstances would the other output message be produced
num1 = 42
if num1 == 42:
print("You have discovered the meaning of life!")
else:
print("Sorry, you have failed to discover the meaning of life!")
# Task 2b
# Add to the code below so that it outputs 'You're not Dave!' if the user does not input 'Dave'
name = input("What’s your name?")
if name == "Dave":
print("Hello Dave")
#EXTRA CHALLENGE - Adapt the code so that it works in the same way but uses a not equal to Boolean operator.
| true |
a0c0c94d964d43a60a5473386310f66e3f2a7e5c | TokyGhoul/Coursera | /Week2/HW8.py | 538 | 4.21875 | 4 | '''
Шоколадка имеет вид прямоугольника, разделенного на n×m долек.
Шоколадку можно один раз разломить по прямой на две части.
Определите, можно ли таким образом отломить от шоколадки
ровно k долек.
'''
num1 = int(input())
num2 = int(input())
num3 = int(input())
if (num3 <= num1 * num2) and \
(num3 % num1 == 0 or num3 % num2 == 0):
print('Yes')
else:
print('No')
| false |
cbea431354921c463d0c4ebf4f923361203ba3b3 | TokyGhoul/Coursera | /Week2/HW14.py | 536 | 4.40625 | 4 | '''
Даны три целых числа. Определите, сколько среди них совпадающих.
Программа должна вывести одно из чисел: 3
(если все совпадают), 2 (если два совпадает) или 0 (если все числа различны).
'''
num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 == num2 or num2 == num3 or num1 == num3:
if num1 == num2 == num3:
print(3)
else:
print(2)
else:
print(0)
| false |
fcd89523ec988e761b4cc22611dd69548b449951 | gitghought/python1 | /day3/mendswith.py | 382 | 4.125 | 4 |
mstr = "u can u up, no can no 13 B"
#查看实现准备好的字符串是否以‘B’字符结尾
#该函数的返回值是布尔值
mbool = mstr.endswith("B")
print(mbool)
#查看实现准备好的字符串是否以‘B’字符结尾
#该方法指定了查找的范围,3-末尾
#该函数的返回值是布尔值
mbool = mstr.endswith("B", 3, mstr.__len__())
print(mbool)
| false |
9c6a978c2595de1301aef97991389bb02cb9855f | skipdev/python-work | /assignment-work/jedi.py | 554 | 4.15625 | 4 | def jedi():
#Display the message "Have you fear in your heart?"
print("Have you fear in your heart?")
#Read in the user’s string.
response = input(str())
#The program will then decide if the user can be a Jedi or not, based on their response.
if response.lower() == "yes":
print("Fear is the path to the dark side. You cannot be a Jedi apprentice.")
elif response.lower() == "no":
print("The force is strong in you. You may be a Jedi apprentice.")
else:
print("You need to decide... yes or no?")
jedi()
jedi() | true |
b76cdc2e8a3bf58989bd280c7f3d82810c67f153 | skipdev/python-work | /assignment-work/jumanji.py | 543 | 4.28125 | 4 | number = 0
#Display the message "How many zones must I cross?"
print("How many zones must I cross?")
#Read in the user’s whole number.
number = int(input())
#Display the message "Crossing zones...".
print("Crossing zones...")
#Display all the numbers from the user's whole number to 1 in the form "…crossed zone [number]" where [number] is the zone number.
while int(number) > 0:
print("... crossed zone" , number)
number = int(number) - 1
#Display the message "Crossed all zones. Jumanji!"
print("Crossed all zones. Jumanji!")
| true |
072bac7e650722c717a17abfa2bc288fde93e0f2 | skipdev/python-work | /work/repeating-work.py | 219 | 4.25 | 4 | #Get the user's name
name = str(input("Please enter your name: "))
#Find the number of characters in the name (x)
x = len(name)
#Use that number to print the name x amount of times
for count in range(x):
print(name) | true |
04a15af1fcb1ffccb529a4321c499c5bd1b88d04 | skipdev/python-work | /work/odd-even.py | 238 | 4.375 | 4 | #Asking for a whole number
number = (int(input("Please enter a whole number: ")))
#Is the number even or odd?
evenorodd = number % 2
#Display a message
if evenorodd == 0:
print("The number is even")
else:
print("The number is odd")
| true |
f2b76267a6fcd9f60e5c1c4745a8362ed3c9bd27 | MrT3313/Algo-Prep | /random/three_largest_numbers/✅ three_largest_numbers.py | 1,413 | 4.34375 | 4 | # - ! - RUNTIME ANALYSIS - ! - #
## Time Complexity: O(n)
## Space Complexity: O(1)
# - ! - START CODE - ! - #
# - 1 - # Define Main Function
def FIND_three_largest_numbers(array):
# 1.1: Create data structure to hold final array
finalResult = [None, None, None]
# 1.2: Loop through each item in the check array and all helper method
for num in array:
updateLargest(finalResult, num)
print(finalResult)
# 1.3: Return final array
return finalResult
# - 2 - # Define Update Helper Function
def updateLargest(finalResult, num):
# 2.1: Check Largest in finalResult
if finalResult[2] is None or num > finalResult[2]:
# 2.1.1 Shift is needed
shift_and_update(finalResult, num, 2)
# 2.2: Check Middle in finalResult
elif finalResult[1] is None or num > finalResult[1]:
# 2.2.1 Shift is needed
shift_and_update(finalResult, num, 1)
# 2.3: Check First in finalResult
elif finalResult[0] is None or num > finalResult[0]:
#2.3.1 Shift is needed
shift_and_update(finalResult, num, 0)
# - 3 - # Define SHIFT AND UPDATE helper function
def shift_and_update(array, num, idx):
for i in range(idx + 1):
if i == idx:
array[i] = num
else:
array[i] = array[i + 1]
# FIND_three_largest_numbers([12,5,7,5,35,187,45,3])
FIND_three_largest_numbers([10,5,9,10,12])
| true |
3c84466bc01a6b2a5ddbd595fbb6dcb107b40e74 | MrT3313/Algo-Prep | /⭐️ Favorites ⭐️/Sort/⭐️ bubbleSort/✅ bubbleSort.py | 590 | 4.21875 | 4 |
def bubbleSort(array):
isSorted = False
counter = 0 # @ each iteration you know the last num is in correct position
while not isSorted:
isSorted = True
# -1 : is to prevent checking w/ out of bounds
# counter : makes a shorter array each iteration
for i in range(len(array) - 1 - counter):
if array[i] > array[i + 1]:
swap(i, i + 1, array)
isSorted = False
counter += 1
return array
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
print(bubbleSort([8,5,2,9,5,6,3])) | true |
71dc3f9110ad21660a526284e6b58b8834729e7a | ashNOLOGY/pytek | /Chapter_3/ash_ch3_coinFlipGame.py | 799 | 4.25 | 4 | '''
NCC
Chapter 3
The Coin Flip Game
Project: PyTek
Code by: ashNOLOGY
'''
import math
import random
#Name of the Game
print("\nThe Coin Flip Game"
"\n------------------\n")
#Set up the Heads & Tails as 0
h = 0
t = 0
#ask user how many flips should it do
howMany = int(input("How many flips? "))
#Set up the random FLIPPER to flip 100 times
#While Loop for the flips?
i = 0
while (i < howMany):
f = random.randint(1,2) #The flip
# If loop for the Heads & Tails?
# If its 1 its/add to Heads
# If its 2 its/add Tails
if f == 1:
h = h + 1
else:
t = t + 1
i = i +1
#print(f)
#Display the result for H & T
print("\nHeads: ", h)
print("Tails: ", t)
#ENTER to Exit
input("\nENTER to EXIT")
| true |
a494320f224a78e13f565b69e7aebd406709c979 | RanabhatMilan/SimplePythonProjects | /GussingNum/guessing.py | 880 | 4.25 | 4 | # This is a simple guessing game.
# At first we import a inbuilt library to use a function to generate some random numbers
import random
def guess_num(total):
number = random.randint(1, 10)
num = int(input("Guess a number between 1 to 10: "))
while num != number:
if num > number:
num = int(input("Guess a number lower than "+str(num)+"! Try Again: "))
if num < number:
num = int(input("Guess a number higher than "+str(num)+"! Try Again: "))
if num == number:
yn = input("Ohh..Your guess is Correct. \nYou WIN. Your total score is "+str(total)+". Do you want to play Again?[y/n] ")
return yn
name = input("What's your name? ")
yn = input("Hello "+name+"!! Do you want to play some game?[y/n]")
total = 10
while yn == 'y':
yn = guess_num(total)
total += 10
if yn == 'n':
print ("Okaay.. Cool")
| true |
f8a581b6c8a2f6c71e332e0e749dc8ce9988159d | mfleming1290/My-written-code | /Python/testing.py | 2,404 | 4.25 | 4 | # first_name = "Zen"
# last_name = "Coder"
# print "My name is {} {}".format(first_name, last_name)
# name = "Zen"
# age = 15
# print "My name is " + name + age
# name = "Zen"
# print "My name is", name, "i am ", 24
# hw = "hello %s" % 'world'
# print hw
# my_string = 'hello world'
# print my_string.capitalize()
#
# my_string = 'Hello WORLD'
# print my_string.lower()
# fruits = ['apple', 'banna', 'orange', 'strawberry']
# vegetables = ['lettuce', 'cucumber', 'carrots']
# fruits_and_vegatables = fruits + vegetables
# print fruits_and_vegatables
# salad = 3 * vegetables
# print salad
# drawer = ['documents', 'envelopes', 'pens']
# print drawer[2]
# x = [1,2,3,4,5]
# x.remove(3)
# print x
# y = [10,11,12,13,14]
# y.pop(4)
# print y
# x = [100,'kiwi',99,4,'apple',2,'bannana',5,-3,'orange'];
# x.sort()
# print x
# x = [99,4,2,5,-3];
# print x[1:2]
# my_list = [0, '']
# print any(my_list)
# list = [4, 'dog', 99, ['list', 'inside', 'another'], 'hello world']
# for elements in list:
# print elements
# count = 0
# while count < 5:
# print count
# count += 1
# for val in "string":
# if val == "t":
# break
# print(val)
# for val in "string":
# if val == "i":
# continue
# print(val)
# x = 3
# y = x
# while y > 0:
# print y
# y = y - 1
# else:
# print "Final else statement"
# def add(a,b):
# x = a + b
# return x
#
# result = add(3,5)
# print result
# print add(3,5)
# print 4 > 3
# dog = ("Canis Familiaris", "dog", "carnivore", 12)
# dog = dog + ("domestic",)
# dog = dog[:3] + ("man's best friend",) + dog[4:]
#
# print dog
# value = ("Michael", "Instructor", "Coding Dojo")
# (name, position, company) = value #tuple unpacking
# print name
# print position
# print company
#
# num = (1, 5, 7, 3, 8)
# for index, item in enumerate(num):
# print(str(index)+" = "+str(item))
# import math
# r = (2)
# def get_circle_area(r):
# #Return (circumference, area) of a circle of radius r
# c = 2 * math.pi * r
# a = math.pi * r * r
# print (c, a)
# get_circle_area(r)
weekend = {"Sun": "Sunday", "Mon": "Monday"} #literal notation
capitals = {} #create an empty dictionary then add values
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"
for data in capitals:
print data
for val in capitals.itervalues():
print val
for key,data in capitals.iteritems():
print key, " = ", data
| false |
cf64c6a26c86f5af34c39f617763757d4ab270ed | bushki/python-tutorial | /tuples_sets.py | 1,801 | 4.53125 | 5 | # tuple - collection, unchangeable, allows dupes
'''
When to use tuples vs list?
Apart from tuples being immutable there is also a semantic distinction that should guide their usage.
Tuples are heterogeneous data structures (i.e., their entries have different meanings),
while lists are homogeneous sequences. Tuples have structure, lists have order.
Using this distinction makes code more explicit and understandable.
One example would be pairs of page and line number to reference locations in a book, e.g.:
my_location = (42, 11) # page number, line number
https://stackoverflow.com/questions/626759/whats-the-difference-between-lists-and-tuples
'''
# create tuple - use parenthese
fruits = ('apples', 'oranges', 'grapes')
print (type(fruits))
print (fruits)
# if only one item and no trailing comma, type will be string
test_tuple = ('orange')
print (test_tuple, type(test_tuple))
# always use trailing comma if you want to make tuple with single item
test_tuple = ('orange',)
print (test_tuple, type(test_tuple))
# get a value - zero-based
print(fruits[1])
# cannot change value
# fruits[0] = 'something else' # TypeError: 'tuple' object does not support item assignment
# delete entire tuple
del test_tuple
#print (test_tuple)
# length
print(len(fruits))
# SETS - collection of unordered and unidexed. No dupes.
#create set (use curly braces)
fruits_set = {'Apples', 'Oranges', 'Mango'}
# check if element is in set
print ('Apples' in fruits_set)
# add to set
fruits_set.add('grape')
print(fruits_set)
# add dupe - will not add and no error
fruits_set.add('grape')
print(fruits_set)
# remove from set (will throw error if element not found)
fruits_set.remove('grape')
print(fruits_set)
# clear set
fruits_set.clear()
print(fruits_set)
# delete set
del fruits_set
| true |
350b1239f1f389a5181a11f3b9fa1c3ed74fa6e6 | victor-erazo/ciclo_python | /Mision-TIC-GRUPO-09-master(16-06-21)/semana 3/ejercicio5.py | 1,813 | 4.1875 | 4 | '''
for x in range(0,10):
print('Valor de x : ', x)
'''
'''
for j in range(0,10,2):
print('La iteracion j : '+ str(j))
'''
'''
for k in range(10,0,-1):
print('La iteracion decremental k es : ' + str(k))
'''
'''
oracion = 'Mary entiende muy bien python'
frases = oracion.split()
print('la oracion analizar es : ',oracion,'\n')
for palabra in range(len(frases)):
print('palabra : {} en la posicion es : {}'.format(frases[palabra],palabra))
'''
'''
oracion = 'Mary entiende muy bien python'
frases = oracion.split()
print('la oracion analizar es : ',oracion,'\n')
for palabra in frases:
print('palabra : {}'.format(palabra))
'''
'''
midic = dict() # midic = {}
lista = list() # lista = []
datos_basicos = {
'nombres': 'Leonardo Jose',
'apellidos': 'Caballero Garcia',
'cedula': '11009321212',
'fecha_nacimiento': '13-12-1980',
'lugar_nacimiento': 'Bucaramanga',
'nacionalidad': 'Colombiano',
'estado_civil': 'Soltero'
}
print(datos_basicos)
clave = datos_basicos.keys()
# print(clave)
valor = datos_basicos.values()
# print(valor)
cantidad_datos = datos_basicos.items()
print(cantidad_datos,'\n')
'''
'''
for clave_1 in clave:
print(clave_1)
for valor_1 in valor:
print(valor_1)
'''
'''
for cla, val in cantidad_datos:
print(cla,' : ', val)
for datos in cantidad_datos:
print(datos)
'''
'''
frutas = {
'fresa': 'roja',
'limon': 'verde',
'papaya': ' naranja',
'manzana': 'amarilla',
'guayaba': 'rosa'
}
for llave in frutas:
print(llave, ' es el color ', frutas[llave])
'''
db_connection = "127.0.0.1","5432","root","nomina"
for parametros in db_connection:
print(parametros)
else:
print("el comando de postgreSQL es : -h=",db_connection[0],' -p=',db_connection[1],
' -u=',db_connection[2],' -d=',db_connection[3]) | false |
ce183d2eae5e4e129a0145de41efada56256241d | JessicaCoelho21/ASI | /ASI_FP_5/ASI_FP_05_ex4.py | 654 | 4.28125 | 4 | # Semana 5, exercício 4
import re
# Verificar se a inicial de todos os nomes se encontra em letra maiúscula
# e as seguintes em letra minúscula
def upperCaseName(name):
# Início da linha (^) com letra maíuscula seguido de letras minúsculas
# Seguido do espaço (/s), depois novamente letra maíuscula seguido de letras minúsculas
# *$ significa que cada caracter, do início ao fim do texto, pode aparecer 0 ou mais vezes
pattern = re.compile(r'^[A-Z][a-z]+(\s[A-Z][a-z]+)*$')
if pattern.match(name):
print("O nome %s obedece ao padrão" % name)
else:
print("O nome %s não obedece ao padrão" % name)
| false |
757c5b54164ebe279401ef9cb63e920715352258 | xatrarana/python-learning | /PYTHON programming/3.dictonary in python/dict problemss.py | 269 | 4.15625 | 4 | ## i have to get the sentance as input form the user and cout the user input..
#sentence -> input,key->word, value->length of the word
sent=input("Enter the sentence")
words=sent.split(" ")
count_words={words:len(words) for words in words}
print(count_words)
| true |
635385f3da34913511846c5f0010347b260aa5fa | houckao/grade-calculator-python | /grades_calculator.py | 1,598 | 4.15625 | 4 | """
This is a library of functions designed to be useful in a
variety of different types of grade calculations.
"""
# import support for type hinting the functions
from typing import List, Dict
def average(grades: List[float]) -> float:
"""Calculates the average of an array of grades, rounded to 2 decimal places
Args:
grades (List[float]): An array of number grades
Returns:
float: The average of the grades
"""
sum = 0
for x in grades:
sum = sum + x
average = sum/len(grades)
return round(average,2)
def drop_lowest(grades: List[float]) -> List[float]:
"""Drops the lowest number and returns the pruned collection
Args:
grades (List[float]): An array of number grades
Returns:
List[float]: The pruned list of grades
"""
new_grades = grades.copy()
new_grades.remove(min(new_grades))
return new_grades
def calculate_gpa(grades: List[str], weights: Dict[str, float]) -> float:
"""
Takes a list of letter grades, and a dictionary that provides
the relative weights of those letter grades in GPA format. It
calculates a GPA based on the number of grades and their weights
rounded to two decimal places.
Args:
grades (List[str]): A list of letter grades, e.g. A, B+, C, A-, etc.
weights (Dict[str, float]): The dictionary equating letter grades to their weight
Returns:
float: The calculated GPA
"""
total = 0
for x in grades:
total += weights[x]
gpa = total/len(grades)
gpa = round(gpa, 2)
return gpa
| true |
c4e289b3c851d27b251685e6ecce708b590c519e | qihong007/leetcode | /2020_04_16.py | 2,169 | 4.125 | 4 | '''
一个有名的按摩师会收到源源不断的预约请求,每个预约都可以选择接或不接。在每次预约服务之间要有休息时间,因此她不能接受相邻的预约。给定一个预约请求序列,替按摩师找到最优的预约集合(总预约时间最长),返回总的分钟数。
注意:本题相对原题稍作改动
示例 1:
输入: [1,2,3,1]
输出: 4
解释: 选择 1 号预约和 3 号预约,总时长 = 1 + 3 = 4。
示例 2:
输入: [2,7,9,3,1]
输出: 12
解释: 选择 1 号预约、 3 号预约和 5 号预约,总时长 = 2 + 9 + 1 = 12。
示例 3:
输入: [2,1,4,5,3,1,1,3]
输出: 12
解释: 选择 1 号预约、 3 号预约、 5 号预约和 8 号预约,总时长 = 2 + 4 + 3 + 3 = 12。
执行用时 :20 ms, 在所有 Python 提交中击败了71.50% 的用户
内存消耗 :12.7 MB, 在所有 Python 提交中击败了100.00%的用户
'''
class Solution(object):
#逆向动态规划,从后往前,最后一个数为n,则累加时间为array[n];倒数第二个数为n-1,则累加时间为array[n]
#倒数第三个数为n-2,则累加时间为array[n-2]+dp[n-2个往前推最大的一个值]
def massage(self, nums):
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
dp = []
result = 0
for i in range(0, len(nums)):
dp.append(0)
for i in range(len(nums)-1, -1, -1):
if i == len(nums)-1:
dp[i] = nums[i]
elif i == len(nums)-2:
dp[i] = nums[i]
else:
maxnum = 0
index = i
while index+2 < len(nums):
if dp[index+2] > maxnum:
maxnum = dp[index+2]
index = index + 1
dp[i] = maxnum + nums[i]
if dp[i] > result:
result = dp[i]
return result
| false |
7bda8a77649f5832e637e38a7f7564cc0b2fd4d1 | qihong007/leetcode | /2020_03_04.py | 1,138 | 4.3125 | 4 | '''
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).
Example 1:
Input: "aabcccccaaa"
Output: "a2b1c5a3"
Example 2:
Input: "abbccd"
Output: "abbccd"
Explanation:
The compressed string is "a1b2c2d1", which is longer than the original string.
执行用时:212 ms
内存消耗:14.4 MB
'''
class Solution(object):
def compressString(self, S):
if len(S) <= 1:
return S
s = S[0]
num = 1
for i in range(0, len(S)-1):
s0 = S[i]
s1 = S[i+1]
if s0 == s1:
num = num + 1
else:
s = s + str(num) + s1
num = 1
if i+1 == len(S)-1:
s = s + str(num)
if len(S) > len(s):
return s
return S
| true |
3761089895083f5fb8111f5b8db218c81fa86d71 | khushalj/GOOGLE-HASH-CODE-2021 | /pizza.py | 2,318 | 4.1875 | 4 | #!/usr/bin/python3
#Function that prints the solution to send to the judge
def imprimirsolucion(deliveries):
# We print number of shipments
print (len (deliveries))
for between in deliveries:
#We print each shipment generating a string and finally printing it
#First, we put the shipment if it goes to a group of 4, 3 or 2
cad = str (between [0])
# We will go through the list to print which pizzas were in that shipment
for element in between [1:]:
cad = cad + "" + str (element)
#We print the solution
print (cad)
#Main program
def main ():
# We declare variables to read total pizzas and total of each type of equipment
nPizzas = 0
nEq2 = 0
nEq3 = 0
nEq4 = 0
# We read number of pizzas, teams of 2, 3 and 4 members
nPizzas, nEq2, nEq3, nEq4 = map (int, input (). split ())
# We declare a list with the pizzas that we will read
pizzas = []
# We read all the pizzas. We put them in a list each, ignoring the first element
# The reason for ignoring the first element is that it tells us how many ingredients there are, but for
# save space we do not put it and we can always calculate with the "len" function
for _ in range (nPizzas):
pizzas.append (input (). split () [1:])
#List that will contain the result of assigned pizzas
res = []
#As long as there are Pizzas and groups left, I create deliveries
pizzaActual = 0
#We assign pizzas first to groups of 4
while (pizzaActual + 4 <= nPizzas and nEq4> 0):
# Add the result
res.append ([4, pizzaActual, pizzaActual + 1, pizzaActual + 2, pizzaActual + 3])
pizzaActual = pizzaActual + 4
nEq4 = nEq4-1
#Then groups of 3
while (pizzaActual + 3 <= nPizzas and nEq3> 0):
res.append ([3, pizzaActual, pizzaActual + 1, pizzaActual + 2])
pizzaActual = pizzaActual + 3
nEq3 = nEq3-1
#last groups of 2
while (pizzaActual + 2 <= nPizzas and nEq2> 0):
res.append ([2, pizzaActual, pizzaActual + 1])
pizzaActual = pizzaActual + 2
nEq2 = nEq2-1
#print the result of res
imprimirsolucion (res)
# Code to execute initial
main ()
| true |
9a20562783968cda53b51396d3a55fc0072ff9d0 | pouya-mhb/My-Py-projects | /OOP Practice/prac1.py | 1,658 | 4.15625 | 4 | # A class for dog informations
dogsName = []
dogsBreed = []
dogsColor = []
dogsSize = []
dogsInformation = [dogsName, dogsBreed,
dogsColor, dogsSize]
#Create the class
class Dog ():
#methods
# init method for intialization and attributes in ()
def __init__(self, dogBreed, name, dogColor, dogSize):
# self refers to itself (the class)
# sth = self.atrribute
self.dogBreed = dogBreed
self.name=name
self.dogColor=dogColor
self.dogSize=dogSize
'''
def barking (self,sound):
self.sound=sound
print("woof .. woofh ")
'''
n = int(input("How many Dogs ? : "))
for i in range (0,n):
a = input("breed : ")
b = input("name : ")
c = input("dogColor : ")
d = input("size : ")
dogObject = Dog(dogBreed=a, name=b, dogColor=c, dogSize=d)
dogsBreed.append(dogObject.dogBreed)
dogsName.append(dogObject.name)
dogsColor.append(dogObject.dogColor)
dogsSize.append(dogObject.dogSize)
#myDog = Dog(dogBreed='labrador', name='jakie', dogColor='golden', dogSize='big') #objects
#myFriendDog = Dog(dogBreed='huskie', name='jousef',dogColor='balck', dogSize='small')
print(type(Dog))
print("dogsBreed : ", dogsBreed,'\n'
"dogsName : ", dogsName,'\n'
"dogsSize : ", dogsSize,'\n'
"dogsColor : ", dogsColor)
#for i in dogsInformation:
#print(i)
# calling like object.attributes
'''
print("my dog information : " ,myDog.dogBreed,myDog.name,myDog.dogColor,myDog.dogSize)
print("my dad's dog information : ", myDadsDog.dogBreed, myDadsDog.name,
myDadsDog.dogColor, myDadsDog.dogSize) '''
| true |
272ecae5432fdc867ed406d728418733938d6525 | pouya-mhb/My-Py-projects | /PublicProjects/1/tamrin5.py | 432 | 4.25 | 4 | number = int(input("please enter a number : "))
number = 5
k = 2 * number - 2
for i in range(0, number):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print("* ", end="")
print("")
k = number - 2
for i in range(number, -1, -1):
for j in range(k, 0, -1):
print(end=" ")
k = k + 1
for j in range(0, i + 1):
print("* ", end="")
print("") | false |
d779c188dbd38b81d162f126fe2f502e2dd671d6 | adityagrg/Intern | /ques2.py | 234 | 4.3125 | 4 | #program to calculate the no. of words in a file
filename = input("Enter file name : ")
f = open(filename, "r")
noofwords = 0
for line in f:
words = line.split()
noofwords += len(words)
f.close()
print(noofwords) | true |
343677c250f436b5095c72985eadd30da635da00 | Young-Thunder/RANDOMPYTHONCODES | /if.py | 206 | 4.1875 | 4 | #!/usr/bin/python
car = raw_input("Which car do you have")
print "You have a " + car
if car == "BMW":
print "Its is the best"
elif car =="AUDI":
print "It is a good car"
else:
print "UNKNOWN CAR "
| true |
e535d1c452c734ab747fda28d116d4b5fe2f9325 | gia-bartlett/python_practice | /practice_exercises/odd_or_even.py | 431 | 4.375 | 4 |
number = int(input("Please enter a number: ")) # input for number
if number % 2 == 0: # if the number divided by 2 has no remainder
print(f"The number {number} is even!") # then it is even
else:
print(f"The number {number} is odd!") # otherwise, it is odd
''' SOLUTION:
num = input("Enter a number: ")
mod = num % 2
if mod > 0:
print("You picked an odd number.")
else:
print("You picked an even number.")''' | true |
626d8988b97db70d28e03e7e884120410120021a | igor91m/homework_1 | /task_1.py | 438 | 4.1875 | 4 | # Создаем простые переменные
name = input("Введите своё имя: ")
print(f"Hello, {name}")
price = 100
quantity = 50
total_cost = price * quantity
print(f"Цена: {price} , Количество: {quantity}")
print(f"Общая стоймость: {total_cost}")
a = int(input(f"Введите цену: "))
b = int(input(f"Количество: "))
print(f"Общая стоймость = {a * b}")
| false |
03d0df2365d10490641e078569b2164c81009fa2 | malthunayan/python | /functions_task.py | 2,165 | 4.21875 | 4 | print("Hello and welcome to the Python Birthday Calculator!\n")
def check_birthdate(d,m,y):
from datetime import date
if y>date.today().year:
return False
elif y==date.today().year:
if m>date.today().month:
return False
elif m==date.today().month:
if d>date.today().day:
return False
elif d<0:
return False
else:
return True
elif m<0 or d<0 or d>31:
return False
else:
return True
elif y<0 or m>12 or m<0 or d<0 or d>31:
return False
else:
return True
def calculate_age(d,m,y):
from datetime import date
age_year=date.today().year-y
age_month=date.today().month-m
age_day=date.today().day-d
if age_month<0 and age_day<0:
age_year-=1
age_month+=11
if date.today().month==2:
if date.today().year%100==0:
if date.today().year%400==0:
age_day+=29
else:
age_day+=28
elif date.today().year%4==0:
age_day+=29
else:
age_day+=28
elif date.today().month==4 or date.today().month==5 or date.today().month==6 or date.today().month==9 or date.today().month==11:
age_day+=30
else:
age_day+=31
print("Your age is %s years, %s months and %s days."%(age_year,age_month,age_day))
elif age_month<0:
age_year-=1
age_month+=12
print("Your age is %s years, %s months and %s days."%(age_year,age_month,age_day))
elif age_day<0:
age_month-=1
if date.today().month==2:
if date.today().year%100==0:
if date.today().year%400==0:
age_day+=29
else:
age_day+=28
elif date.today().year%4==0:
age_day+=29
else:
age_day+=28
elif date.today().month==4 or date.today().month==5 or date.today().month==6 or date.today().month==9 or date.today().month==11:
age_day+=30
else:
age_day+=31
print("Your age is %s years, %s months and %s days."%(age_year,age_month,age_day))
else:
print("Your age is %s years, %s months and %s days."%(age_year,age_month,age_day))
y=int(input("Enter the YEAR you were born in: "))
m=int(input("Enter the MONTH you were born in as a NUMBER: "))
d=int(input("Enter the DAY you were born in: "))
if check_birthdate(d,m,y)==True:
calculate_age(d,m,y)
else:
print("The birthdate you entered is invalid.") | false |
8596578006399b3095b2a572e3f08aa0789031ba | JavaPhish/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 340 | 4.28125 | 4 | #!/usr/bin/python3
""" Adds 2 integers """
def add_integer(a, b=98):
""" Adds A + B and returns """
if (type(a) is not int and type(a) is not float):
raise TypeError("a must be an integer")
if (type(b) is not int and type(b) is not float):
raise TypeError("b must be an integer")
return (int(a) + int(b))
| true |
a6b0b97119142fff91d2b99dc01c945d5409c799 | JavaPhish/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 873 | 4.125 | 4 | #!/usr/bin/python3
""" AAAAAAHHHHH """
class Square:
""" Square: a class. """
def __init__(self, size=0):
""" Init - init method """
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
self.__size = size
def area(self):
""" area - Returns the area of the square """
return self.__size * self.__size
# getter
def get_size(self):
""" get_size - getter """
return self.__size
# setter
def set_size(self, n_size=0):
""" set_size - setter """
if type(n_size) is not int:
raise TypeError("size must be an integer")
if n_size < 0:
raise ValueError("size must be >= 0")
self.__size = n_size
size = property(get_size, set_size)
| true |
649b70c784a4bebd56897ba1f7b89fc98277a6e8 | OlayinkaAtobiloye/Data-Structures | /Data Structures With OOP/linkedlist.py | 2,391 | 4.3125 | 4 | class Node:
def __init__(self, value, next_=None):
self.value = value
self.next = next_
class LinkedList:
"""A linked list is a linear data structure. It consists of nodes. Each Node has a value and a pointer
to a neighbouring node(i.e it links to it's neighbor) hence the name linked list.
They are used in cases where constant time insertion and deletion are required."""
def __init__(self, head=None):
self.head = head
def insert(self, value, position):
count = 0
current = self.head
while current:
previous = current
current = current.next
count += 1
if count == position:
previous.next = value
value.next = current
break
def append(self, value):
"""takes in the head of the linked list and the value to be appended in the linked list. """
current = self.head
previous = current
if current:
while current:
previous = current
current = current.next
else:
previous.next = value
else:
self.head = value
def remove(self, position):
"""removes element at given position"""
current = self.head
count = 0
if current:
while current:
previous = current
current = current.next
count += 1
if count == position:
previous.next = current.next
break
def pop(self):
"""removes the last element from the linked list. """
current = self.head
previous = current
last = previous
while current:
last = previous
previous = current
current = current.next
else:
last.next = None
def __repr__(self):
"""representation of the linked list"""
x = self.head
a = f'{str(x.value)}'
if x:
while x.next:
x = x.next
a += f"-->{str(x.value)}"
return a
l = LinkedList(Node(6))
l.append(Node(5))
l.append(Node(7))
l.append(Node(10))
l.append(Node(1))
l.append(Node(3))
l.insert(Node(8), 2)
l.append(Node(9))
l.remove(3)
# print(l.head.value)
# print(l.head.next.value)
print(l)
| true |
59c9e4ce10bbfcff84f1d0b23d2938ea98e67783 | motleytech/crackCoding | /RecursionAndDyn/tripleStep.py | 568 | 4.1875 | 4 | '''Count ways to get to nth step, given child can
take 1, 2 or 3 steps at a time'''
# let f(n) be the ways to get to step n, then
# f(n) = f(n-1) + f(n-2) + f(n-3)
def tripleStep(n):
'return number of ways to get to nth step'
if 1 <= n <= 3:
return n
a, b, c = 1, 2, 3
n = n-3
while n > 0:
n -= 1
a, b, c = b, c, (a + b + c)
return c
def test_tripleStep():
'test for tripleStep method'
for x in range(1, 20):
res = tripleStep(x)
print x, res
if __name__ == '__main__':
test_tripleStep()
| true |
0eaabc6474396fc098c038667a838bf486705375 | motleytech/crackCoding | /arraysAndStrings/uniqueCharacters.py | 1,703 | 4.21875 | 4 | '''
determine if a string has all unique characters
1. Solve it.
2. Solve it without using extra storage.
Key idea: Using a dictionary (hashmap / associative array), we simply iterate
over the characters, inserting each new one into the dictionary (or set).
Before inserting a character, we check if it already exists in the dictionary/set.
If it exists, then that character is repeated, and we return False.
If we reach the end of the string while repeating this process, it implies that
all characters are unique (else we would have returned False at some point).
We return True.
'''
def hasUniqueChars(s):
'''
checks if a string is composed of unique characters
(using a set to store seen characters)
'''
existing = set()
for c in s:
if c in existing:
return False
existing.add(c)
return True
def hasUniqueCharsNoBuf(s):
'''
checks if a string consists of unique characters
This version uses no extra storage.
Works by iterating over characters and comparing each character with
all the others to make sure none other matches.
'''
ls = len(s)
for x in range(ls - 1):
for y in range(x+1, ls):
if s[x] == s[y]:
return False
return True
def testMethod(func):
'''
test unique verification methods
'''
print 'Testing %s: ' % func.__name__,
assert func('')
assert not func('aa')
assert func('abcde')
assert not func('abcdea')
assert not func('aagdjflk')
assert not func('gdjfklaa')
assert not func('gdjfjkl')
print 'Passed'
if __name__ == '__main__':
testMethod(hasUniqueChars)
testMethod(hasUniqueCharsNoBuf)
| true |
e7d7975306ff4dc19aace83acc35a0b95172a3e0 | motleytech/crackCoding | /arraysAndStrings/isStringRotated.py | 788 | 4.125 | 4 | '''
Given 2 strings s1 and s2, and a method isSubstring, write a
method to detect if s1 is a rotation of s2
The key ideas are...
1. len(s1) == len(s2)
2. s1 is a substring of s2 + s2
If the above 2 conditions are met, then s2 is a rotation of s1
'''
def isSubstring(s1, s2):
'''
Returns True if s1 is a substring of s2
'''
return s1 in s2
def isRotation(s1, s2):
'''
Returns True if s1 is a rotation of s2
'''
if len(s1) == len(s2):
if isSubstring(s1, s2 + s2):
return True
return False
def test_isRotation():
'''
test for isRotation
'''
print 'Testing isRotation...',
assert isRotation('abcd', 'bcda')
assert isRotation('a', 'a')
print 'Passed'
if __name__ == '__main__':
test_isRotation()
| true |
6a6a06d047a95ed76a60ed9f2392016f6d379ccf | motleytech/crackCoding | /arraysAndStrings/urlify.py | 1,506 | 4.34375 | 4 | '''
Replace all spaces in a string with '%20'
We can do this easily in python with the string method 'replace', for example
to urlify the string myurl, its enough to call myurl.replace(' ', '%20')
Its that simple.
To make the task a little more difficult (to be more in line with what
the question expects), we will convert the string into a list of characters.
Our task will now be to return ['a', '%', '2', '0', 'b'] when given an input ['a', ' ', 'b']
'''
def urlify(s):
'''
replace spaces in s with %20... the C/Java way
'''
# convert string into list of characters
s = [c for c in s]
# count number of spaces
ns = sum(1 for c in s if c == ' ')
# get length of string
ls1 = len(s) - 1
# add 2*ns empty spaces at the end of the list
s.extend([' ']*(2*ns))
# get the new length
ls2 = len(s) - 1
# move characters from end of string to end of list
# while replacing space with %20
while ls1 >= 0:
if s[ls1] == ' ':
s[ls2] = '0'
s[ls2-1] = '2'
s[ls2-2] = '%'
ls2 -= 3
else:
s[ls2] = s[ls1]
ls2 -= 1
ls1 -= 1
return ''.join(s)
def test_urlify():
'''
Test the urlify method
'''
print 'Testing URLify: ',
assert urlify(' ') == '%20'
assert urlify('a b') == 'a%20b'
assert urlify('a b ') == 'a%20b%20'
assert urlify('a b ') == 'a%20%20b%20'
print 'Passed'
if __name__ == '__main__':
test_urlify()
| true |
edf168e27bffaa08a8f44733f3b55a524ff3052f | ZswiftyZ/Nested_Control_Structures | /Nested Control Structures.py | 1,064 | 4.25 | 4 | """
Programmer: Trenton Weller
Date: 10.15.19
Program: This program will nest a for loop inside of another for loop
"""
for i in range(3):
print("Outer for loop: " + str(i))
for l in range(2):
print(" innner for loop: " +str(l))
"""
Programmer: Trenton Weller
Date: 10.22.19
Program: Average Test Scores
This program asks for the test score for multiple peeople and
reports the average test score for each portion
"""
num_people = int(input("How many people are taking the test?: "))
testperperson = int(input("How many tests are going to be averaged?: "))
for i in range(num_people):
name = input("Enter Name: ")
sum = 0
for j in range(testperperson):
score = int(input("Enter a score: "))
sum = sum + score
average = float(sum) / testperperson
print(" Average for " + name + ": " + str(round(average, 2)))
print("\n****************\n")
"""
Programmer: Trenton
Date: 10.23.19
Program: This program will ask users of an interest to them
theen ask for two items related to that interest
"""
| true |
fe6259b11728d674f4e31caef1a1d284bc2b225a | Harshhg/python_data_structures | /Arrays/alternating_characters.py | 634 | 4.125 | 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.
For example, given the string AABAAB , remove an A at positions 0 and 3 o make ABAB in 2 deletions.
Function that takes string as argument and returns minimum number of deletion
'''
def alternatingCharacters(s):
d=0
prev="None"
for x in s:
if x==prev:
d+=1
else:
prev=x
return d
| true |
368a07b7981351a62e8090e04924e62e0a03bafa | Harshhg/python_data_structures | /Graph/py code/implementing_graph.py | 1,481 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Implementing Graph using Adjacency List
from IPython.display import Image
Image("graph.png")
# In[6]:
# Initializing a class that will create a Adjacency Node.
class AdjNode:
def __init__(self,data):
self.vertex = data
self.next = None
# In[15]:
# A class to represent the graph
class Graph:
def __init__(self,vertices):
self.V = vertices
self.graph = [None] * self.V
# Function to add an EDGE to the undirected graph
# Adding the node to the source
def addEdge(self, src, dest):
node = AdjNode(dest)
node.next = self.graph[src]
self.graph[src] = node
# Adding the node to the Destination (since it is undirected graph)
node = AdjNode(src)
node.next = self.graph[dest]
self.graph[dest] = node
# Function to print the Graph
def printGraph(self):
for i in range(self.V):
print("Adjacency list of vertex {}\n head".format(i), end="")
temp = self.graph[i]
while temp:
print(" -> {}".format(temp.vertex), end="")
temp = temp.next
print(" \n")
# In[16]:
# Driver Program
V = 5
graph = Graph(V)
graph.addEdge(0, 1)
graph.addEdge(0, 4)
graph.addEdge(1, 2)
graph.addEdge(1, 3)
graph.addEdge(1, 4)
graph.addEdge(2, 3)
graph.addEdge(3, 4)
graph.printGraph()
# In[ ]:
# stay Tuned :)
| true |
6d9e626308c9d866e15c071a6b0e74a3f38eeda5 | NiklasAlexsander/IN3110 | /assignment3/wc.py | 2,168 | 4.40625 | 4 | #!/usr/bin/env python
import sys
def main():
"""Main function to count number of lines, words, and characters, for all
the given arguments 'filenames' given.
A for-loop goes through the array of arguments given to wc.py when run from
from the terminal. Inside the loop each argument will be 'open' for
read-only. Our needed variables will be made and a 'with' will be called
containing the open files. A for-loop will go through each line of a file.
The counting of lines, words, characters, and spaces will be done in this
loop. To get the count of the lines we count one '1' on each iteration.
We split the lines at spaces ' ' and count the length to find the
wordcount. We find the count of the characters by finding the length of the
line and subtracting the amout of spaces in the line and subtract to
count for the newline at the end of each line. At the end we print the
result as a human-readable string to the default output.
Note:
The 'with' keyword is being used as it will clean the file-opening
regardless of the code gets done, or if it fails, gets interrupted,
or exceptions are thrown.
Args:
argv(array): Array containing all arguments given as strings.
Expecting filenames or filepaths.
Attributes:
lineCounter (int): Variable to keep track of the number of lines
wordCounter (int): Variable to keep track of the number of words
characterCounter (int): Variable to keep track of the number of characters
spaces (int): Variable to keep track of the number of spaces
"""
if __name__ == "__main__":
for path in sys.argv[1:]:
file = open(path, 'r')
lineCounter = wordCounter = characterCounter = spaces = 0
with file as f:
for line in f:
lineCounter+=1
wordCounter+= len(line.split())
characterCounter+=len(line)-line.count(' ')-line.count('\n')
spaces += line.count(' ')
print(f"{lineCounter} {wordCounter} {characterCounter} {path}")
main()
| true |
5d86b8b02a006566aefd819c9249151916514c82 | TECHNOCRATSROBOTICS/ROBOCON_2018 | /Computer Science/Mayankita Sisodia/ll.py | 1,564 | 4.53125 | 5 | # TO INSERT A NEW NODE AT THE BEGINNING OF A LINKED LIST
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data to the node.
self.next = None # Initialize next as null so that next of the new node can be made the head of the linked list
class LinkedList:
# Function to initialize the Linked List object
def __init__(self):
self.head = None #Assign head of linked list as null.
def push(self, new_data):
new_node = Node(new_data) # creating object of class node, which is the new node to be inserted
new_node.next = self.head # making the next of new node as head of linked list
self.head = new_node # making head of list to point at new node
def PrintList( self ):
node = self.head # assigning head to a variable node
while node != None: #until node is not null
print (node.data) # print the data of the node
node = node.next #move to the next of the current node
l=LinkedList() #object of class LinkedList
l.push(5) # push function to insert elements in the beginning
l.push(6)
l.push(7)
l.PrintList()
| true |
dca26a9e0cc1952bd168baae5621036c8ac19e8d | TECHNOCRATSROBOTICS/ROBOCON_2018 | /Computer Science/Mayankita Sisodia/tree.py | 1,955 | 4.28125 | 4 | class Node:
def __init__(self, val): #constructor called when an object of class Node is created
self.left = None #initialising the left and right child node as null
self.right = None
self.data = val # data of each object/node
def insert(self, data):
if self.data: #if current root is not null
if data < self.data: # if the new data to be inserted is less than the the root, assign data to the left node if the left node is empty
if self.left is None:
self.left = Node(data)
else: #if the left node is filled, insert data to one of the child nodes of it.
self.left.insert(data)
elif data > self.data: # if the new data to be inserted is greater than the the root, assign data to the right node if the right node is empty
if self.right is None:
self.right = Node(data)
else: #if the right node is filled, insert data to one of the child nodes of it.
self.right.insert(data)
else: # if node of given root is null, insert data at the root
self.data = data
def search(self,key):
if self.data==key: # root is key itself
print(self.data)
elif self.data<key: # key is greater than given root, compare with the right node
search(self.right,key)
else: # if key is lesser than the given root, compare with the left node.
search(self.left,key)
r = Node(3)
r.insert(2)
r.insert(4)
r.insert(5)
r.search(5)
| true |
818f452713e6fce3908f59df610f6a9e4dd073b9 | mo2274/CS50 | /pset7/houses/import.py | 1,508 | 4.375 | 4 | from sys import argv, exit
import cs50
import csv
# check if the number of arguments is correct
if len(argv) != 2:
print("wrong argument number")
exit(1)
# create database
db = cs50.SQL("sqlite:///students.db")
# open the input file
with open(argv[1], "r") as characters:
# Create Reader
reader_csv = csv.reader(characters)
# skip the first line in the file
next(reader_csv)
# Iterate over csv
for row in reader_csv:
# get the name of the character
name = row[0]
# counter for the number of words in the name
count = 0
# check if the name is three words or two
for c in name:
if c == ' ':
count += 1
# if the name contain three words
if count == 2:
# split the name into three words
name_list = name.split(' ', 3)
first = name_list[0]
middle = name_list[1]
last = name_list[2]
# if the name contain two words
if count == 1:
# split the name into two words
name_list = name.split(' ', 2)
first = name_list[0]
middle = None
last = name_list[1]
# get the name of house
house = row[1]
# get the year of birth
birth = int(row[2])
# insert the data into the table
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", first, middle, last, house, birth)
| true |
d56d83109a66b60b73160c4a45d770d01ef76274 | Stuff7/stuff7 | /stuff7/utils/collections/collections.py | 1,021 | 4.1875 | 4 | class SafeDict(dict):
""" For any missing key it will return {key}
Useful for the str.format_map function when
working with arbitrary string and you don't
know if all the values will be present. """
def __missing__(self, key):
return f"{{{key}}}"
class PluralDict(dict):
""" Parses keys with the form "key(singular, plural)"
and also "key(plural)".
If the value in the key is 1 it returns singular
for everything else it returns plural """
def __missing__(self, key):
if "(" in key and key.endswith(")"):
key, rest = key.split("(", 1)
value = super().__getitem__(key)
suffix = rest.rstrip(")").split(",")
if len(suffix) == 1:
suffix.insert(0, "")
return suffix[0].strip() if value == 1 else suffix[1].strip()
return f"{{{key}}}"
def safeformat(string, **options):
""" Formatting and ignoring missing keys in strings. """
try:
return string.format_map(SafeDict(options))
except ValueError as e:
return f"There was a parsing error: {e}"
| true |
5fdd9607564a70b74cbab892584f6c9f6a83d532 | vinaud/Exercicios-Python | /Recursividade/elefantes.py | 1,044 | 4.15625 | 4 | """
Implemente a função incomodam(n) que devolve uma string contendo "incomodam "
(a palavra seguida de um espaço) n vezes. Se n não for um inteiro estritamente positivo,
a função deve devolver uma string vazia. Essa função deve ser implementada utilizando recursão.
Utilizando a função acima, implemente a função elefantes(n) que devolve uma string contendo
a letra da música "Um elefante incomoda muita gente" de 1 até n elefantes. Se n não for maior que 1,
a função deve devolver uma string vazia. Essa função também deve ser implementada utilizando recursão.
"""
def incomodam(n):
if n < 1:
return ""
return "incomodam " + incomodam(n-1)
def elefantes(n):
if n < 1:
return ""
if n == 1:
return "Um elefante incomoda muita gente\n"
if n == 2:
return elefantes(n-1)+str(n)+" elefantes "+incomodam(n)+"muito mais\n"
return elefantes(n-1)+str(n-1)+" elefantes incomodam muita gente\n"+str(n)+" elefantes " + incomodam(n)+"muito mais\n"
print(elefantes(4)) | false |
ebba3c73c933c9b32ba3b2e1a59600e1bfb84d3e | aaazezeze1/BMI-Python | /bmi.py | 544 | 4.34375 | 4 | print("BMI Calculator\n")
name = input("Enter your name: ")
weight = float(input("Enter your weight (kg): "))
height = float(input("Enter your height (mtr): "))
bmi = weight / (height * height)
if bmi <= 18.5:
print('\nYour BMI is', bmi, 'which means you are underweight')
elif 18.5 < bmi < 25:
print('\nYour BMI is', bmi,'which means you are normal')
elif 25 < bmi < 30:
print('\nyour BMI is', bmi,' which means you are overweight')
elif bmi > 30:
print('\nYour BMI is', bmi,'which means you are obese') | false |
68b0ed0774592899b32fc7838d54d9d361a05ff8 | gevuong/Developer-Projects | /python/number_game.py | 1,407 | 4.21875 | 4 | import random
def game():
# generate a random number between 1 and 10
secret_num = random.randint(1, 10) # includes 1 and 10 as possibilities
guess_count = 3
while guess_count > 0:
resp = input('Guess a number between 1 and 10: ')
try:
# have player guess a number
guess = int(resp)
except ValueError:
print("{} is not an integer!".format(resp))
else:
# compare player guess to secret number
if guess == secret_num:
print("You guessed it right! My number was {}!".format(secret_num))
play_again = input("Play again? y/n: ")
if play_again == 'y':
game()
else:
print('Ok bye!')
break
elif guess < secret_num:
print("My number is higher than {}, guess again".format(guess))
guess_count -= 1
elif guess > secret_num:
print("My number is lower than {}, guess again".format(guess))
guess_count -= 1
else: # runs when while loop finishes on its own, and when break or exception does not execute.
print("You ran out of guesses. My number was {}!".format(secret_num))
play_again = input("Play again? y/n: ")
game() if play_again == 'y' else print('Ok bye!')
game()
| true |
8f8cb15ef494edb05050d9eb8e82047c89dd1ad1 | chandrikakurla/inorder-traversal-using-stack-in-python | /bt_inorder traversal using stack.py | 1,018 | 4.28125 | 4 | #class to create nodes of a tree
class Node:
def __init__(self,data):
self.left=None
self.data=data
self.right=None
#function to inorder traversal of a tree
def print_Inorder(root):
#initialising stack
stack=[]
currentnode=root
while True:
#reach leftmost node of current
if currentnode is not None:
stack.append(currentnode)
currentnode=currentnode.left
elif(stack):
currentnode=stack.pop()
print(currentnode.data,end=" ")
currentnode=currentnode.right
else:
#if currentnode is none and stack is empty then traversal is completed
break
#main programme
if __name__=="__main__":
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(4)
root.left.right=Node(5)
root.right.left=Node(6)
root.right.right=Node(7)
print("Inorder traversal of tree is:")
print_Inorder(root)
| true |
1398699207d99c1fd94e7ed1e72fc3ec0cb661de | cvk1988/biosystems-analytics-2020 | /assignments/01_strings/vpos.py | 1,425 | 4.375 | 4 | #!/usr/bin/env python3
"""
Author : cory
Date : 2020-02-03
Purpose: Find the vowel in a string
"""
import argparse
import os
import sys
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casbah',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('vowel',
metavar='str',
help='A vowel',
choices=['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
parser.add_argument('text',
help='Some text',
metavar='str',
type=str,
default='')
return parser.parse_args()
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
vowel = args.vowel
text = args.text
#index =text.index(vowel)
#text.index(vowel)
if vowel in text:
print(f'Found "{vowel}" in "{text}" at index {text.index(vowel)}.')
else:
print(f'"{vowel}" is not found in "{text}".')
#print(f'Found "{vowel}" in "{text}" at index {index}.') if vowel in text else print(f'"{vowel}" not found')
#print(index))
# --------------------------------------------------
if __name__ == '__main__':
main()
| true |
d5ff9d18c1fdf3e489080b6925293d5626adae93 | sideroff/python-exercises | /01_basic/exercise_024.py | 363 | 4.25 | 4 | def is_vowel(char: str):
vowels = ('a', 'e', 'i', 'o', 'u')
if len(string_input) > 1:
print("More than 1 character received. Choosing the first char as default.")
char = string_input[:1]
print("Your char is a vowel" if char in vowels else "Your char is not a vowel")
string_input = input("Choose a char: ")
is_vowel(string_input)
| true |
58a9abb0dae2450fd180b6e00ae41748647b9176 | sideroff/python-exercises | /various/class_properties.py | 634 | 4.15625 | 4 | # using property decorator is a different way to say the same thing
# as the property function
class Person:
def __init__(self, name: str):
self.__name = name
def setname(self, name):
self.__name = name
def getname(self):
return self.__name
name = property(getname, setname)
class DifferentPerson:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
p = DifferentPerson('Steve')
# p = Person('Steve')
print(p.name)
p.name = 'Josh'
print(p.name)
| true |
e6f65dfc64711b4e19a0c2d0391197a050402ac1 | judyhuang209/001Data-Science | /hw2/euclideanDistance.py | 606 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 14:00:49 2019
Ref: https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/
@author: 105502506
"""
import math
def euclideanDistance(instance1, instance2, length):
distance = 0
for x in range(length):
distance += pow((instance1[x] - instance2[x]), 2)
return math.sqrt(distance)
# test
def main():
data1 = [1, 2, 3, 'a']
data2 = [3, 2, 1, 'b']
distance = euclideanDistance(data1, data2, 3)
print ('Distance: ' + repr(distance))
if __name__ == "__main__":
main() | false |
bd11a5ebbf2cdb102526ec1f39866c801e04ff54 | ladamsperez/python_excercises | /Py_Gitbook.py | 2,123 | 4.75 | 5 | # # Integer refers to an integer number.For example:
# # my_inte= 3
# # Float refers to a decimal number, such as:
# # my_flo= 3.2
# # You can use the commands float()and int() to change from onte type to another:
# float(8)
# int(9.5)
# fifth_letter = "MONTY" [4]
# print (fifth_letter)
# #This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the problem(for escaping characters), like this:
# yee_yee = 'There\'s a snake in my boot!'
# print(yee_yee)
#len() The output when using this method will be the number of letters in the string.
# parrot="Norwegian Blue"
# len(parrot)
# print (len(parrot))
# parrot="Norwegian Blue"
# print(parrot.lower())
# parrot="Norwegian Blue"
# print(parrot.upper())
# Now let's look at str(), which is a little less straightforward.
# The str() method turns non-strings into strings.
# pi=3.14
# pi=(str(pi))
# print(type(pi))
# #<class 'str'>
# You can work with integer, string and float variables.
# But don't mix string variables with float and integer ones when making concatenations:
# width + "Hello"
# # Sometimes you need to combine a string with something that isn't a string.
# # In order to do that, you have to convert the non-string into a string using `str()``.
# print("The value of pi is around " + str(3.14))
# The value of pi is around 3.14
# When you want to print a variable with a string,
# there is a better method than concatenating strings together.
# The %operator after a string is used to combine a string with variables.
# The %operator will replace a %s in the string with the string variable that comes after it.
# string_1= "Erle"
# string_2= "drone"
# print (" %s is an awesome %s" %(string_1, string_2))
# Erle is an awesome drone
name = raw_input("What is your name?")
color = raw_input("What is your favorite color?")
print ("Ah, so your name is %s and your favorite color is %s." % (name, color))
name = raw_input("What is your name?")
color = raw_input("What is your favorite color?")
print "Ah, so your name is %s and your favorite color is %s." % (name, color)
| true |
8c650f2e69061c4d164e8028b41009512e47d715 | ladamsperez/python_excercises | /task6_9.py | 636 | 4.125 | 4 | # Write a python function that takes a list of names and returns a new list
# with all the names that start with "Z" removed.
# test your function on this list:
# test_list = ['Zans', 'Dan', 'Grace', 'Zelda', 'L.E.', 'Zeke', 'Mara']
test_list = ['Zans', 'Dan', 'Grace', 'Zelda', 'L.E.', 'Zeke', 'Mara']
def noznames(namelist):
newlist = []
for name in namelist:
if not name.startswith("Z"):
newlist.append(name)
print(newlist)
noznames(test_list)
# nosynames(name)
# namelist = ['Zans', 'Dan', 'Grace', 'Zelda', 'L.E.', 'Zeke', 'Mara']
# namelist.strip(name.startswith("Z"))
# print(namelist) | true |
49e49eb50b5beca72b1e6261390d99b1d45922a5 | Vuyanzi/Python | /app.py | 307 | 4.125 | 4 |
name = input ('What is your name? ')
print ('Hi '+ name)
colour = input ('What is your favourite colour ' + name + '')
print (name + ' likes ' + colour)
year_of_birth = input (name + ' Please enter your year of birth ' )
age = 2019 - int(year_of_birth)
g = 'Your current age is '
v = age
print (g + str(v)) | false |
7816945813febe2936ba26f6177c1bbfae2e4724 | lisachen0112/Coffee-machine | /coffee_machine.py | 2,499 | 4.34375 | 4 | water = 400
milk = 540
coffee_beans = 120
cups = 9
money = 550
espresso = {"water": 250, "milk": 0, "coffee_beans": 16, "money": 4}
latte = {"water": 350, "milk": 75, "coffee_beans": 20, "money": 7}
cappuccino = {"water": 200, "milk": 100, "coffee_beans": 12, "money":6}
def home():
print(f"""The coffee machine has:
{water} of water
{milk} of milk
{coffee_beans} of coffee beans
{cups} of disposable cups
{money} of money\n""")
def adj_balance(coffee):
global water, milk, coffee_beans, cups, money
water -= coffee["water"]
milk -= coffee["milk"]
coffee_beans -= coffee["coffee_beans"]
cups -= 1
money += coffee["money"]
def check_resources(coffee):
global water, milk, coffee_beans, cups, money
if water > coffee["water"]:
if milk > coffee["milk"]:
if coffee_beans > coffee["coffee_beans"]:
if cups > 0:
print("I have enough resources, making you a coffee!")
adj_balance(coffee)
else:
print("Sorry, not enough coffee beans!")
else:
print("Sorry, not enough coffee beans!")
else:
print("Sorry, not enough milk!")
else:
print("Sorry, not enough water!")
def buy():
buy = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\n")
if buy == "1":
check_resources(espresso)
elif buy == "2":
check_resources(latte)
elif buy == "3":
check_resources(cappuccino)
else:
pass
def fill():
global water
global milk
global coffee_beans
global cups
add_water = int(input("Write how many ml of water do you want to add:\n> "))
add_milk = int(input("Write how many ml of milk do you want to add:\n> "))
add_coffee_beans = int(input("Write how many grams of coffee beans do you want to add:\n> "))
add_cups = int(input("Write how many disposable cups of coffee do you want to add:\n> "))
water += add_water
milk += add_milk
coffee_beans += add_coffee_beans
cups += add_cups
def take():
global money
print(f"I gave you ${money}")
money = 0
while True:
action = input("Write action (buy, fill, take, remaining, exit):\n")
if action == "buy":
buy()
elif action == "fill":
fill()
elif action == "take":
take()
elif action== "remaining":
home()
else:
break | false |
b3facc57e8f25fe47cbd1b12d94d98403d490c9a | GabrielCernei/codewars | /kyu6/Duplicate_Encoder.py | 596 | 4.15625 | 4 | # https://www.codewars.com/kata/duplicate-encoder/train/python
'''
The goal of this exercise is to convert a string to a new string where each character in the new
string is "(" if that character appears only once in the original string, or ")" if that character
appears more than once in the original string. Ignore capitalization when determining if a character
is a duplicate.
'''
def duplicate_encode(word):
result = ""
word = list(word.lower())
for c in word:
if word.count(c) > 1:
result += ")"
else:
result += "("
return result | true |
2811c2f7ad8732f43ab8498fb10ba05d8e6ad1e6 | GabrielCernei/codewars | /kyu6/Opposite_Array.py | 342 | 4.15625 | 4 | # https://www.codewars.com/kata/opposite-array/train/python
'''
Given an array of numbers, create a function called oppositeArray that returns an array
of numbers that are the additive inverse (opposite or negative) of the original. If the
original array is empty, return it.
'''
def opposite_list(numbers):
return [-i for i in numbers] | true |
61e909280a67b37ae7f53ace4915e2ef3b51ba67 | GabrielCernei/codewars | /kyu6/To_Weird_Case.py | 859 | 4.5625 | 5 | # https://www.codewars.com/kata/weird-string-case/train/python
'''
Note: The instructions are not very clear on this one, and I
wasted a lot of time just trying to figure out what was expected.
The goal is to alternate the case on *EACH WORD* of the string,
with the first letter being uppercase. You will not pass all of the
tests if you alternate case based on the indexes of the entire string
as a whole.
eg. "This is a test string" should return "ThIs Is A TeSt StRiNg"
^ ^ ^ ^ ^ ^ ^ ^ ^
'''
def to_weird_case(string):
starter = string.split()
result = ""
for index, char in enumerate(starter):
for i, c in enumerate(char):
if i == 0 or i % 2 == 0:
result = result + (c.upper())
else:
result = result + (c.lower())
result = result + " "
return result.rstrip() | true |
0e26c6bb0da2b0e5546e86aa6b2cb6ba09b27ccf | enajeeb/python3-practice | /PythonClass/answer_files/exercises/sorting.py | 711 | 4.1875 | 4 | # coding: utf-8
'''
TODO:
1. Create a function called sort_by_filename() that takes a path and returns the filename.
- Hint: You can use the string's split() function to split the path on the '/' character.
2. Use sorted() to print a sorted copy of the list, using sort_by_filename as the sorting function.
'''
paths = ['PythonClass/exercises/variadic.py',
'PythonClass/exercises/comprehensions.py',
'PythonClass/exercises/hello.py',
'PythonClass/exercises/exceptions.py',
'PythonClass/exercises/directory_iterator.py']
def sort_by_filename(path):
segments = path.split('/')
filename = segments[-1]
return filename
print sorted(paths, key = sort_by_filename)
| true |
c09cdf2e94f9060f285d01e110dc2fc48f2db496 | enajeeb/python3-practice | /PythonClass/class_files/exercises/lists.py | 688 | 4.34375 | 4 | # coding: utf-8
'''
Lists
Lists have an order to their items, and are changeable (mutable).
Documentation:
https://docs.python.org/2/tutorial/introduction.html#lists
'''
# Square brackets create an empty list.
animals = []
# The append() function adds an item to the end of the list.
animals.append('cat')
animals.append('frog')
animals.append('bird')
# To access an item in the list, indicate the item number in brackets.
# Python lists are zero-based, meaning the first item is item #0.
first = animals[0]
# Negative numbers index from the end of the list, so -1 is the last item in the list.
last = animals[-1]
# You can change an item in the list.
animals[1] = 'swallow'
| true |
cffa20e72d74c07324bac4fdd490bac5218dae9a | enajeeb/python3-practice | /PythonClass/class_files/exercises/functions.py | 552 | 4.40625 | 4 | # coding: utf-8
''' Useful functions for the Python classs. '''
'''
TODO:
1. Create a function called words().
2. The function should take a text argument,
and use the string's split() function to return a list of the words found in the text.
The syntax for defining a function is:
def func_name(argument1, argument2):
# code
return result
'''
def get_words(arg1):
'''This is my test function'''
words = arg1.split()
count = len(words)
return words, count
# print get_words('Hello monty python')
| true |
dd18b7dbf8cf814f889a497c4565dcb3b1d12719 | drnodev/CSEPC110 | /meal_price_calculator.py | 1,349 | 4.15625 | 4 | """
File:meal_price_calculator.py
Author: NO
Purspose: Compute the price of a meal as follows by asking for the price of child and adult meals,
the number of each, and then the sales tax rate. Use these values to determine the total price of the meal.
Then, ask for the payment amount and compute the amount of change to give back to the customer.
"""
child_price = float(input("What is the price of a child's meal? "))
adult_price = float(input("What is the price of an adult's meal? "))
child_number = int(input("How many children are there? "))
adult_number = int(input("How many adults are there? "))
tax_rate = float(input("What is the sales tax rate? "))
subtotal = (child_number * child_price) + (adult_number * adult_price)
sales_tax = subtotal * (tax_rate / 100)
total = subtotal + sales_tax
#print results
print(f"\nSubtotal: ${subtotal:.2f}")
print(f"Sales Tax: ${sales_tax:.2f}")
print(f"Total: ${total:.2f}")
payment = float(input("\nWhat is the payment amount? "))
print(f"Change: ${payment-total:.2f}")
yes_no = input("\nDid you enjoy your meal? (Yes/No) ")
starts = int(input("Give us your opinion, how many stars would you give to this restaurant? "))
print(f"\nThe customer rated the restaurant with {starts} stars")
print(f"The customer enjoyed his meal: {yes_no}") | true |
a90c6a4910e4c959057a6662dfb76c08fa123931 | LucasHenriqueAbreu/introducaoprogramaca | /exercicios.py | 777 | 4.15625 | 4 | # Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
# A) Quantas vezes apareceu o valor 9.
# B) Em que posição foi digitado o primeiro valor 3.
# C) Quais foram os números pares.
valores = (
int(input('Informe um número: ')),
int(input('Informe um número: ')),
int(input('Informe um número: ')),
int(input('Informe um número: ')),
int(input('Informe um número: ')),
)
print('A quantidade de noves encontrados é: {}'.format(valores.count(9)))
if 3 in valores:
print('O valor 3 foi encontrado na posição: {}'.format(valores.index(3)))
else:
print('O valor 3 não foi encontrado na tupla. ')
for valor in valores:
if valor % 2 == 0:
print('Número par: {}'.format(valor)) | false |
844344450154b2caacee4af1a0530e14781b9ace | sayan19967/Python_workspace | /Python Application programming practice/Context Managers.py | 2,410 | 4.59375 | 5 | #A Context Manager allows a programmer to perform required activities,
#automatically, while entering or exiting a Context.
#For example, opening a file, doing few file operations,
#and closing the file is manged using Context Manager as shown below.
##with open('a.txt', 'r') as fp:
##
## content = fp.read()
##
##print(content)
##print(fp.read())
#Consider the following example, which tries to establish a connection to a
#database, perform few db operations and finally close the connection.
##import sqlite3
##try:
## dbConnection = sqlite3.connect('TEST.db')
## cursor = dbConnection.cursor()
## '''
## Few db operations
## ...
## '''
##except Exception:
## print('No Connection.')
##finally:
## dbConnection.close()
# Using Context Manager
##import sqlite3
##class DbConnect(object):
## def __init__(self, dbname):
## self.dbname = dbname
## def __enter__(self):
## self.dbConnection = sqlite3.connect(self.dbname)
## return self.dbConnection
## def __exit__(self, exc_type, exc_val, exc_tb):
## self.dbConnection.close()
##with DbConnect('TEST.db') as db:
## cursor = db.cursor()
## '''
## Few db operations
## ...
## '''
#quiz
##from contextlib import contextmanager
##
##@contextmanager
##def tag(name):
## print("<%s>" % name)
## yield
## print("</%s>" % name)
##
##with tag('h1') :
## print('Hello')
# Hackerrank -1
# Complete the function below.
##def writeTo(filename, input_text):
## with open(filename, 'w') as fp:
## fp.write(input_text)
# Hackerrank - 2
# Define 'writeTo' function below, such that
# it writes input_text string to filename.
##def writeTo(filename, input_text):
## with open(filename, 'w') as fp:
## fp.write(input_text)
##
### Define the function 'archive' below, such that
### it archives 'filename' into the 'zipfile'
##def archive(zfile, filename):
## with zipfile.ZipFile(zfile, 'w') as myzip:
## myzip.write(filename)
# Hackerrank - 3
# Complete the function below.
def run_process(cmd_args):
with subprocess.Popen(cmd_args, stdout=subprocess.PIPE) as p:
out1 = p.communicate()[0]
return out1
| true |
baef544efc97fab5a7ce87d4a9ccff5fae67b5f8 | DeepthiTabithaBennet/Py_Conversions_Temperature | /Celsius_to_Farenheit.py | 397 | 4.28125 | 4 | #TASK :
#Convert the given temperature to Farenheit
#(Celsius * 9/5) + 32 = Farenheit
#INPUT FORMAT :
#Temperature in Celsius
#OUTPUT FORMAT :
#Temperature in Farenheit
#__________________________________________________________________________________#
Celsius = float(input())
x = Celsius * 9.0
y = x / 5.0
Farenheit = y + 32.0
print (Celsius, 'Celsius in Farenheit is', Farenheit)
| false |
81eccca3e13efaf255a41a92b5f7ee203a6aca41 | Elzwawi/Core_Concepts | /Objects.py | 2,689 | 4.4375 | 4 | # A class to order custom made jeans
# Programming with objects enables attributes and methods to be implemented
# automatically. The user only needs to know that methods exist to use them
# User can focus on completing tasks rather than operation details
# Difference between functions and objects: Objects contain state and behaviour
# while a function only defines a behaviour
class jeans:
# the _init_ method is a python constructor method for creating new objects.
# it defines unique parameters for a new object.
def __init__(self, waist, length, color):
self.waist = waist
self.length = length
self.color = color
self.wearing = False
def put_on(self):
print('Putting on {}x{} {} jeans'.format(self.waist, self.length, self.color))
self.wearing = True
def take_off(self):
print('Taking off {}x{} {} jeans'.format(self.waist, self.length, self.color))
self.wearing = False
# create and examine a pair of jeans
my_jeans = jeans(31, 32, 'blue') # creating a jeans object
print(type(my_jeans))
print(dir(my_jeans))
# put on the jeans
my_jeans.put_on()
print(my_jeans.wearing)
my_jeans.take_off()
print(my_jeans.wearing)
## Properties of objects ################################################
class shirt:
def __init__(self):
self.clean = True
def make_dirty(self):
self.clean = False
def make_clean(self):
self.clean = True
# create one shirt with two names
red = shirt()
crimson = red
# examine the red/crimson shirt
print(id(red))
print(id(crimson))
print(red.clean)
print(crimson.clean)
# spill juice on the red/crimson shirt
red.make_dirty()
print(red.clean)
print(crimson.clean)
# check that red and crimson are the same shirt
print(red is crimson)
# create a second shirt to be named crimson
crimson = shirt()
# examine both shirts
print(id(red))
print(id(crimson))
print(crimson.clean)
print(red.clean)
# clean the red shirt
red.make_clean()
print(red.clean)
print(crimson.clean)
# check that red and crimson are different shirts
print(red is crimson)
## Mutable vs. immutable ################################################
# A mutable object can be modified after creation
# Immutable objects can not be modified.
closet = ['shirt', 'hat', 'pants', 'jacket', 'socks'] # Mutable variable (list)
print(closet)
print(id(closet))
closet.remove('hat')
print(closet)
print(id(closet))
words = "You're wearing that " # Immutable variable (string)
print(id(words))
# We can only modify it if we assign a new value to the variable
words = words + 'beutiful dress'
print(words)
print(id(words)) # it is now a different id
| true |
af30645406d953795958b806cf529f1ce97150c2 | ZSerhii/Beetroot.Academy | /Homeworks/HW6.py | 2,918 | 4.1875 | 4 | print('Task 1.\n')
print('''Make a program that generates a list that has all squared values of integers
from 1 to 100, i.e., like this: [1, 4, 9, 16, 25, 36, ..., 10000]
''')
print('Result 1:\n')
vResultList = []
for i in range(1, 101):
vResultList.append(i * i)
print('Squared values list of integers from 1 to 100:\n', vResultList, '\n', sep='')
print('Task 2.\n')
print('''Make a program that prompts the user to input the name of a car, the program
should save the input in a list and ask for another, and then another,
until the user inputs ‘q’, then the program should stop and the list of
cars that was produced should be printed.
''')
print('Result 2:\n')
vCarList = []
while True:
vCarName = input('Input the name of a car or letter "q" to exit: ')
if vCarName == 'q':
break
vCarList.append(vCarName)
print('\nYour car list:\n', vCarList, '\n', sep='')
print('Task 3.\n')
print('''Start of with any list containing at least 10 elements, then print all elements
in reverse order.
''')
print('Result 3:\n')
import random
vAnyList = [random.randint(1, 10) for i in range(20)]
print('Original list:\n', vAnyList, '\n', sep='')
vResultList = vAnyList.copy()
vResultList.reverse()
print('Reverse version 1:\n', vResultList, '\n', sep='')
vResultList = []
for vIndex in range(1, len(vAnyList) + 1):
vResultList.append(vAnyList[-vIndex])
print('Reverse version 2:\n', vResultList, '\n', sep='')
print('Lesson topics: Fibonacci sequence.\n')
print('''If n > 1 then (n-1)+(n-2)
If n == 1 then 1
If n == 0 then 0.
''')
print('Result Fibonacci sequence:\n')
vFibonacciCount = int(input('Input the number of Fibonacci sequence elements: '))
print('')
vResult = 0
vPrevious = 0
vCurrent = 0
vResultList = []
for i in range(vFibonacciCount):
vResult = vPrevious + vCurrent
if i < 2:
vCurrent = i
vResult = i
else:
vPrevious = vCurrent
vCurrent = vResult
vResultList.append(vResult)
print('First {} elements of Fibonacci sequence:\n'.format(vFibonacciCount), vResultList, sep='')
print('Lesson topics: Pascal\'s triangle sequence.\n')
print('''Pascal’s triangle sequence, given positive int k, returns a list of k
lists, each representing a floor in the pyramid/triangle. See the following for
rules: https://en.wikipedia.org/wiki/Pascal%27s_triangle
''')
print('Result Pascal\'s triangle sequence:\n')
vPascalsDepth = int(input('Input the depth of Pascal\'s triangle sequence: '))
vPascalsPrev = []
print('')
for i in range(vPascalsDepth):
vPascalsLine = []
j = 0
while j <= i:
if j == 0 or j == i:
vPascalsLine.append(1)
else:
vPascalsLine.append(vPascalsPrev[j - 1] + vPascalsPrev[j])
j += 1
vPascalsPrev = vPascalsLine.copy()
print('{}:'.format(i), vPascalsLine)
print('\nThat\'s all Folks!') | true |
4cc9d559c7a44cd2f500a60548fc6b98294828f0 | erictseng89/CS50_2021 | /week6/scores.py | 769 | 4.125 | 4 | scores = [72, 73, 33]
""" print("Average: " + (sum(scores) / len(scores))) """
# The "len" will return the number of values in a given list.
# The above will return the error:
# TypeError: can only concatenate str (not "float") to str
# This is because python does not like to concatenate a float value to a string.
# In order to fix this issue, we can cast the float into a string:
print("Average " + str((sum(scores) / len(scores))))
# You can also wrap the functions themselves inside the print("") contents, which can remove the need for the str() cast function as python will presume that I intended for the value be converted into a str. This can cause the print content to be longer and messier to read.
print(f"Average {((sum(scores) / len(scores)))}")
| true |
72548593092cdbc2ddb64d76951d71d4a89b93e3 | mzdesa/me100 | /hw1/guessNum.py | 599 | 4.21875 | 4 | #write a python program that asks a user to guess an integer between 1 and 15!
import random
random_num = random.randint(1,15) #generates a random int between 0 and 15
guess = None #generate an empty variable
count = 0
while guess != random_num:
count+=1
guess = int(input('Take a guess: '))
if guess == random_num:
print('Congratulations, you guessed my number in', count, 'trials!')
break #exit the loop and end the program if it is correctly guessed
elif guess<random_num:
print('Your guess is too low.')
else:
print('Your guess is too high.')
| true |
e7011a00db9e29abb6e8ad19259dfcacc1423525 | abrolon87/Python-Crash-Course | /useInput.py | 1,219 | 4.28125 | 4 | message = input("Tell me something, and I will repeat it back to you: ")
print (message)
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
#prompt += "\nWhat is your age? " this doesn't work
name = input(prompt)
print(f"\nHello, {name}!")
#as numerical input
age = input("How old are you? ")
#to compare, we have first convert the string to a numerical value:.
#age = int(age)
#age >= 18
#try it yourself 7-1
rentalCar = input("What kind of car would you like to rent? ")
print(f"\nLet me see if I can find you a {rentalCar}.")
# 7-2
guests = input("How many people are in your group?")
guests = int(guests)
if guests >= 8:
print("\nYou will have to wait to be seated.")
else:
print("Your table is ready.")
#7-3
number = input("Enter a number. I'll tell you if it is a multiple of 10 or not: ")
number = int(number)
if number % 10 == 0:
print(f"\nThis number is a multiple of 10")
else:
print(f"\nThis number is NOT a multiple of 10")
#while loop
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
| true |
1957711865e1570ed423c327f288ce8a12d2fe50 | jacquelinefedyk/team3 | /examples_unittest/area_square.py | 284 | 4.21875 | 4 | def area_squa(l):
"""Calculates the area of a square with given side length l.
:Input: Side length of the square l (float, >=0)
:Returns: Area of the square A (float)."""
if l < 0:
raise ValueError("The side length must be >= 0.")
A = l**2
return A
| true |
a957e7f81f52bc56d9af1cd63a284f2e597c6f9d | JohnAsare/functionHomework | /upLow.py | 766 | 4.15625 | 4 | # John Asare
# Jun 19 2020
""" Write a Python function that accepts a string and calculates the number of upper case letters and
lower case letters.
Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'
Expected Output :
No. of Upper case characters : 4
No. of Lower case Characters : 33 """
def up_low(s):
uppers = ''
lowers = ''
for letter in s:
if letter.isupper():
uppers += letter
elif letter.islower():
lowers += letter
print(f'No. of Upper case characters : {len(uppers)}')
print(f'No. of Lower case characters : {len(lowers)} \n')
print('#########################################')
s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
up_low(s)
up_low('Hi, My name is John Asare')
| true |
f5306409b6be76bdc3ce5789daafcca973fdb971 | kelvinng213/PythonDailyChallenge | /Day09Challenge.py | 311 | 4.1875 | 4 | #Given a string, add or subtract numbers and return the answer.
#Example:
#Input: 1plus2plus3minus4
#Output: 2
#Input: 2minus6plus4plus7
#Output: 7
def evaltoexpression(s):
s = s.replace('plus','+')
s = s.replace('minus','-')
return eval(s)
print(evaltoexpression('1plus2plus3minus4')) | true |
e082eb4ff18f0f3a19576a5e3e346227ba98ebf8 | kelvinng213/PythonDailyChallenge | /Day02Challenge.py | 894 | 4.53125 | 5 | # Create a function that estimates the weight loss of a person using a certain weight loss program
# with their gender, current weight and how many weeks they plan to do the program as input.
# If the person follows the weight loss program, men can lose 1.5% of their body weight per week while
# women can lose 1.2% of their body weight per week.
# The possible inputs are:
# Gender: 'M' for Male, 'F' for Female
# Current weight: integer above 0
# Number of weeks: integer above 0
# Return the estimated weight after the specified number of weeks.
def lose_weight():
gender = input("M or F:").upper()
weight = int(input("Enter weight:"))
num_weeks = int(input("Number of weeks:"))
if gender == "M":
n = weight - ((0.015 * weight) * num_weeks)
print(n)
else:
n = weight - ((0.012 * weight) * num_weeks)
print(n)
lose_weight() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.