blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7cbf817dc4836a6462360cb4dc445a4f726d709d | bawejakunal/leetcode | /string-chain/str-chain.py | 877 | 4.15625 | 4 | """
Practise question
"""
def maxlength(words):
"""
sample question
"""
dictionary = dict()
for word in words:
dictionary[word] = 1
"""
The run time for words.sort() is O(nlg(n))
which can be reduced to O(n) by using bucket
concept to group words by their lengths.
"""
words.sort(key=len)
maxchain = 0
for word in words:
current = dictionary[word]
for i in xrange(len(word)):
temp = word[:i] + word[i+1:]
if temp in dictionary:
current = max(current, dictionary[temp]+1)
dictionary[word] = current
maxchain = max(maxchain, current)
return maxchain
def main():
"""
driver method
"""
words = ['a', 'b', 'ba', 'bca', 'bda', 'bdca']
print maxlength(words)
if __name__ == '__main__':
main()
| true |
48519eb32d32dd66aedfdb1189d096ec744fcf0d | Nkaka23dev/data-structure-python | /general/map.py | 650 | 4.21875 | 4 | import math
#the below code are normal way of calculating areas of different radii using loop
#but wit a map function it can be accomplished by one line of code.
# def area(r):
# return round((math.pi)*(r**2),2)
# radii=[2,5,7.1,0.3,10]
# areas=[]
# for r in radii:
# a=area(r)
# areas.append(a)
# print(areas)
# we can even use list comprehension to reduce the size of the code
# def area(r):
# return round((math.pi)*(r**2),2)
# radii=[2,5,7.1,0.3,10]
# print([area(r) for r in radii])
# let us use map now
# radii=[2,5,7.1,0.3,10]
print(list(map(lambda r:round(math.pi*(r**2),2),radii)))
| true |
00a9ad96ea6ce706f756b61a8b846e3deaa67c4f | Nkaka23dev/data-structure-python | /mericar.py | 679 | 4.125 | 4 |
def findNumber(arr,k):
if k<=0 or k>=10*5:
raise ValueError("Not allowed")
if len(arr)<=0 or len(arr)>=10*9:
raise ValueError("index??")
while k in arr:
print("yes")
break
while k not in arr:
print("No")
break
arr=[1,3,4,5,7]
number=4
if __name__=='__main__':
findNumber(arr,number)
def oddNumbers(l, r):
# Write your code here
arr=[]
if l<=0 or l<=10*5:
print("invalid input")
if r<=0 or r>=10*5:
print("Invalid r")
if l>=r:
print("not allowed")
for i in list(range(l,r)):
if i%2!=0:
print(i,end=' ')
oddNumbers(1,9) | false |
ed3257a9ea3049735b10f82310c7ef9dd3a6030d | Jakesh-Bohaju/python | /right_angle _triangle.py | 1,269 | 4.6875 | 5 | """
check either the entered angle of triangle form right angled triangleor not
to be a triangle the sum of angles must not be greater than 180
if any one angle enter greater or equal to 180 then it does not form any triangle
if any one of angle of triangle is equal to 90 then it is right angle triangle
no need to check the a = b+c or b = a=c or c = a+b, because to be right angle triangle either one angle must be 90 or sum of two angle must be 90 ie. there must be one angle 90
"""
def right_angle_triangle(a, b, c):
if a + b + c > 180 or a + b + c < 180:
print("Angles you entered does not form triangle")
else:
if not a >= 180 and not b >= 180 and not c >= 180:
if a == 90 or b == 90 or c == 90:
print("The triangle is right angle triangle")
#elif a == (b + c) or b == (a + c) or c == (a + b):
# print("The triangle is right angle triangle")
else:
print("The triangle is not right angle triangle")
else:
print("A angle of triangle is exceed than 178 degree")
a = float(input("Enter first angle"))
b = float(input("Enter second angle"))
c = float(input("Enter third angle"))
right_angle_triangle(a, b, c)
| true |
85cde7ad6a2289547cd6dde0e729cc61c5715bd6 | Jakesh-Bohaju/python | /lambda_map.py | 1,119 | 4.71875 | 5 | # using function definition
names = ['Hari', 'Shyam', 'Rajesh']
formatted_names = []
for name in names:
namesss = 'Mr ' + name
formatted_names.append(namesss)
print(formatted_names)
# using lambda function
new_name = []
formatted_namess = lambda names: 'Mr ' + names
for name in names:
namess = formatted_namess(name)
new_name.append(namess)
print(new_name)
# using map in list
# map is use for data transfer like "Ram" to "Mr Ram"
# note : map use in case of having only one parameter
# map(function, iteration)
# function must have only one parameter, iteration is of looping i.e use list or tuple
formatted_names = list(map(formatted_namess, names))
print(formatted_names)
names1 = ['Ram Shrestha', 'Jakesh Bohaju', 'Ramesh keumar Sharma']
first_name = lambda names1: names1.split(' ')[0]
first_names = list(map(first_name, names1))
print(first_names)
g_added= lambda names1: names1 + ' ji'
add_g_at_last_of_name = list(map(g_added, names1))
print(add_g_at_last_of_name)
#squaring list element using map and lambda in single line
print(list(map(lambda no: no ** 2, [2, 3, 6, 7])))
| true |
89f6c2dc8fe1e9208085a5a96bc99ac500cd82ee | ajmerasaloni10/Python | /Array/array_intersection/intersection_array_method_1.py | 546 | 4.15625 | 4 | """Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
"""
def array_intersection(list1, list2):
"""
:params list1:
:params list2:
"""
list3 = []
for num in list1:
if num in list2:
list3.append(num)
return list3
def main():
nums1 = [1,2,2,1]
nums2 = [2,2]
intersection = array_intersection(nums1, nums2)
print intersection
if __name__ == "__main__": main() | true |
550bf05c56943c0316963873cccc0f5f2935ae7c | jrhdoty/project_euler | /project_euler_python/problem_7.py | 456 | 4.15625 | 4 | '''
Project Euler
What is the 10 001st prime number?
'''
def is_prime(num, primes):
for item in primes:
if num%item == 0:
return False
return True
def list_primes(num_primes):
primes = [2]
num = 3
while len(primes) < num_primes:
if is_prime(num, primes):
primes.append(num)
num += 1
return primes
if __name__=="__main__":
primes = list_primes(10001)
print primes[-1]
| true |
d43a719263ef48b92c8aec448308f59d02d77bcb | yknot/adventOfCode | /2019/01_02.py | 1,004 | 4.21875 | 4 | """
Day 1 part 2
amount of fuel for a module is based on mass
floor(mass / 3) - 2
part 2: we need to calculate fuel for the fuel...
as long as the calculated fuel is not negative
(aka the floor doesen't amount to 2 or less)
then we need to add the new fuel
test cases
12 -> 2
14 -> 2
1969 -> 654 + 216 + 70 + 21 + 5 = 966
100756 -> 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346
output:
sum of the fuel required for each module
"""
from utils import read_input
def calc_fuel(mass):
"""floor of the mass divided by 3 minus 2"""
fuel = (mass // 3) - 2
# check if added fuel is less than 0
if fuel <= 0:
return 0
# otherwise recurse to add the fuel for our fuel
return fuel + calc_fuel(fuel)
def tests():
"""tests from the description"""
assert calc_fuel(12) == 2
assert calc_fuel(14) == 2
assert calc_fuel(1969) == 966
assert calc_fuel(100756) == 50346
tests()
assert sum(calc_fuel(int(l)) for l in read_input(1)) == 5268207
| true |
a5df1dfb36d2ccb407b0dc8fb6616aaa1845da7e | Alweezy/oop-concepts | /shape.py | 383 | 4.375 | 4 | class Shape(object):
"""The base class from which other classes will inherit """
def __init__(self, length, width):
self._length = length
self._width = width
def calc_area(self):
return self._length * self._width
def calc_perimeter(self):
return 2 * (self._width + self._length)
square = Shape(2, 3)
print(square.calc_perimeter())
| true |
6cce85796afa2a8ca0a3e4365cb1435edf83ac52 | Iuterian99/conditional-operators | /Uy_ishi_5.py | 984 | 4.125 | 4 | #3-Uyga vazifa
# import math
# note1 = "Let`s define the number of solutions of quadratic equation 'ax^2 + bx + c = 0'!"
# note2 = "\nFor this, you have to enter a, b, c values!"
# print(note1, note2)
# a = int(input("Please enter the value of 'a': "))
# b = int(input("Please enter the value of 'b': "))
# c = int(input("Please enter the value of 'c': "))
# d = pow(b,2)- 4*a*c
# if d > 0:
# print("Equation has Two unique solutions!")
# elif d < 0:
# print("Equation has no solution!")
# else:
# print("Equation has one solution!")
# a = int(input("weight: "))
# b = input("(L)bs or (K)g : ")
# if b.upper() == "L":
# converted = 0.45 * a
# print(f"you are {converted} kilos! ")
# else: converted = a / 0.45
# print(f"you are {converted} pounds!")
inro = "Welcome to Guessing game!"
second ="\n you can guess max three times! "
input = "\n please enter numbers from 1 to 5! "
print(inro, second, input)
name = input("enter")
print(name)
#
| false |
4520747ab2bff923b233e276d5234d2cfcc4919c | amirsh7000/lecture2 | /3_1_input.py | 383 | 4.28125 | 4 | ##########################
# get a string from user #
##########################
text = input("enter what you want\n")
print(5*text)
string = input("enter a string\n")
print(string)
##########################
# get a number from user #
##########################
number=int(input("enter an integer\n"))
print(5*number)
integer = int(input("inter an integer\n"))
print(4+integer)
| false |
cd56361550bcc206d055d186c87da460db7802cf | leewalter/coding | /python/hackerrank/BreakingRecordsMinMax.py | 1,362 | 4.25 | 4 | '''
https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
Function Description
Complete the breakingRecords function in the editor below. It must return an integer array containing the numbers of times she broke her records. Index is for breaking most points records, and index is for breaking least points records.
breakingRecords has the following parameter(s):
scores: an array of integers
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the breakingRecords function below.
def breakingRecords(scores):
min1 = 0
max1 = 0
countermin1 = 0
countermax1 = 0
for i in range(len(scores)):
if i == 0: # init min1 and max1 = first element in scores
min1 = scores[i]
max1 = scores[i]
else:
if scores[i] < min1:
min1 = scores[i]
countermin1 += 1
elif scores[i] > max1:
max1 = scores[i]
countermax1 += 1
print(countermax1, countermin1)
return(countermax1, countermin1)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
scores = list(map(int, input().rstrip().split()))
result = breakingRecords(scores)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| true |
8f7494f9cafc11007aa88ffc99a5b7dd7b78a56b | leewalter/coding | /python/prime_numbers.py | 1,099 | 4.15625 | 4 | # find prime numbers based on https://hackernoon.com/prime-numbers-using-python-824ff4b3ea19
primes = []
candidates = list(range(2, 21)) # find prime numbers from 2 to 21; 1 is not a prime number
#print("candidates list is:", candidates)
while len(candidates) > 0:
#print("length is: ", len(candidates))
prime = candidates[0] # 2 is the first prime number
#print("prime is", prime)
primes.append(prime)
#print("primes list is : ", primes)
candidates = candidates[1:] # start checking from 3
# print("candidates list is:" , candidates)
# print("candidates[1:] list is:" , candidates[1:])
for x in candidates[:]:
#print("candidates list is:", candidates)
#print("x is: ", x)
if (x % prime) == 0: # check if x in candidates list is divisible by prime numbers, e.g. 2,3,5 in the prime list
#print("removing ", x)
candidates.remove(x) # remove those divisible by 2,3,5,7 ,etc. to reduce candidates list
print("final prime numbers list", primes)
'''
final prime numbers list [2, 3, 5, 7, 11, 13, 17, 19]
'''
| false |
8345c5260100ee2f6659296632981994782ff270 | chusk2/python-code | /ec_2do_grado_final.py | 2,952 | 4.25 | 4 | """Programa para ecuación de segundo grado"""
# importa una librería con funciones adicionales
import math
print('\n')
print('Programa para cálculo de ecuaciones de 2do grado.')
print('\n')
print('Las ecuaciones son del tipo: ax^2 + bx + c = 0')
a = input('\nDame el coeficiente "a" : ')
b = input('\nDame el coeficiente "b" : ')
c = input('\nDame el coeficiente "c" : ')
# transformamos los números en forma de texto en números en forma numérica
# a,b y c ahora son números decimales
a = float (a)
b = float (b)
c = float (c)
# guardo los coeficientes en una lista
coeficientes = [a,b,c]
# voy a comprobar si cada uno de los coeficientes es decimal o no
# el ciclo for significa: hazle lo de dentro del bloque
# a cada uno de los elementos de la lista coeficientes
# creo una nueva lista de coeficientes con su forma final
# el método .append() añade elementos a una lista
coef_final =[]
for numero in coeficientes :
partes_numero = math.modf(numero)
if partes_numero[0] == 0 :
coef_final.append( int(numero) )
else :
coef_final.append( numero )
print(coef_final)
a = coef_final[0]
b = coef_final[1]
c = coef_final[2]
# si el número no es con decimales, transfórmalo a entero
# para saber si es con decimales, le pido que me de su parte decimal
# si la parte decimal es 0, es que el número es entero
# el método .modf() me devuelve la parte entera y la parte decimal de un número
# el resultado es una "tupla" con la parte decimal y la parte entera
### ejemplo: obtener la parte entera y la parte decimal de un número decimal
### partes_numer0 = modf(325.48)
### (0.48,325.0)
### necesito acceder al primer número
### partes[0]
if b > 0 :
signo_b ='+'
else :
signo_b =''
if c > 0 :
signo_c ='+'
else :
signo_c =''
# usando f-string puedo incluir en el texto variables
print(f'\nTu ecuación es: {a}x^2{signo_b}{b}x{signo_c}{c}')
# fórmula de la ecuación de 2do grado:
# x = ( -b +- raiz(b^2 -4*a*c) ) / 2a
# sqrt() me calcula la raiz cuadrada de un número
# para poder usar función sqrt() he tenido que "enseñarle mates" ---> import math
if (b**2-4*a*c) >= 0 :
x1 = (-b + math.sqrt( b**2 - 4*a*c) ) / 2*a
x2 = (-b - math.sqrt( b**2 - 4*a*c) ) / 2*a
print(f'\nLa primera solución es: {x1:.2f}')
print(f'\nLa segunda solución es: {x2:.2f}')
else :
print("La ecuación no tiene solución. El discriminante es negativo.")
## ejemplos: x^2+4x+4 = 0
## ejemplo: x^2+4x = 0
## ejemplo: x^2-16 = 0
# print("Estos son los tipos de variables: ")
# imprime el tipo de una variable
# texto ='hola'
# number = 23
# number_decimal = 23.56
# lista = [1,2,3,4,5]
# print( type(texto) ) # str -> string
# print( type(number) ) # int -> integer
# print( type(number_decimal) ) # float -> decimal
# print( type(lista) ) # list -> lista
| false |
296158eecfc716afe0530e8e68ef8351ec4e0133 | chusk2/python-code | /divisors.py | 725 | 4.375 | 4 | """"Create a program that asks the user for a number and then prints out a list of all the divisors of that number. (If you don’t know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)"""
def divisors(num) :
return [i for i in range(1,num-1) if num%i == 0 ]
print('Give me a number greater than 0 and I will return a list of its divisors.')
while True :
number = input('Number? ')
if number.isnumeric() :
number = int(number)
if number >=1 :
print(f'Here you have the divisor(s) of {number}: {divisors(number)}')
break
else :
print('Please, give me a NUMBER.')
| true |
a1af64977701084aa052b982ad0dfdd8415fc574 | chusk2/python-code | /university_stats.py | 2,233 | 4.4375 | 4 | universities = [
['California Institute of Technology', 2175, 37704],
['Harvard', 19627, 39849],
['Massachusetts Institute of Technology', 10566, 40732],
['Princeton', 7802, 37000],
['Rice', 5879, 35551],
['Stanford', 19535, 40569],
['Yale', 11701, 40500]
]
def mean(values:list) -> int :
return sum(values)/len(values)
def median(values:list) -> int :
if len(values) % 2 == 0 : # there is an even number of data
mid_point = len(values)//2
median = values[mid_point] + values[mid_point+1]
else :
mid_point = (len(values) -1 )//2 # result must be int, not float
median = values[mid_point]
def enrollment_stats(universities_data:list) -> list :
'''Takes, as an input, a list of lists where
each individual list contains three elements:
(a) the name of a university
(b) the total number of enrolled students
(c) the annual tuition fees.
Example:
universities = [
['California Institute of Technology', 2175, 37704],
['Harvard', 19627, 39849] ]
enrollment_stats() returns two lists:
1) list containing all of the student enrollment values
2) list containing all of the tuition fees.'''
num_students = []
tuition_fees = []
for university in universities_data :
num_students.append(university[1])
tuition_fees.append(university[2])
total_students = sum(num_students)
total_tuition = sum(tuition_fees)
mean_students = mean(num_students)
median_students = median(num_students)
mean_tuition = mean(tuition_fees)
median_students = median(tuition_fees)
print('*'*40)
print(f'\nTotal students:{total_students}:,>10')
print(f'Total tuition:${total_tuition}:,>10')
print(f'Students mean:{mean_students}:,.2f>10')
print(f'Students median:{median_students}:,.2f>10')
print(f'Tuition mean:${mean_tuition}:,.2f>10')
print(f'Tuition median:${median_students}:,.2f>10')
print('\n'+'*'*40)
enrollment_stats(universities)
'''
******************************
Total students: 77,285
Total tuition: $ 271,905
Student mean: 11,040.71
Student median: 10,566
Tuition mean: $ 38,843.57
Tuition median: $ 39,849
******************************
'''
| true |
ed98d8403425a1bfc37e806fe87ced65ae885eea | chusk2/python-code | /flip_gravity.py | 1,280 | 4.15625 | 4 | """ Kata de codewars.com: https://www.codewars.com/kata/5f70c883e10f9e0001c89673/train/python """
def flip(d, a):
# Do some magic
# el argumento d me indica la dirección a la que se mueven los bloques
# el argumento a me da las cantidades de bloques que hay en cada columna
# a es una lista de números que tengo que ordenar de mayor a menor (si d = L)
# o de menor a mayor (si d = R)
# si se cumple la condición de que d es igual a L, ordénalos de mayor a menor
if d == 'L' :
# ordena la lista en orden de mayor a menor
a.sort( reverse = True)
# el comando return se utiliza para indicarle a la función que devuelva un determinado elemento
# en este caso le indicamos que devuelva la lista ordenada en un sentido u otro
return a
elif d == 'R' :
# ordena la lista en orden de menor a mayor
a.sort()
# devuelve la lista reorganizada
return a
## Ejecuta el programa si quieres ver cómo funciona:
print('\nResultado esperado: [1, 2, 2, 3]')
print( f'\n{ flip( "R", [3, 2, 1, 2] ) } ' )
print('\nResultado esperado: [5, 5, 4, 3, 1]')
print(f'\n{flip("L", [1, 4, 5, 3, 5])}\n') | false |
87bc0218074b1295ce212c9ab5e8253d49fe9575 | mariamGi/guessproject | /main.py | 1,683 | 4.34375 | 4 | # with this function user will guess the random number
import random
def guess(x):
random_number = random.randint(1, x)
answer = 0
chance = 5
while answer != random_number:
answer = input(f'you have {chance} chance.\n enter the number from 1 to {x} :')
chance -= 1
if answer.isdigit():
answer = float(answer)
if answer > random_number:
print(' your number is high')
elif answer < random_number:
print(' your number is law')
else:
print(f'Congratulations you won, your number is {answer}')
else:
print("I can only read numbers, it is'not number.")
break
if chance == 0:
print('Unfortunately you have exhausted your number of attempts, try again.')
break
guess(1)
# with ths function computer will guess the random number
max_number = random.randint(1, 10) # random number is between 1 to 10.
def computer_guess(max_number):
random_numbers = random.randint(1, max_number)
computer_choose = random.randint(1, max_number)
chance = 5
while random_numbers != computer_choose:
print(f'you have {chance} chance.\n enter the number from 1 to {max_number}')
print(computer_choose)
chance -= 1
if random_numbers > computer_choose:
print('your number is law')
elif random_numbers < computer_choose:
print('your number is high')
if chance == 0:
print('No more chances.')
break
computer_guess(max_number)
def add_number(x, y):
return x + y
print(add_number(5, 1))
| true |
d81086a233477f55c8abd835661f79387916f68d | NavinPoonia/Python-Exercises | /Prettify My Folder/Soldier.py | 1,136 | 4.15625 | 4 | # oh soldier prettify my folder
# take a path from user which has folders and files,
# do not change folders only operate on files
# include.txt file which includes names of files and folders we have to capatilize
# capitalize only files and not folders
# ask user to specify any format type files he wants to rename in proper order. example jpg
import os
def soldier(path,file,format):
folder_list=(os.listdir(path))
print(folder_list)
os.chdir(path)
# this file includes name of those files which user wants to capatilaize
f=open(file)
list=f.read().split(",")
print(list)
# loop to capatilize those files
for item in folder_list:
if os.path.isfile(item):
if item in list:
os.rename(item,item.capitalize())
# to rename the files
count=0
for x in folder_list:
if os.path.isfile(x):
format_type=os.path.splitext(x)
if format_type[1]==format and format_type[0]!="exclude":
count=count+1
os.rename(x,f"{count}{format}")
ask=input("enter the path :")
soldier(ask,"include.txt",".jpg") | true |
e56c3a4518f78ad9afae1e6a84bc70c17c54b83a | vatsalgamit/Sorting-Algorithms | /Bubble_Sort.py | 413 | 4.28125 | 4 | #Bubble Sort
list1 = [int(input('Enter Elements: ')) for x in range(int(input('How many elements? : ')))]
print(list1)
def Bubble_Sort(list1):
for i in range(len(list1)-1,0,-1):
for j in range(i):
if list1[j]>list1[j+1]:
#Swapping
# temp = list1[j]
# list1[j]=list1[j+1]
# list1[j+1]=temp
list1[j], list1[j+1] = list1[j+1], list1[j]
print(list1)
Bubble_Sort(list1) | false |
fc4bd5a81ae32454956ba43c716750fe8f03c05f | nsotiriou88/Python | /Training/While and Guess Random.py | 1,228 | 4.28125 | 4 | available_exits = ["east", "north east", "south"]
chosen_exit = ""
while chosen_exit not in available_exits:
chosen_exit = input("Please choose a direction: ")
if chosen_exit == "quit":
print("Game Over")
break
else:
print("aren't you glad you got out of there!")
# Check how the structure of the else is presented.
# It is mixed with the while, and it exits normally,
# it will go to else and print the message.
# Second part with random
import random
highest = 10
answer = random.randint(1, highest)
print("Please guess a number between 1 and {}: ".format(highest))
guess = int(input())
if guess != answer:
if guess < answer:
print("Please guess higher")
else: # guess must be greater than number
print("Please guess lower")
guess = int(input())
if guess == answer:
print("Well done, you guessed it")
else:
print("Sorry, you have not guessed correctly")
else:
print("You got it first time")
# Be aware that with only if statements, we have to implement
# infinate loops almost (up to the max number), in order to ensure
# that the user guesses right at some point. With the use of
# while, we can actually make it work with less code. | true |
32d3fb7d4ecb692eeb89f430d6bc6e83fbd6c3f7 | CuriosityGym/Mentees | /Ishaan Thakker/SieveOfEratosthenes.py | 432 | 4.25 | 4 | primeList=[2]
print ("Enter a Number: ")
a=int(input())
for i in range (3,a):
isPrime=True
#print(primeList)
for prime in primeList:
if i%prime==0:
isPrime=False
#print(str(i) + " is divisible by " +str(prime))
break
if isPrime==True:
primeList.append(i)
print("Numbers which are prime till " +str(a) +" are")
print(primeList)
| false |
08ccf1d13844e53b83679238e8ef4280edbc0f9e | dmaida/document-classifier | /processing.py | 2,640 | 4.15625 | 4 | import re
import sys
#import enchant
def processing(f_in):
"""
Processes a file by doing 3 operations:
1) puts all letters in lowercase
2) removes all non ascii characters and replaces them with spaces
3) compresses all spaces to a single space
"""
f_in = open(f_in, 'r')
input_string = f_in.read() #read in
input_string = input_string.lower() #to lower case
input_string = re.sub("[^0-9a-z]+", ' ', input_string)
input_string = re.sub('\s+', ' ', input_string).strip() #compresses spaces
#print(input_string)
return input_string
def preprocessed_data(f_in):
"""
Method to read in already processed data
for time efficiency.
"""
f_in = open(f_in, 'r')
input_string = f_in.read()
#input_string = processing(f_in)
nput_string = input_string.lower() #to lower case
input_string = re.sub('\s+', ' ', input_string).strip() #compresses spaces
input_string = re.sub("[^0-9a-z]+", ' ', input_string)
#input_string = re.sub(r'\b\w{1,5}\b', '', input_string)
return input_string
def processing_with_autocorrect(directory):
"""
Processing with spell checking.
Spell checking function that autocorrects
using the suggestion method in
the enchant library. The incorrectly spelled
word is replaced with first suggestion of suggestion()
Processes a file by doing 3 operations:
1) puts all letters in lowercase
2) removes all non ascii characters and replaces them with spaces
3) compresses all spaces to a single space
"""
count = 0
for documents in directory:
count = count+1
f_in = open(documents, 'r')
input_string = f_in.read() #read in
input_string = re.sub("[^0-9a-z]+", ' ', input_string)
list_of_words = input_string.split()
d = enchant.Dict("en_US")
for i in range(len(list_of_words)):
if d.check(list_of_words[i]) == False: # if the word is miss spelled
suggestion = d.suggest(list_of_words[i])
if suggestion:
list_of_words[i] = suggestion[0]
processed_string = ' '.join(list_of_words)
processed_string = processed_string.lower() #to lower case
processed_string = re.sub("[^0-9a-z]+", ' ', processed_string)
processed_string = re.sub('\s+', ' ', processed_string).strip() #compresses spaces
path = '/home/daniel/Desktop/AI_Project2/test/'
f = open(path + documents, 'w+')
f.write(processed_string)
print(count,'processing:', documents)
return processed_string
def main(argv):
"""
Main method for running program
Interprets a single command line arg for text processing
"""
if len(argv) < 2:
print("Must provide a file as an argument")
return
processing_with_autocorrect(argv)
if __name__ == '__main__':
main(sys.argv)
| true |
0cf03ae6b4a66838a9c54eca9b1c4fb3cfd92c20 | christianjmd/ds-and-algos | /friends.py | 2,785 | 4.1875 | 4 | """
popular function: returns a list of people who at least n friends.
- each person is identified by the number of their vertex.
- examples:
a) Calling popular(clayton list,2) returns [0,1,2,3].
b) Calling popular(clayton list,3) returns [0].
c) Calling popular(clayton list,0) returns [0,1,2,3,4].
"""
def popular(graph_list, n):
output = []
for i in range(len(graph_list)):
if len(graph_list[i]) >= n:
output.append(i)
return output
"""
friend of a friend function: determines whether two people have exactly one degree
of separation. whether two people aren't friends
but at least one friend in common
- examples: clayton_matrix = [ [0,1,1,1,0],
[1,0,0,1,0],
[1,0,0,0,1],
[1,1,0,0,0],
[0,0,1,0,0] ]
- a) Calling foaf(clayton matrix,0,4) returns True as 0 and 4 are both friends with 2.
b) Calling foaf(clayton matrix,0,3) returns False as 0 and 3 are friends directly.
c) Calling foaf(clayton matrix,1,4) returns False as 1 and 4 have no friends in common.
"""
def foaf(graph_matrix, person1, person2):
counter = 0
if (graph_matrix[person1][person2] == 0) and (graph_matrix[person2][person1] == 0):
for j in range(len(graph_matrix)):
if graph_matrix[person1][j] and graph_matrix[person2][j] == 1:
counter = counter + 1
if counter >= 1:
return True
else:
return False
"""
society function: determines whether a person has two friends who are also friends
with each other.
Input: a nested list graph matrix that represents a graph as an adjacency matrix, that models the friendships
at Monash; and an integer person, where 0 person < number of people on campus.
Output: a boolean,
examples:
a) Calling society(clayton matrix,0) returns True as 1 and 3 are both friends with 0.
b) Calling society(clayton
"""
def society(graph_matrix, person):
friends = []
counter = 0
for i in range(len(graph_matrix)):
if graph_matrix[person][i] == 1:
friends.append(i)
if len(friends) == 2:
if graph_matrix[friends[0]][friends[1]] and graph_matrix[friends[1]][friends[0]] == 1:
counter = counter + 1
if len(friends) > 2:
if graph_matrix[friends[0]][friends[1]] and graph_matrix[friends[1]][friends[0]] == 1:
counter = counter + 1
if graph_matrix[friends[0]][friends[2]] and graph_matrix[friends[2]][friends[0]] == 1:
counter = counter + 1
if graph_matrix[friends[1]][friends[2]] and graph_matrix[friends[2]][friends[1]] == 1:
counter = counter + 1
if counter >= 1:
return True
else:
return False
| true |
1757864c2d096f03659464980170c7cdb7230743 | evank28/ContestCoding | /Learning/learning_Itertools.py | 449 | 4.375 | 4 | import itertools
import operator
#Count function -- begins at START paramater and creates values incremented by STEP parameter
for i in itertools.count(10,3):
print(i)
if i>20:
break
#repeat - itertools.repeat(value,limit)
#accumulate -- takes parameters of a list of values and a function. The iterating calls then use the
#value returned by the last call and the next value in the original list to call the next iteration
| true |
4737ea52e7ae02f39faddbd6b6d8ea9d3071c841 | anuknowndeveloper/randomprojects | /is-it-halloween.py | 547 | 4.375 | 4 | #date library to see what the day is
from datetime import date
#variable decloration
today = date.today()
todayy = str(today)
#if some parts of the variable "todayy" are 10-31 (october 31) then it tells the user yes!
if todayy[5:10] == "10-31":
print('yes, it is halloween!')
#slight rejection
elif toddayy[5:7] == "10":
print("it's not halloween, but it's october.")
daysaway = 31 - int(todayy[8:10])
print('you are: ' + daysaway + ' away from halloween!')
#total rejection
else:
print('nope. too bad bud.')
| true |
c945c6cb60fd280db3df468d2d818660809316bd | yanliang1/Python-test | /Python-03/sequence.py | 1,374 | 4.1875 | 4 | #序列的通用操作
#相加 相乘 切片 长度 成员资格
#字符串列表的加法
str1 = "hello"
str2 = "python"
str3 = str1 + " " + str2
print("str3 = {}".format(str3))
a = [1,2,3]
b = ["hello","world"]
c = a + b
print(c)
print(a)
print(b)
a = (1,2,3)
b = ("hello","world")
c = a + b
print(type(c))
print(c)
print("----------------------------")
# 乘法操作
s1 = "hello"
print("s1.len = {}".format(len(s1)))
s2 = s1 * 3
print("s2 = {}".format(s2))
print("s2.len = {}".format(len(s2)))
d = a * 3
print(type(d))
print(d)
print("-" * 30)
#成员资格
result = "hello" in s2
print("result = {}".format(result))
a = [1,2,3,4]
result = 10 in a
print("result = {}".format(result))
print("---------------------------")
#切片 切取序列中的部分内容
a = [1,2,3,4,5,6,7,8]
b = a[0:3] #序列[开始位置:结束位置] 取值范围 -> [开始位置:结束位置)
print(type(b))
print(b)
string = "hello python"
b = string[1:] #结束位置可省略,表示直到序列结束,开始位置也可省略,表示从零开始
print(type(b))
print(b)
c = a[:] #起始位置和结束位置都可省略,表示为复制
print(type(c))
print(c)
c = a[-5:-2] #索引可以为负值
print(c)
print("-"*30)
a = [1,2,3,4,5]
b = a
print(b)
c = a[:]
print(c)
a[0] = 100
print(a)
print(b)
print(c)
print(a is b) #身份运算符
print(a is c) | false |
01b1b8e6fa43a543d979fb3286c60dfd18f02d26 | yanliang1/Python-test | /Python-03/string.py | 1,883 | 4.28125 | 4 | # find() 查找(*)
# join() 加入
# replace() 替换(*)
# lower() 小写
# split() 切分(*)
# strip() 去空
# format() 格式(*)
# count() 统计
# index() 索引
# endswith() 是否以某字符串结束
# startswith() 是否以某字符串开始
string = "hello python"
print(string)
index = string.find('python') #查找 找到返回其下标,没找到返回-1
print("index =",index)
print("----------------------------------")
path = ["home","gec","tool"] #连接 /home/gec/tool
string = "/".join(path)
print(string)
print(type(string))
print("----------------------------------")
string = "hello"
string2 = '#'.join(string) #连接
print(string2)
print("----------------------------------")
string3 = string2.replace("#",",") #替换
print(string2)
print(string3)
print("----------------------------------")
string = "hello python"
print(string.upper()) #大写:HELLO PYTHON
print(string.lower()) #小写:hello python
print(string.title()) #标题:Hello Ptthon
print("----------------------------------")
path = "/usr/local/arm/bin"
# path = path.replace("/"," ")
# print(path)
res = path.split('/') #切分,默认以空白字符为切分点,也可自己指定切分字符和字符串
print(type(res)) #切分后的得到的是一个列表
print(res)
print("----------------------------------")
string = " hello world "
res = string.strip() #去除字符串两边的空格,返回一个新的字符串
print(string)
print(res)
print("----------------------------------")
a = 10
b = 20
print("{} + {} = {}".format(a,b,a + b)) #格式字符串 # 10 + 20 = 30
print("----------------------------------")
string = "/home/csgec/abc.mp3"
print(string.endswith(".mp3")) #是不是以.mp3结尾
print(string.endswith(".mp4")) | false |
4535a8d02742bc9f2f3822b0e513c32e5c1b2a6d | sabbubajra/School_mgmt | /projectfilehandling.py | 759 | 4.125 | 4 | print('1.Enter the records.')
print('2.Read the records.')
choice=int(input("Enter the choice:"))
cont=True
if(choice==1):
while cont:
name=input('Enter the name:')
address=input('Enter the address:')
phone=input('Enter the phone no:')
course=input('Enter the course:')
file=open('enter.txt','a')
file.write('Name of the student:{}\n'.format(name))
file.write('{} lives in {}\n'.format(name,address))
file.write('Phone no is {}\n'.format(phone))
file.write('{} is studying {}\n'.format(name,course))
file.close()
repeat=input('Do you want to continue(Y/N):')
cont=(repeat=='y')
else:
file=open('enter.txt','r')
print(file.read())
file.close()
| true |
8437a86d3a1351e74aac419f534972a5f9dafbd6 | Aadars/Python-Project-Repo | /02-Code/mall.py | 731 | 4.25 | 4 | print('your welcome in the mall')
print('what you want to buy.')
print('press 1 if you want fruit material')
print('press 2 if you want toys')
print('press 3 if you want mobile phone')
n=int(input("enter the choice wht you want. i'll show you the way "))
if n==1:
fruit={'apple':'40 rs/kg','banana':'50 rs/12p','mango':'80 rs/kg'}
print('we have apple banana and mango to view the rate of fruit press 1 for apple,2 for banana,3 for mango')
a=int(input('select the item what you want'))
if a==1:
k=fruit['apple']
print(k)
elif a==2:
m=fruit['banana']
print(m)
elif a==3:
l=fruit['mango']
print(l)
else:
print("oops! sorry we don't have this food")
| true |
a32aa525e8642b6a355d618d03f1e14dce73aaa2 | Suren76/Python | /python procedural programing/homework6/test.py | 691 | 4.15625 | 4 | # Call function: simple_numbers(0)
# Function return: ()
# Call function: simple_numbers(8)
# Output: (2, 3, 5, 7)
# Call function: simple_numbers(97)
# Function return: (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
def simple_numbers(input_num):
"""
Prints the primes.
"""
all_num = tuple()
for num in range(2, input_num+1):
if num % 2 != 0 and num % 3 != 0 and num % 5 != 0 and num % 7 != 0 \
or num == 2 or num == 3 or num == 5 or num == 7:
all_num += (num,)
return all_num
print(simple_numbers(0), "\n")
print(simple_numbers(8), "\n")
print(simple_numbers(97)) | true |
43dcefe21de19735da50e87b71417e2436edeb01 | Storiesbyharshit/Competetive-Coding | /GeeksforGeeks/Dynamic Programming/Print first n Fibonacci Numbers .py | 704 | 4.21875 | 4 | Print first n Fibonacci Numbers
Given a number N, find the first N Fibonacci numbers. The first two number of the series are 1 and 1.
#Python 3
def printFibb(n):
res = []
a=b=1
if n>=1:
res.append (1)
if n>=2:
res.append (1)
for i in range(2,n):
res.append (a+b)
c=a+b
a=b
b=c
return res
#app2
n = int(input())
if n == 1:
print("1")
break
else:
a = 1
b = 1
print(a, end=" ")
print(b, end=" ")
for j in range(n-2):
c = a + b
a,b = b,c
print(c, end=" ")
print()
| true |
65b14c2897ed8ad8bfc859637adb179d93c4078b | Storiesbyharshit/Competetive-Coding | /GeeksforGeeks/Strings/Check if string is rotated by two place.py | 457 | 4.25 | 4 | #Python 3
###
'''
Function to check if the given string can be obtained
by rotating other string 'p' by two places.
Function Arguments: s (given string), p(string to be rotated)
Return Type: boolean
Contributed By: Nagendra Jha
'''
def isRotated(s,p):
n=len(p)
if(n<3):
return p==s
anticlock_str=p[2:]+p[0:2]
clockwise_str=p[-2]+p[-1]+p[:n-2]
if(s==anticlock_str or s==clockwise_str):
return True
return False
| true |
caf91e8d37a6a9e1e8a1a216eeb2d38e37245cf3 | ansaws/practice_python | /exercise_3.py | 950 | 4.125 | 4 | #sucess
my_list = []
while True:
my_list_len =len(my_list)
append = None
while append == None:
try:
append = input('Do you want to add a number to the list, press y for yes and press n no: ')
except:
print('Please input a y or n')
if append == "y":
while len(my_list) == my_list_len:
try:
my_list.append(int(input("Enter a number to input: ")))
except:
print("add a valid number to the list")
if append == "n":
break
print("These are the items in your list so far: ")
for item in my_list:
print(item)
append_list = []
for item in my_list:
if item<5:
append_list.append(item)
if len(append_list)>0:
print("These are the items in your list that are under 5:")
for item in append_list:
print(item)
if len(append_list)== 0:
print("there are no items in your list") | true |
54dd82292d4f46721bafabe3d50226c4ea5df181 | SACHSTech/ics2o1-livehack---2-oscarlin05 | /problem2.py | 960 | 4.5625 | 5 | """
------------------------------------------------------------------------------
Name: problem2.py
Purpose: a program that calculates the side of the shape if it is a triangle or not.
Author: Lin.O
Created: 23/02/2021
------------------------------------------------------------------------------
"""
print("****** Triangle Calcualtor ******")
#get the three lengths of the triangle
side1 = int(input("Enter the length of the first side: "))
side2 = int(input("Enter the length of the second side: "))
side3 = int(input("Enter the length of the third side: "))
#compute
if side1 >= side2 and side1 >= side3:
largest = side1
othersides = side2 + side3
elif side2 >= side1 and side2 >= side3:
largest = side2
othersides = side1 + side3
elif side3 >= side1 and side3 >= side2:
largest = side3
othersides = side2 + side1
#output
if largest > othersides:
print("The figure is NOT a triangle.")
else:
print("The figure is a triangle.")
| true |
4b535367ffb220db4c483f7129481cd99687cee4 | PopVladCalin/Python_Course | /HelloWorld/4.40 if Statements.py | 648 | 4.1875 | 4 | # name = input("Please enter your name: ")
# age = input("How old are you, {0}? ".format(name))
# print (age)
# We want an integer
name = input("Please enter your name: ")
age = int(input("How old are you, {0}? ".format(name))) # only integers can be tasted, for ex. Twenty will raise an error
print (age)
if age >= 18: #condition
print("You are old enough to vote")
print("Please put an X in the box")
else:
print("Please come back in {0} years".format(18 - age))
if age < 18: #condition
print("Please come back in {0} years".format(18 - age))
else:
print("You are old enough to vote")
print("Please put an X in the box") | true |
01d9eb6eabb3abc6e76c081cc0b3b178bbed24ca | abhisek08/Python-Basics-Part-1- | /current date and time.py | 222 | 4.3125 | 4 | '''
Write a Python program to display the current date and time.
Sample Output :
Current date and time :
2014-07-05 14:34:14
'''
import datetime
c=datetime.datetime.now()
print(c)
d=c.strftime("%Y-%m-%d %H:%M:%S")
print(d) | true |
525bd6f92d6169db214033e45bd9b05c68f422f1 | abhisek08/Python-Basics-Part-1- | /Name reverse.py | 255 | 4.15625 | 4 | '''
Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them.
'''
name=input('Enter your name: ')
lst=[]
for a in name.split():
lst.append(a)
for a in lst[::-1]:
print(a,end=' ') | true |
8da785a3e24e2f50cca8e20703218b4475fc945c | abhisek08/Python-Basics-Part-1- | /printing extension.py | 304 | 4.375 | 4 | '''
Write a Python program to accept a filename from the user and print the extension of that. Go to the editor
Sample filename : abc.java
Output : java
'''
filename=input('Enter a file name: ')
print('filename :',filename)
lst=[]
for a in filename.split('.'):
lst.append(a)
print("Output :",lst[-1]) | true |
d860ea1207b803c1fae3bd48bd55a377066b2149 | svisser/python-3-examples | /examples/strings.py | 1,011 | 4.15625 | 4 | import collections
import collections.abc
def strings_have_format_map_method():
"""
As of Python 3.2 you can use the .format_map() method on a string object
to use mapping objects (not just builtin dictionaries) when formatting
a string.
"""
class Default(dict):
def __missing__(self, key):
return key
print("This prints key1 and key2: {key1} and {key2}".format_map(Default(key1="key1")))
mapping = collections.defaultdict(int, a=2)
print("This prints the value 2000: {a}{b}{c}{d}".format_map(mapping))
class MyMapping(collections.abc.Mapping):
def __init__(self):
self._data = {'a': 'A', 'b': 'B', 'c': 'C'}
def __getitem__(self, key):
return self._data[key]
def __len__(self):
return len(self._data)
def __iter__(self):
for item in self._data:
yield item
mapping = MyMapping()
print("This prints ABC: {a}{b}{c}".format_map(mapping))
| true |
90932cfd47fffb27c5b18a721c97b227b3112739 | misstong/Programming-Language_Udacity | /3/party.py | 595 | 4.25 | 4 | # Bonus Practice: Subsets
# This assignment is not graded and we encourage you to experiment. Learning is
# fun!
# Write a procedure that accepts a list as an argument. The procedure should
# print out all of the subsets of that list.
def sublists(big_list,selected_so_far):
if big_list==[]:
print selected_so_far
else:
current_element=big_list[0]
rest_of_big_list=big_list[1:]
sublists(rest_of_big_list,selected_so_far+[current_element])
sublists(rest_of_big_list,selected_so_far)
dinner_guests=["LM","ECB","SBA"]
sublists(dinner_guests,[])
| true |
4d4eb5318049dfa806f49628d7700b36838b41f3 | arob5/boston-housing-data-clustering-analysis | /pca_analysis.py | 1,337 | 4.21875 | 4 | #
# pca_analysis.py
# Using PCA in conjunction with Kmeans on Boston Housing Dataset
#
# Last Modified: 3/15/2018
# Modified By: Andrew Roberts
#
import run
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
def pca(X, norm=False):
if not norm:
mu = X.mean(0)
X = X - mu
n = X.shape[0]
cov_mat = (X.T @ X) / n
w, v = np.linalg.eig(cov_mat)
v = v[:, np.argsort(w)]
scores = X @ v
X_2 = scores[:, -2:] #@ v[:, -2:].T
return X_2
def show_2D_clusters(X, c, axis1=0, axis2=1):
"""
Visualize the different clusters using color encoding.
:param X: An n-by-d numpy array representing n points in R^d
:param c: A list (or numpy array) of n elements. The ith entry, c[i], must
be an integer representing the index of the cluster that point i belongs
to.
"""
plt.figure()
plt.scatter(X[:, axis1], X[:, axis2], c=c)
plt.title("KMeans on 2D PCA Projection")
plt.xlabel("PC 1")
plt.ylabel("PC 2")
def main():
X, X_norm, features = run.fetch_data()
X_norm = np.delete(X_norm, [3, 8], 1)
X = np.delete(X, [3, 8], 1)
features = np.delete(features, [3, 8], 0)
nclusters = 2
kmeans = KMeans(n_clusters=nclusters, random_state=0).fit(X_norm)
X_2 = pca(X_norm, True)
show_2D_clusters(X_2, kmeans.labels_)
plt.show()
main()
| true |
cb09b4785a93170aae9ee0fedaaab2e9b7612033 | utkarshyadav46/PythonLanguage | /Python Programming/Utkarsh_yadav_13.py | 357 | 4.25 | 4 | #code challenge 13
# this is to print the star pattern
n=input("enter the number of line ")#take the iteger input
for i in range(1,n+1): #this loop is for priting half above pattern
print i * "* "
for j in range(n-1,0,-1): #this loop is for printiing below half pattern
print j * "* "
#this loop is for printing another half pattern
| true |
8068de17547dbed51c6411d393946c4e02b78afd | SundropFuels/gasifier_analysis | /element_parser.py | 2,164 | 4.15625 | 4 | def parse_species(species_str):
"""Parses a molecule into into a dictionary of {element: # of atoms}"""
parsed_elements = {}
current_element = ""
current_number_str = ""
i = 0
if not species_str[0].isalpha():
raise BadCharacterError, "A molecule must start with an alphabetical character"
while i < len(species_str):
current_char = species_str[i]
if current_char.isalpha():
if i+1 == len(species_str) or species_str[i+1].isupper():
#Allows for single character names, like CH4
current_element = "".join([current_element, current_char])
if current_element in parsed_elements.keys():
parsed_elements[current_element] += 1
else:
parsed_elements[current_element] = 1
current_element = ""
else:
current_element = "".join([current_element, current_char])
i += 1
continue
elif current_char.isdigit():
#we have gotten to the end of an element name
while i < len(species_str) and species_str[i].isdigit():
current_char = species_str[i]
current_number_str = "".join([current_number_str, current_char])
i += 1
if current_number_str == '':
raise BadCharacterError, "Each element must have a number associated with it"
if current_element in parsed_elements.keys():
parsed_elements[current_element] += int(current_number_str)
else:
parsed_elements[current_element] = int(current_number_str)
current_element = ""
current_number_str = ""
else:
raise BadCharacterError, "A molecule can only contain alphabetical and numerical characters"
return parsed_elements
if __name__ == "__main__":
f = parse_species("C2H4")
print f
g = parse_species("CH3OH")
print g
m = parse_species("Ar")
print m
| true |
af9967cb964d1647af85fc79ee2c74ae2d97d3b2 | 786440445/leecode | /src/栈队列堆/232.py | 1,554 | 4.375 | 4 | '''
232. 用栈实现队列
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
'''
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack_a = []
self.stack_b = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stack_a.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if not self.stack_b:
for _ in range(len(self.stack_a)):
self.stack_b.append(self.stack_a.pop())
return self.stack_b.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if not self.stack_b:
for _ in range(len(self.stack_a)):
self.stack_b.append(self.stack_a.pop())
return self.stack_b[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return not self.stack_b and not self.stack_a
# Your MyQueue object will be instantiated and called as such:
obj = MyQueue()
obj.push(1)
obj.push(2)
print(obj.pop())
print(obj.peek())
print(obj.empty()) | false |
46255375b88bfa67aebdf4c0f76abed006c4a06c | jdtully/coursera-python | /count_letters.py | 831 | 4.25 | 4 | def count_letters(words):
result = {}
for letter in words:
if letter not in result:
result[letter] = 0
result[letter] += 1
return result
print(count_letters("Dictionaries are mutable, meaning they can be modified by adding, removing, and replacing elements in a dictionary, similar to lists. You can add a new key value pair to a dictionary by assigning a value to the key, like this: animals This creates the new key in the animal dictionary called zebras, and stores the value 2. You can modify the value of an existing key by doing the same thing. So animals would change the value stored in the bears key from 10 to 11. Lastly, you can remove elements from a dictionary by using the del keyword. By doing del animals you would remove the key value pair from the animals dictionary."))
| true |
f03931b6613a4314d723376780eba5b3566830c0 | uma-c/CodingProblemSolving | /recursion/letter_combinations_phone_number.py | 1,164 | 4.25 | 4 | '''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
digits[i] is a digit in the range ['2', '9'].
'''
from typing import List
def letterCombinations(digits: str) -> List[str]:
if digits:
buttons = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r', 's'], ['t', 'u', 'v'], ['w', 'x', 'y', 'z'] ]
a = buttons[int(digits[0]) - 2]
b = []
for d in digits[1:]:
t = int(d) - 2
for j in buttons[t]:
for k in a:
b.append(k + j)
a, b = b, []
return a
else:
return []
if __name__ == "__main__":
print(letterCombinations('234')) | true |
d567ee8c32b0f7744deea7f5d2b3ee55c8c57ec1 | uma-c/CodingProblemSolving | /2-pointer/sliding_window/dynamic_window_size/longest_continuous_increasing_subseq.py | 1,464 | 4.21875 | 4 | '''
Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.
A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].
Example 1:
Input: nums = [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
Example 2:
Input: nums = [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
'''
from typing import List
import unittest
def longest_continuous_increasing_subseq(nums: List[int]) -> int:
if len(nums) < 1:
return 0
i, max_l, l, n = 1, 1, 1, len(nums)
while i < n:
if nums[i - 1] < nums[i]:
l += 1
else:
max_l = max(l, max_l)
l = 1
i += 1
return max(l, max_l)
class Tests(unittest.TestCase):
def test_ex1(self):
self.assertEqual(3, longest_continuous_increasing_subseq([1,3,5,4,7]))
def test_ex2(self):
self.assertEqual(1, longest_continuous_increasing_subseq([2,2,2,2,2]))
if __name__ == "__main__":
unittest.main(verbosity = 2) | true |
2cd5a9a7481ab842c802423e332de2e3861d91d3 | uma-c/CodingProblemSolving | /hash/array_intersection.py | 778 | 4.125 | 4 | '''
349. Intersection of Two Arrays
Easy
1159
1411
Add to List
Share
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:
Each element in the result must be unique.
The result can be in any order.
'''
from typing import List
def intersection(nums1: List[int], nums2: List[int]) -> List[int]:
nums_set = None
nums = None
if len(nums1) > len(nums2):
nums_set = set(nums2)
nums = nums1
else:
nums_set = set(nums1)
nums = nums2
result = []
for num in nums:
if num in nums_set:
result.append(num)
nums_set.remove(num)
return result | true |
c341a8e6df224d699793a266aac3e5ac02ca4b62 | mohamedhassanamara/turtle-race | /main.py | 906 | 4.125 | 4 | import random
from turtle import Turtle, Screen
race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput("Make your bet", "Who you think will win? pick a color")
colors = ["red", "yellow", "green", "purple", "blue", "orange", "pink", "cyan", "grey"]
turtles= []
for i in range(9):
turtles.append(Turtle(shape="turtle"))
turtles[i].color(colors[i])
turtles[i].penup()
turtles[i].goto(x=-230, y=-100+i*30)
if user_bet:
race_on = True
while race_on:
for turtle in turtles:
turtle.forward(random.randint(0,10))
if turtle.xcor() > 230:
race_on = False
win_color = turtle.pencolor()
if win_color == user_bet:
print(f"You've won! The {win_color} is the winner!")
else:
print(f"You've lost! The {win_color} is the winner!")
screen.exitonclick()
| true |
880541e0857c69661276e8a50bbc20f0d6aafa86 | matvey19-meet/YL1-201718 | /Agar.io/ball.py | 1,039 | 4.125 | 4 | import turtle
from turtle import *
turtle.hideturtle()
turtle.penup()
class Ball(Turtle):
def __init__(self, x, y, dx, dy, r, color):
Turtle.__init__(self)
self.penup()
self.x=x
self.y=y
self.dx=dx
self.dy=dy
self.r= r
self.shape("circle")
self.shapesize(self.r/10)
self.color(color)
def move(self, width, height):
self.width=width
self.height=height
current_x=self.xcor()
new_x=current_x+self.dx
current_y=self.ycor()
new_y=current_y+self.dy
self.goto(new_x, new_y)
right_side_ball= new_x + self.r
left_side_ball= new_x - self.r
top_side_ball= new_y + self.r
bottom_side_ball= new_y - self.r
if top_side_ball>= (height/2):
self.dy= -(self.dy)
self.clear()
if bottom_side_ball <= -(height/2):
self.dy= -(self.dy)
self.clear()
if right_side_ball >= (width/2):
self.dx= -(self.dx)
self.clear()
if left_side_ball <= -(width/2):
self.dx= -(self.dx)
self.clear()
# ball1=Ball(0,0,2,5,10,"red")
# while True:
# ball1.move(400,400)
# turtle.mainloop()
| false |
d215ad258230dd69db029c102542f6650c7eca38 | Hander22101998/CHT1Part2Task14 | /task14.py | 547 | 4.375 | 4 | '''Учитывая список чисел, найдите и распечатайте все элементы, которые являются четными
число. В этом случае используйте цикл for, который перебирает список, а не
его показатели! То есть не используйте диапазон (На английском языке, чтобы Вы научились)'''
list_ = [1 , 5 ,7, 8 , 10 , 12 ,9]
for i in list_ :
if i % 2 == 0:
print (i) | false |
5cccd9b9bbc51729ba9186200350cfa6dad3c384 | pvargos17/pat_vargos_python_core | /week_03/labs/06_strings/Exercise_05.py | 617 | 4.5625 | 5 | '''
Write a script that takes a user inputed string
and prints it out in the following three formats.
- All letters capitalized.
- All letters lower case.
- All vowels lower case and all consonants upper case.
'''
def all_caps_lower_vowels(s):
print (s.upper())
print (s.lower())
vowels = "aeiou"
camel = ""
for i in s:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
camel += i.lower()
elif i != "a" or i == "e" or i == "i" or i == "o" or i == "u":
camel += i.upper()
print(camel)
print(all_caps_lower_vowels("patrick"))
| true |
8e767f17bb33c51644368cecc3f0e6765dcf24f4 | pvargos17/pat_vargos_python_core | /week_02/labs/04_conditionals_loops/Exercise_10.py | 545 | 4.25 | 4 | '''
Write a script that prints out all the squares of numbers
from a user inputed lower to a user inputed upper bound.
Use a for loop that demonstrates the use of the range function.
'''
upper = int(input("Please enter uppbound: "))
lower = int(input("Please enter lowerbound: "))
def square():
for i in range(lower, upper+1):
print(i**2)
print(square())
# lower, upper = input("Enter lower and upper bound (both inclusive), \
# separated by a space: ").split()
# for n in range(int(lower), int(upper)+1):
# print(n**2)
| true |
524ff463e33b82d54b3de3fa2e1549c05a3dcb32 | pvargos17/pat_vargos_python_core | /week_03/labs/08_tuples/08_01_make_tuples.py | 620 | 4.34375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
input_l=[1,2,3,4,5,6,7,8,9]
new_tupple = []
def make_tuple(l):
l.sort()
for i in range(0, len(l), 2):
list_slice = l[i:i+2]
if len(list_slice) % 2 != 0:
list_slice.append(0)
tuple_1 = tuple(list_slice)
new_tupple.append(tuple_1)
print(tuple_1)
return new_tupple
print(make_tuple(input_l))
#
| true |
a6d8e698667262f0a525a461b41ae9d0a18a008f | Yunram/python_training | /Programs/day_5.py | 1,147 | 4.125 | 4 | # Password Generator
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome ti the Password Generator by Ramis")
ch_letter = int(input("Please type how many letters do you like in your password?\n"))
ch_symbols = int(input("Please type how many symbols would you like?\n"))
ch_number = int(input("Please type how many number would you like?\n"))
password_list = []
for i in range(1, ch_letter + 1):
password_list += random.choice(letters)
for i in range(1, ch_symbols + 1):
password_list += random.choice(symbols)
for i in range(1, ch_number + 1):
password_list += random.choice(numbers)
random.shuffle(password_list)
password = ""
for char in password_list:
password += char
print("Your new password: " + password)
| false |
ba67eece01b9a7b5b74db41828cf5c82a3e03dad | quadrant26/python_in_crossin | /Lesson/lesson60.py | 1,581 | 4.15625 | 4 | import random
print( random.randint(1, 100) ) #可以生成一个a到b间的随机整数,包括a和b。
print( random.random() ) #生成一个0到1之间的随机浮点数,包括0但不包括1
# print( random.uniform(a, b))
# 生成a、b之间的随机浮点数。不过与randint不同的是,a、b无需是整数,也不用考虑大小。
print( random.uniform(1.5, 3))
print( random.uniform(3, 1.5))
# random.choice(seq)
# 从序列中随机选取一个元素。seq需要是一个序列,比如list、元组、字符串。
print( random.choice([1, 2, 3, 5, 8, 13]) ) #list
print( random.choice('hello') ) #字符串
print( random.choice(['hello', 'world']) ) #字符串组成的list
print( random.choice((1, 2, 3)) ) #元组
# random.randrange(start, stop, step)
# 生成一个从start到stop(不包括stop),间隔为step的一个随机数。start、stop、step都要为整数,且start<stop。
# start和step都可以不提供参数,默认是从0开始,间隔为1。但如果需要指定step,则必须指定start。
print( random.randrange(1, 9, 2)) # 就是从[1, 3, 5, 7]中随机选取一个。
print( random.randrange(4) ) #[0, 1, 2, 3]
print( random.randrange(1, 4)) #[1, 2, 3]
# print( random.randrange(start, stop, step)
# 其实在效果上等同于 print( random.choice(range(start, stop, step))
# random.sample(population, k)
# 从population序列中,随机获取k个元素,生成一个新序列。sample不改变原来序列。
# random.shuffle(x)
# 把序列x中的元素顺序打乱。shuffle直接改变原有的序列。
| false |
107824fc69ae97b4b25907551eaaf50e9b9ac3a9 | sservett/python | /PDEV/SECTION4/hw402.py | 829 | 4.40625 | 4 | print("""=================================================
Please enter 3 number, the highest one will be printed..
================================================="""
)
a = int(input("1st Number : "))
b = int(input("2nd Number : "))
c = int(input("3rd Number : "))
if a > b and a > c :
print("The Highest Number is {}".format(a))
elif b > a and b > c :
print("The Highest Number is {}".format(b))
elif c > a and c > b :
print("The Highest Number is {}".format(c))
elif a == b and b > c :
print("1st and 2nd Numbers are Equal and the number is {}".format(a))
elif a == c and a > b :
print("1st and 3rd Numbers are Equal and the number is {}".format(a))
elif b == c and b > a :
print("2nd and 3rd Numbers are Equal and the number is {}".format(b))
else:
print("All Numbers are Equal!!")
| false |
0a6483f7445505d99eee2522b919594c10256a33 | vmchenni/PythonPractice | /Factorial.py | 398 | 4.3125 | 4 | # Factorial of a number to be calculated
number = 5
fact = 1
if number == 0:
print("Factorial of ", number, " is ", number)
elif number == 1:
print("Factorial of ", number, " is ", number)
else:
for num in range(1, number+1):
fact = fact * num
print("Factorial of ", number, " is ", fact)
# Check if number is odd
if fact % 2 == 0:
print("Even")
else:
print("odd")
| true |
a8375441aa2b92b7c9687d702401ba35ff7917f1 | JohnnyAIO/Python | /Exercise2.py | 954 | 4.125 | 4 | print("Universidad Central de Venezuela")
print("Facultad de Ciencias - Escuela de Computación")
print("Developer: Jonathan Torres C.I - 25.211.873")
print("Ejercicio 2")
a = int(input("Ingrese un numero: "))
b = int(input("Ingrese otro numero: "))
c = int(input("Ingrese un ultimo numero: "))
if a > b:
if a > c:
print("El mayor es: %d (a)" % a)
print("El medio es: %d (b)" % b) #correcto
print("El menor es: %d (c)" % c)
print(a, b, c)
else:
print("El mayor es: %d (c)" % c)
print("El medio es: %d (a)" % a) #correcto
print("El menor es: %d (b)" % b)
print(c, a, b)
elif b > c:
print("El mayor es: %d (b)" % b)
print("El medio es: %d (c)" % c) #correcto
print("El menor es: %d (a)" % a)
print(b, c, a)
else:
print("El mayor es: %d (c)" % c)
print("El medio es: %d (b)" % b) #correcto
print("El menor es: %d (a)" % a)
print(c, b, a)
| false |
6a63aff412f24dacf98a600b9704f99709302b3c | JohnnyAIO/Python | /Methodo_Lista.py | 892 | 4.375 | 4 | #!/usr/bin/python
#Programa de prueba
pi = 3.141516
l1 = ["Numero", "Letra",[23,pi,278],"variable"]
l2 = ["Cesar", "Octavio", "Mario"]
print "Buscar el indice de la lista -variable-"
print l1.index("variable")
print "\n"
print "Agregar un elemento en la ultima lista"
print l1.append("constante")
print "\n"
print "Contar veces que aparece el valor -variable-"
print l1.count("variable")
print "\n"
print "Insetar un valor en el indice seleccionado"
l1.insert(2, "Valor Nuevo")
print l1
print "\n"
print "Agregar una lista a una cadena"
l1.extend(l2)
print l1
print "\n"
l1.pop(2)
print "Eliminar el valor del indice seleccionado"
print l1
print "\n"
l1 = ["Letra", "Numero", "Variable", "Incognita"]
l1.remove("Numero")
print "Lista nueva sin el numero"
print l1
print "\n"
l1 = ["Numero", "Letra",[23,pi,278],"variable"]
print "Invirtiendo el orden de la lista"
l1.reverse()
print l1
| false |
4d0cad841fd078b8a707e8094165cfdc3aac4030 | saravana1992/python_code | /check_number.py | 227 | 4.1875 | 4 | x=int(input("enter the number"))
if x==1:
print("number is one")
elif x==2:
print("number is two")
elif x==3:
print("number is three")
elif x==0:
print("number is zero")
else:
print("number is above three") | true |
e522269907d68d81a57cc841e5dd4e3a990bd77d | naffi192123/Python_Programming_CDAC | /Day1/8-userinputtype.py | 206 | 4.15625 | 4 | # find the type of number
var = input("Enter the number: ")
print("type of number is: ",type(var))
num = int(var)
num2 = float(var)
print(" new type is: ", type(num))
print(" new type is: ", type(num2))
| true |
4fbf6f8cdc9d14d3b136a9961d4ced80f183657b | AnmolTomer/lynda_programming_foundations | /04_Algorithms/04_03.py | 1,159 | 4.125 | 4 | # Merge Sort: D&C Algo, Breaks data into individual pieces and merges them, uses recursion to operate on datasets. Key is to understand how to merge 2 sorted arrays.
items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53]
def mergesort(dataset):
if len(dataset) > 1:
mid = len(dataset) // 2
leftarr = dataset[:mid]
rightarr = dataset[mid:]
# TODO: Recursively break down the arrays
mergesort(leftarr)
mergesort(rightarr)
# TODO: Perform merging
i = 0 # index into the left array
j = 0 # index into the right array
k = 0 # index into the merger array
while i < len(leftarr) and j < len(rightarr):
if(leftarr[i] <= rightarr[j]):
dataset[k] = leftarr[i]
i += 1
else:
dataset[k] = rightarr[j]
j += 1
k += 1
while i < len(leftarr):
dataset[k] = leftarr[i]
i += 1
k += 1
while j < len(rightarr):
dataset[k] = rightarr[j]
j += 1
k += 1
print(items)
mergesort(items)
print(items)
| true |
6bae12413031c41501919528c67b2c20b953d6ea | xilixjd/leetcode | /Linked List/148. Sort List (medium).py | 1,528 | 4.125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'xilixjd'
'''
Sort a linked list in O(n log n) time using constant space complexity.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
h = head
length = 0
while h:
length += 1
h = h.next
if length <= 1:
return head
p1 = head
slow = fast = head
while slow.next and fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
p2 = slow.next
slow.next = None
left = self.sortList(p1)
right = self.sortList(p2)
return self.merge_list(left, right)
def merge_list(self, listNode1, listNode2):
root = ListNode(0)
p = root
p1 = listNode1
p2 = listNode2
while p1 and p2:
if p1.val < p2.val:
p.next = p1
p = p.next
p1 = p1.next
else:
p.next = p2
p = p.next
p2 = p2.next
if p1:
p.next = p1
if p2:
p.next = p2
return root.next
l = ListNode(3)
l.next = ListNode(2)
l.next.next = ListNode(4)
# l.next.next.next = ListNode(1)
re = Solution()
l = re.sortList(l)
while l:
print l.val
l = l.next
| true |
8d8ee00f1635ef440d7978f6452a8613ff2a7dbf | xilixjd/leetcode | /Tree/110. Balanced Binary Tree (easy).py | 1,748 | 4.28125 | 4 | # -*- coding:utf-8 -*-
'''
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ReSolution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def get_depth(root):
left_depth = right_depth = 1
if root is None:
return 0
if root.left:
left_depth = 1 + get_depth(root.left)
if root.right:
right_depth = 1 + get_depth(root.right)
return left_depth if left_depth > right_depth else right_depth
if root is None:
return True
left = get_depth(root.left)
right = get_depth(root.right)
if abs(left - right) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
if abs(self.height(root.left) - self.height(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def height(self, node):
if node is None:
return 0
left = 1
right = 1
left += self.height(node.left)
right += self.height(node.right)
return left if left > right else right | true |
faeac22f247a65deea0895b1cd5bed4715c00576 | xilixjd/leetcode | /Linked List/21. Merge Two Sorted Lists(easy).py | 1,808 | 4.15625 | 4 | '''
Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class ReSolution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
n = root = ListNode(0)
p1 = l1
p2 = l2
while p1 and p2:
if p1.val < p2.val:
n.next = p1
p1 = p1.next
else:
n.next = p2
p2 = p2.next
n = n.next
if p1:
n.next = p1
if p2:
n.next = p2
return root.next
n1 = ListNode(1)
n1.next = ListNode(3)
n1.next.next = ListNode(5)
n2 = ListNode(2)
n2.next = ListNode(4)
n2.next.next = ListNode(6)
re = ReSolution()
print re.mergeTwoLists(n1, n2).next.val
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
n = head = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
n.next = l1
l1 = l1.next
else:
n.next = l2
l2 = l2.next
n = n.next
if l1:
n.next = l1
if l2:
n.next = l2
return head.next
# n1 = ListNode(1)
# n1.next = ListNode(3)
# n1.next.next = ListNode(5)
#
# n2 = ListNode(2)
# n2.next = ListNode(4)
# n2.next.next = ListNode(6)
#
# solu = Solution()
# print solu.mergeTwoLists(n1, n2).next.val | true |
a815eba7c8cd894dcc5403418163bd74e9b23192 | xilixjd/leetcode | /Tree/199. 二叉树的右视图(medium).py | 1,189 | 4.3125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'xilixjd'
'''
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
array = [root]
res = []
while len(array) != 0:
temp = [a.val for a in array]
res.append(temp)
temp = []
for a in array:
if a.left:
temp.append(a.left)
if a.right:
temp.append(a.right)
array = temp
return [re[-1] for re in res] | true |
fed109cc60966e89e62fe5d89636b9cec7074713 | xilixjd/leetcode | /剑指offer/104. Maximum Depth of Binary Tree (easy).py | 853 | 4.15625 | 4 | '''
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
leftDepth = 1
rightDepth = 1
leftDepth += self.maxDepth(root.left)
rightDepth += self.maxDepth(root.right)
return leftDepth if leftDepth > rightDepth else rightDepth
root = TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(1)
root.left.right = TreeNode(1)
solu = Solution()
print solu.maxDepth(root) | true |
0d166e69e46aa9bc68abb2a4f8384c934481bd6c | xilixjd/leetcode | /Array/189. Rotate Array(easy).py | 1,485 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
'''
class ReSolution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
nums = nums[k + 1:] + nums[:k + 1]
print nums
re = ReSolution()
re.rotate([1,2,3,4,5,6,7], 3)
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
nums[:] = nums[n-k:] + nums[:n-k]
return nums
def rotate2(self, nums, k):
'''
Step 1 - 12345 6789 ---> 54321 6789
Step 2 - 54321 6789 ---> 54321 9876
Step 3 - 543219876 ---> 678912345
'''
n = len(nums)
k = k % len(nums)
self.reverse(0, n - k - 1, nums)
print nums
self.reverse(n - k, n - 1, nums)
print nums
self.reverse(0, n - 1, nums)
return nums
def reverse(self, start, end, nums):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
solu = Solution()
print solu.rotate2([1,2], 0) | false |
659ed9c877fb587b4ac4139beb83ce767fc80814 | xilixjd/leetcode | /Tree/95. Unique Binary Search Trees II (medium 太难不会,递归).py | 1,543 | 4.1875 | 4 | # -*- coding: utf-8 -*-
'''
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
https://yq.aliyun.com/articles/3692
"""
def generate(start, end):
sub_tree = []
if start > end:
sub_tree.append(None)
return sub_tree
for i in range(start, end + 1):
left_sub_tree = generate(start, i - 1)
right_sub_tree = generate(i + 1, end)
for j in range(len(left_sub_tree)):
for k in range(len(right_sub_tree)):
node = TreeNode(i)
node.left = left_sub_tree[j]
node.right = right_sub_tree[k]
sub_tree.append(node)
return sub_tree
if n <= 0:
return generate(1, 0)
else:
return generate(1, n)
solu = Solution()
print solu.generateTrees(3) | true |
9a995024a90cb42eb272825f0770c51061970b72 | mcraipea/Bootcamp__python | /ML/Day_00/ex01/mean.py | 523 | 4.1875 | 4 | import numpy as np
def mean(x):
"""Computes the mean of a non-empty numpy.ndarray, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The mean as a float.
None if x is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if len(x) == 0:
return None
moy = 0.0
for i in range(0, len(x)):
moy += float(x[i])
moy /= len(x)
return moy
#X = np.array([0, 15, -9, 7, 12, 3, -21])
#print(mean(X))
#X = np.array([0, 15, -9, 7, 12, 3, -21])
#print(mean(X ** 2)) | true |
cac3332148fccf8b20e4044d0b88949e73c11a1f | kyleanthony8/python_assignments | /python_oop_assignments/bike_oop.py | 2,079 | 4.71875 | 5 | # Assignment: Bike
# Create a new class called Bike with the following properties/attributes:
#
# price
# max_speed
# miles
# Create 3 instances of the Bike class.
#
# Use the __init__() function to specify the price and max_speed of each instance (e.g. bike1 = Bike(200, "25mph"); In the __init__() also write the code so that the initial miles is set to be 0 whenever a new instance is created.
#
# Add the following functions to this class:
#
# displayInfo() - have this method display the bike's price, maximum speed, and the total miles.
# ride() - have it display "Riding" on the screen and increase the total miles ridden by 10
# reverse() - have it display "Reversing" on the screen and decrease the total miles ridden by 5...
# Have the first instance ride three times, reverse once and have it displayInfo(). Have the second instance ride twice, reverse twice and have it displayInfo(). Have the third instance reverse three times and displayInfo().
#
# What would you do to prevent the instance from having negative miles?
#
# Which methods can return self in order to allow chaining methods?
#Bike OOP Assignment
class bike(object):
#Called init first since it is called every time there is a new instance
def __init__(self,price, max_speed):
self.price = price
self.max = max_speed
self.miles = 0
def displayInfo(self):
print "Bike price is %s" %(self.price)
print "Bike max speed is %s" %(self.max)
print "Total miles travelled are %s" %(self.miles)
def ride(self):
print "Riding"
self.miles += 10
def reverse(self):
print "Reversing"
if self.miles >= 5:
self.miles -= 5
elif self.miles < 5:
self.miles = 0
#the above is so that we do not have negative miles, so if it is less than 5, the total goes to 0
#Trial run
my_bike = bike(100.00, 30)
my_bike.displayInfo()
my_bike.ride()
my_bike.ride()
my_bike.ride()
my_bike.ride()
my_bike.ride()
my_bike.reverse()
my_bike.reverse()
my_bike.reverse()
my_bike.displayInfo()
| true |
453bbc36f9f203fbd0c8be88989d4c8501d2765f | kyleanthony8/python_assignments | /python_basics/dict_basics.py | 787 | 4.5625 | 5 | # Assignment: Making and Reading from Dictionaries
# Create a dictionary containing some information about yourself. The keys should include name, age, country of birth, favorite language.
#Making and Reading from Dictionaries
def info(name, age, bp, favelang): #this allows user to input whatever name, age, bp, and fave lang values
details = {} #this is creating an empty dictionary which will be filled with the inputted info
details["name"] = name
details["age"] = age
details["bp"] = bp
details["favelang"] = favelang
print "My name is", str(details["name"]) #now here we retrieve that info and print
print "My age is", str(details["age"])
print "My birthplace is", str(details["bp"])
print "My favorite language is", str(details["favelang"])
| true |
7fc2aa21d6671fc280b6c4af567f3a2a524fba64 | kyleanthony8/python_assignments | /python_basics/compare_arr_basics.py | 1,740 | 4.34375 | 4 | # Assignment: Compare Arrays
# Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
#
# Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same."
#
#Compare Arrays
def comp(one, two): #defining with two arrays being inputted
same = 0 #to keep track of amount of values that are the same
if isinstance(one, list) and isinstance(two, list): #verifying that inputs are lists
if len(one) >= len(two): #if the lengths of the arrays are diff you have to change the range
for x in range(0,len(two)):
if one[x] == two[x]:
same += 1
else:
print "The lists are not the same."
break
if same == len(one) and same == len(two):
print "The lists are the same."
else:
print "The lists are not the same."
elif len(two) > len(one):
for x in range(0, len(one)):
if one[x] == two[x]:
same += 1
else:
print "The lists are not the same."
break
if same == len(one) and same == len(two): #this verifies that the lists are exactly the same, as in the lengths are the same
print "The lists are the same."
else: #if one array is the same but is shorter and is missing values, then they technically are not the same
print "The lists are not the same."
else:
print "You did not input valid lists/arrays."
| true |
fdf12e497232af7981c7631e63a78fa415fa8fc1 | Alef-Martins/Exercicios_python_mundo-1 | /Mundo 1/ex022.py | 610 | 4.25 | 4 | #Crie um programa que leia o nome completo de uma pessoa e mostre:
#O nome com todas as letras maiúsculas e minúsculas, Quantas letras ao todo (sem considerar os espaços), Quantas letras tem o primeiro nome.
nome = input('Digite seu nome: ')
print(f'Seu nome em maiúsculas é {nome.upper()}')
print(f'Seu nome em minúsculas é {nome.lower()}')
new_var = len(nome.replace(' ', ''))
print(f'Seu nome tem ao todo {new_var} letras')
nome = nome.split()
primeiro_nome = nome[0]
print(f'Seu primeiro nome é {primeiro_nome}')
primeiro_nome = len(nome[0])
print(f'Seu primeiro nome tem {primeiro_nome} letras')
| false |
e88f3ee8297c13aed65f5bbe05cab5629b26e44e | buhanec/euler | /034_2.py | 524 | 4.125 | 4 | #!/usr/bin/env python3
"""
Project Euler #34.
Find the sum of all numbers which are equal to the sum of the
factorial of their digits.
"""
from math import factorial
from itertools import combinations_with_replacement as cwr
FACTORIALS = {str(i): factorial(i) for i in range(10)}
factorial_sum = 0
for n in range(2, 7):
for c in cwr(map(str, range(0, 10)), n):
c_sum = sum(map(FACTORIALS.__getitem__, c))
if sorted(c) == sorted(str(c_sum)):
factorial_sum += c_sum
print(factorial_sum)
| true |
895b6aed471aef6f1dff4aefe4293c104e749a6d | mpigelati/B_Python_work | /Assain/More_data_type/3-tuples.py | 2,056 | 4.28125 | 4 | tuple1 = (123, 'abcdef')
tuple2 = (123, 'abb')
print cmp(tuple1, tuple2)
print cmp(tuple2, tuple2)
print cmp(tuple2, tuple1)
print cmp(tuple1, (123, 'abe'))
print ""
print cmp((123, 'abc'), (123, 'abc'))
print cmp((123, 'abc'), (123, 'abz'))
print cmp((123, 'abc'), (123, 'aba'))
print cmp((123, 'abc'), (123, 'abaxyz'))
print cmp((123, 'abc'), (123, 'abdxyz'))
print cmp((123, 'abc'), ('123', 'abdxyz'))
print ""
#tuple3 = tuple2 + ('823')
tuple3 = tuple2 + tuple("823")
print tuple3
print cmp(tuple2, tuple3)
print ""
tuple1 = tuple('823')
print tuple1
print type(tuple1)
print ""
tuple1 = (123, '283')
print tuple1
print type(tuple1)
print tuple1[0]
print type(tuple1[0])
print tuple1[0]+5
print type(tuple1[1])
print tuple1[1]*5
print int(tuple1[1])+5
print str(tuple1[0])[0]
print tuple1[1][0]
tuple1 = (123, '283')
tuple2 = (123, 'abb')
print "First tuple length : ", len(tuple1)
print "Second tuple length : ", len(tuple2)
tuple1 = ('1834', 98346)
print "tuple1 :", tuple1
print "tuple2 :", tuple2
print dir(tuple1)
print "Max value element tuple1: ", max(tuple1)
print "Max value element tuple2: ", max(tuple2)
print "min value element : ", min(tuple1)
print "min value element : ", min(tuple2)
print ""
aList = [123, 'xyz', 'zara', 'abc'];
aTuple = tuple(aList)
print "Tuple elements : ", aTuple
print type(aTuple)
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0] : ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
#tup1[0] = 100;
#tup1.append(4)
#del tup1;
print ""
print "tup1 :", tup1
tup3 = tup2 + tup1 + tup2 + (2, 3, 4, 5)
print "tup3 :", tup3
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
(name, surname, b_year, movie, m_year, profession, b_place) = julia
print name, surname
print ""
months = (' ', 'January','February','March','April','May','June', 'July','August','September','October','November',' December')
print "months :", months
print ""
x = 8
print months[x]
print len(months)
#months.sort()
print "months :", months
exit(1)
| false |
ee570c84488827fc9db581f9586e106fc7967214 | aimeepearcy/Coderbyte-Solutions-Python-Easy | /03. LongestWord.py | 844 | 4.4375 | 4 | # Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string.
# If there are two or more words that are the same length, return the first word from the string with that length.
# Ignore punctuation and assume sen will not be empty.
def LongestWord(sen):
newStr = ""
# Remove all non-ascii characters from the string
for letter in sen:
if letter.isalnum() or letter == " ":
newStr += letter
# Split the sentence into individual words and add them to a list
separateWords = newStr.split(" ")
# Use built in Python function, max, using length as a parameter of key to find the longest word
longest = max(separateWords, key=len)
return longest
# keep this function call here
print(LongestWord(raw_input()))
| true |
8590b59bbd5718bb41a3f504a1e3a2ad69315857 | ryumanji/PythonSutudy | /退屈なことはPythonにやらせよう/print_table.py | 1,414 | 4.21875 | 4 | #! python
# print_table.py - リストの中身を整理して表示する
table_data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def print_table(data):
values_0 = ''
values_1 = ''
values_2 = ''
values_3 = ''
max_length_list = [[],[],[],[]]
for value in range(len(data)):
for i in range(len(data)+1):
#print(data[value][i])
length = len(data[value][i]) # 要素の文字数を計算
if i == 0 :
max_length_list[i].append(length)
values_0 += data[value][i]
elif i == 1 :
max_length_list[i].append(length)
values_1 += data[value][i]
elif i == 2 :
max_length_list[i].append(length)
values_2 += data[value][i]
elif i == 3 :
max_length_list[i].append(length)
values_3 += data[value][i]
max_length_list[i].sort(reverse = True)
while len(max_length_list[i]) != 1:
del max_length_list[i][1]
print(max_length_list)
print(values_0)
print(values_1)
print(values_2)
print(values_3)
print_table(table_data)
| false |
c1ac1b8493b89dc22d668888fe95f4f656363f7d | lilindian16/UniBackup | /2017/COSC121/Labs/Sets and Dictionaries/Finding keys.py | 289 | 4.21875 | 4 | def find_key(input_dict, value):
"""THIS FUNCTION FINDS THE KEY OF THE VALUE THAT IS ENTERED IN
"""
if value in input_dict.values():
for key in input_dict:
if input_dict[key] == value:
return key
else:
return None
| true |
a245639972df7cc89ba18d9cffc79a5eadeab24b | lilindian16/UniBackup | /2017/COSC121/Assignments/Assignment 3/Question 1.py | 2,449 | 4.21875 | 4 | from datetime import date
def calc_average(value_of_day):
"""This finds and returns the average reading of PM10 for each day from the
selected file
"""
if len(value_of_day) > 0:
days_total = 0
for value in value_of_day:
if value is not None:
days_total += value
if len(value_of_day) > 0:
days_average = days_total / len(value_of_day)
else:
days_average = None
else:
days_average = None
return days_average
def max_day(value_of_day):
"""This determines and returns the maximum PM10 reading for each day from
the selected file
"""
if len(value_of_day) > 0:
maximum_day = value_of_day[0]
for value in value_of_day:
if value > maximum_day:
maximum_day = value
else:
maximum_day = None
return maximum_day
def value_day(lines_of_data):
"""This finds each day that needs to be analysed by the program and returns
the days in a list
"""
value_of_day = []
for value in lines_of_data:
floating_value = float(value)
if floating_value >= 0:
value_of_day.append(floating_value)
return value_of_day
def date_proper(date_data_taken):
"""This creates a properly formatted date and returns it
"""
year_number = int(date_data_taken[0:4])
month_number = int(date_data_taken[5:7])
date_number = int(date_data_taken[8:10])
date_correct_format = date(year_number, month_number, date_number)
return date_correct_format
def create_summary(lines):
"""This is the function that creates the summary for each day and returns
it
"""
summaries = []
for line in lines:
lines_of_data = line.strip().split(',')
date_data_taken = lines_of_data[0]
lines_of_data = lines_of_data[1:]
value_of_day = value_day(lines_of_data)
maximum_day = max_day(value_of_day)
days_average = calc_average(value_of_day)
date_correct_format = date_proper(date_data_taken)
summary_tuple = (date_correct_format, maximum_day, days_average)
summaries.append(summary_tuple)
return summaries
def day_summaries(lines):
"""This is the main function that combines the summaries for each day and
returns the whole summary
"""
summaries = create_summary(lines)
summaries.sort()
return summaries
| true |
7d9db9d4d067ad59fd79e34fb72a11d9b6237035 | jakdept/pythonbook | /ch4/comma_code.py | 758 | 4.25 | 4 | #!/usr/bin/env python3
'''
Chapter 4 of Automate the Boring Stuff
The first assignment for this chapter is to write a program - comma_code.py
This program includes the function `comma_code(list)` to process one step of the sequence.
Included is a second way to do this easier with join() - a function not yet introduced.
'''
# ch4 problem - https://automatetheboringstuff.com/chapter4/
# Written by Jack Hayhurst
def comma_code(parts):
'''comma_code joints the elements in a list with an oxford comma'''
output = ''
for word in parts[:-1]:
output += str(word)
output += ', '
output += 'and '
output += str(parts[-1])
return output
if __name__ == "__main__":
print('there is no default action defined for this file')
| true |
14348fd45a6296446c27a801720a9c512d4b15d2 | Saranya-sharvi/saranya-training-prgm | /facto.py | 273 | 4.28125 | 4 | number=int(input("Enter the number:"))
factorial=1
if number>0:
for i in range(1,number+1):
factorial=factorial*i
print("factorial of",number,"is",factorial)
elif number==0:
print("factorial of 0 is 1")
else:
number<0
print("dsnt find fact for neg numbers")
| true |
7895efa20450de674f36518e9e7e0a175d2dd73e | Saranya-sharvi/saranya-training-prgm | /exc-pgm/sorting.py | 618 | 4.375 | 4 | """make the program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score"""
#importing itemgetter is used to enable multiple sort
from operator import itemgetter, attrgetter
l = []
while True:
s = input()
if not s:
break
#append the user input and it is splited under comma
l.append(tuple(s.split(",")))
#print the appropriate result
print(sorted(l, key=itemgetter(0,1,2)))
| true |
ce258c4cff2417409af3af592c3a6e12ce1a8bfd | Saranya-sharvi/saranya-training-prgm | /exc-pgm/oddnum.py | 292 | 4.1875 | 4 | """ make the program to get number of integer values from user seperated usinf comma and then print only the odd numbers"""
values = input()
#split the odd numbers among user input
numbers = [x for x in values.split(",") if int(x)%2!=0]
#print the appropriate result
print(",".join(numbers))
| true |
5adb4e5059b41241d6ddeb46e934454d6e1dfbdf | Saranya-sharvi/saranya-training-prgm | /exc-pgm/array.py | 230 | 4.375 | 4 | """write a program generate a 3*5*8 3D array whose each element is 0"""
#Using list comprehension to make an array
array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
#print the 3d array
print(array)
| true |
7519dc20247459b518ac9b9806e22f7149dea8fd | RoamHz/LearnAlgorithm | /LeetCode8.py | 2,717 | 4.375 | 4 | '''
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found.
Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
'''
MIN = -2**31
MAX = 2**31 -1
import re
# def myAtoi(str):
# """
# :type str: str
# :rtype: int
# """
# str = str.strip(' ')
# MIN = -2**31
# MAX = 2**31 -1
# numlst = []
# if str == '':
# return 0
# for i in str.split(' '):
# try:
# i = float(i)
# numlst.append(i)
# except Exception:
# pass
# if numlst[0] < MIN:
# print(MIN)
# elif numlst[0] > MAX:
# print(MAX)
# else:
# print(numlst[0])
# def myAtoi(str):
# MIN = -2**31
# MAX = 2**31 -1
# if not str:
# return 0
# str = str.strip()
# number, flag = 0, 1
# if str[0] == '-':
# str = str[1:]
# flag = -1
# elif str[0] == '+':
# str = str[1:]
# for c in str:
# if c >= '0' and c <= '9':
# number = 10 * number + ord(c) - ord('0')
# else:
# break
# number = flag * number
# number = number if number <= MAX else MAX
# number = number if number >= MIN else MIN
def myAtoi(str):
str = str.strip()
str = re.findall(r'(^[\+\-0]*\d+)', str)
try:
result = int(''.join(str))
# print(result)
if result > MAX > 0:
return MAX
elif result < MIN < 0:
return MIN
else:
return result
except:
return 0
if __name__ == '__main__':
s = '42 sdg 56 74574 '
atoi = myAtoi(s)
print(atoi) | true |
0f71f9c560642588ce8c1f9762db9ee38dab605a | wanmuz86/maths-kpmb | /factorial.py | 539 | 4.53125 | 5 | # Create a function to calculate factorial, for example
# factorial(5) = 1 x 2 x 3 x 4 x 5 = 120
# without recursion
def factorial(number):
answer = 1;
if (number == 0):
return 1
else:
for n in range(1,number+1):
answer = answer * n
return answer
print(factorial(5))
# with recursion
# 1) We declare a stopper.. f(0) = 1
# 2) We declare the function by calling previous function
def factorial_recursive(number):
if number == 0:
return 1
else:
return number * factorial_recursive(number-1)
print(factorial_recursive(4))
| true |
118c2195bdb2d312450c6136c014cbf9b6052f40 | aahmetyildiz/Python3_Accenture | /rock_paper_scissors.py | 2,838 | 4.15625 | 4 | #Class for random PC choice
import random
#Define variables for score
user_score = 0
pc_score = 0
values = ['r','p','s']
#Function for control user input
def input_control (user_input):
if user_input in values :
if user_input == 'r':
print('You choose "Rock"')
elif user_input == 'p':
print('You choose "Paper"')
else:
print('You choose "Scissors"')
#If user choose valid value write choice and return input
return user_input
else:
print('Please write valid character. Write "r" for Rock, "p" for Paper, "s" for Scissors.')
# If user choose invalid value return fail
return 'fail!'
#Function for random pc choice
def pc_choice():
pc_rnd = random.choice(values)
return pc_rnd
#Function for match choices
def match(user, pc):
if user == "r" and pc == "s":
print("Rock smashes Scissors. You win!")
return "user"
elif user == "s" and pc == "r":
print("Rock smashes Scissors. PC win!")
return "pc"
elif user == "s" and pc == "p":
print("Scissors cut Paper. You win!")
return "user"
elif user == "p" and pc == "s":
print("Scissors cut Paper. PC win!")
return "pc"
elif user == "p" and pc == "r":
print("Paper wraps Rock. You win!")
return "user"
elif user == "r" and pc == "p":
print("Paper wraps Rock. PC win!")
return "pc"
else:
print("Equality")
return "eq"
#Game continue in a loop since user exit.
while True:
# Print a blank row for separate rounds.
print("")
#Define user input and control its validity with input_control() function defined before. user_value define as result of control
user_input = input('What\'s your choice? Write "r" for Rock, "p" for Paper, "s" for Scissors:')
user_value = input_control(user_input)
#user input not valid error message write at input_control function and loop go to start again.
if user_value == 'fail!':
continue
else:
#If user input is valid first random pc choice generated.
pc_value = pc_choice()
if pc_value == 'r':
print('PC choose "Rock"')
elif pc_value == 'p':
print('PC choose "Paper"')
else:
print('PC choose "Scissors"')
#User and PC choices compare with match() function. It return the winner (user, pc, eq)
winner = match(user_value, pc_value)
#Score board change with return value of match
if winner == "pc":
pc_score += 1
elif winner == "user":
user_score += 1
else:
pc_score += 0
user_score += 0
print("Score, You: "+str(user_score)+" - PC: "+str(pc_score))
| true |
cf9a2f88d03d08b1986f68ed838079f487c2e85f | mparedes003/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,416 | 4.3125 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(i + 1, len(arr)):
if arr[smallest_index] > arr[j]:
smallest_index = j
# TO-DO: swap
# Store the element in a temp variable
temp = arr[i]
# Swap the element found at the current index
# with the next smallest element found
arr[i] = arr[smallest_index]
arr[smallest_index] = temp
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# Length of the array stops at the 2nd to the last element
# because we will be comparing the current value to the next value each time
len_of_arr = len(arr)-1
# Loop through your array
for i in range(len_of_arr):
# Compare each element to its neighbor
# by comparing the current j with the next value
for j in range(len_of_arr - i):
# if left element > right element
if arr[j] > arr[j+1]:
# swap them
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
| true |
750a644102deaf247f6dc8535a6552c20d7efe49 | WinPlay02/Python-Vorkurs | /Tag 1/a1.py | 477 | 4.125 | 4 | x = float(input("X: "))
op = input("Rechenoperation: ")
y = float(input("Y: "))
if op == '+':
print("Ergebnis: " + str(x) + " + " + str(y) + " = ", x + y)
elif op == '-':
print("Ergebnis: " + str(x) + " - " + str(y) + " = ", x - y)
elif op =='*':
print("Ergebnis: " + str(x) + " * " + str(y) + " = ", x * y)
elif op == '/':
print("Ergebnis: " + str(x) + " / " + str(y) + " = ", x / y)
else:
print("Deine Eingabe der Rechenoperation war ungültig.") | false |
8a7e5c3ec07b2e8912906c2cb962a70dd8ce51d5 | marwenbhz/devops-exercises | /coding/reverse_string.py | 540 | 4.71875 | 5 | #!/usr/bin/env python
def reverse_string(string):
"""
A Function that gets a string and reverse it.
"""
index = len(string) # calculate length of string and save in index
reversedString = ""
while index > 0:
reversedString += string[ index - 1 ] # save the value of str[index-1] in reverseString
index = index - 1 # decrement index
return reversedString
if __name__ == '__main__':
string = input("Enter your string: ")
res = reverse_string(string)
print("reversed string: ", res) | true |
d71c583195bf5ce4b78b3c3bf78a2887ea3e09cc | Kazzuki/study_python | /65_errorhandring.py | 1,512 | 4.1875 | 4 | # 例外処理→エラーが発生してもプログラムを停めずに最後まで処理させる
# tyrでIndexErrorをチャッチして次のプログラムにすすめる!
l = [1,2,3]
i = 5
try:
# IndexErrorが発生する
l[i]
except:
print("Don't worry!")
# Pythonのエラー階層参考(https://docs.python.org/3.6/library/exceptions.html#exception-hierarchy)
l = [1,2,3]
i = 5
try:
l[0]
except IndexError as ex:
print("Don't worry!: {}".format(ex))
except NameError as ex:
print(ex)
# ほぼ全てのエラーに該当するExceptionで、エラーをキャッチすることはよくない!
except Exception as ex:
print("other: {}".format(ex))
# エラーにかかることがなく終わるとき
else:
print('Done')
# 必ず最後に実行される
finally:
print('clean up')
print('############################')
# 独自例外の作成→例外は自分で起こすことができる!
# 自分たち独自のエラーに対して処理をかけるので開発の効率が上がる
# raise NameError('kakakkakakka')
#Exceptionを継承したUppercaseErrorクラスを定義している
class UppercaseError(Exception):
pass
#この中に付け加えたい処理を書いていく
def check():
words = ['APPLE', 'orange', 'banana']
for word in words:
if word.isupper():
raise UppercaseError(word)
try:
check()
except UppercaseError as exc:
print('This is my fault. Go next!{}'.format(exc)) | false |
10d018580b0b4e3ce2784cd251f7245ed8e71618 | Kazzuki/study_python | /tutorial/unit4/function1.py | 1,264 | 4.1875 | 4 | """
p69のチャレンジ問題
・数学と同じで数式を書きながら理解する過程がプログラミンで全く身についていない。
・はじめは、コードを書くことになれないかもしれないが、頭の中にある考えを表現していかないといつまで立ってもこのまま。
・文章を書く、考えを書き出す習慣があるんだから、絶対コードを書くこともできる!俺はやれる。
"""
def calcurate():
"""入力した値を二乗して返す
Returns print(a * 2).
"""
a = int(input("1つ目"))
return print(a * 2)
def show_str(str):
return print(str)
def five_params(a, b, c, d="hoge", e="fuga"):
print(a)
print(b)
print(c)
print(d)
print(e)
def fuc1(num):
print(num / 2)
return num / 2
def fuc2(num):
print(num * 4)
return num * 4
def error_float():
str = "hogehoge"
try:
type_conversion = float(str)
except ValueError as ex:
print("文字列をfloatって舐めんなよ!")
print(ex)
else:
return type_conversion
calcurate()
show_str("hoge")
five_params("mama", "papa", "ane", "unnti")
result = fuc1(10)
fuc2(result)
error_float()
print(calcurate.__doc__) | false |
ae33a6814d89e7f0ffff78971bad7a8a1d2e69c8 | Luskinnn28/Sete-Exerc-cios-de-fixa-o | /Exercício 1.py | 553 | 4.25 | 4 | #1) Faça um programa que insira um valor em reais, e faça ele converter o valor para dólar,mostrando quantos
# dólares podem ser comprados com aquela quantia. (Valor para ser usado do dólar no exercício: 5.30)
print('RESOLUÇÃO DA 1')
ValorEscolhido = float(input("Digite o valor que você quer converter para dolar"))
DolarAtual = 5.30
valorConvertido = (ValorEscolhido * DolarAtual)
print("R${} equivale a {} Dolares".format(ValorEscolhido, valorConvertido))
print('----------------------------------------------------------------------')
| false |
bc21452d6fe5e22f5580c172737d2cecea07dee5 | DimaLevchenko/intro_python | /homework_5/task_7.py | 736 | 4.1875 | 4 | # Написать функцию `is_date`, принимающую 3 аргумента — день, месяц и год.
# Вернуть `True`, если дата корректная (надо учитывать число месяца. Например 30.02 - дата не корректная,
# так же 31.06 или 32.07 и т.д.), и `False` иначе.
# (можно использовать модуль calendar или datetime)
from datetime import datetime
d = int(input('Enter day: '))
m = int(input('Enter month: '))
y = int(input('Enter year: '))
def is_date(a, b, c):
try:
datetime(day=a, month=b, year=c)
return True
except ValueError:
return False
print(is_date(d, m, y))
| false |
2281c15d17ca74442e1fb0086ed38b3e4b2f90dd | Ellen172/UFU-Python | /Olá, usuário.py | 314 | 4.125 | 4 | #Segundo programa em Pyhton
#vamos saudar o usuário usando seu nome
nome = input("Insira seu nome: ") #imprimi o argumento dado como entrada e recebe a variavel nome
#a variavel nome também aceita espaços
print("Olá", nome) #colocando dois objetos, o python automaticamente insere um espaço entre eles | false |
6be9a69c88f683f8870578d8329979a79bc3c57f | Ellen172/UFU-Python | /Circulo APD.py | 763 | 4.46875 | 4 | #Terceiro programa em Python
#programa que calcula a area, o perimetro e diametro do circulo
#autora: Ellen Christina
raio = input("Entre com o raio do circulo: ")
#a função input recebe apenas elementos Stings, com os quais não conseguimos fazer contas
raio = float(raio) #define que o elemento raio se torna um float
#tambem pode ser usado: raio = float( input("Entre com o raio do circulo: ") )
pi = 3.1415
diametro = 2 * raio #2 vezes raio
perimetro = 2 * pi * raio #2 vezes pi vezes raio
area = pi * (raio ** 2) #pi * (raio elevado a 2)
texto = "Perimetro: %0.2f" %(perimetro)
print("Diametro:", diametro)
print(texto) #dessa forma a variavel texto contem todos os dados e no final só ela precisa ser chamada
print("Area: %0.2f" %(area))
| false |
9120fc75e9933e3babe883ef386aefef5462c70c | aprilyichenwang/small_projects | /coding_exercise/sum_of_leaves.py | 2,128 | 4.15625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# Note, this questions asks for the leaf only
# always go the left node if possible, if not, go to the right node
# append val into a list, after verifying that it is a leaf
# sum(list)
queue=[root]
val_ls=[]
while queue:
node=queue.pop()
if node.left:
queue.append(node.left)
if not node.left.left and not node.left.right: # verify a leaf
val_ls.append(node.val)
# need to visit right anyway (keep walking)
if node.right:
queue.append(node.right) # next root to go
return sum(val_ls)
x=Solution()
print x.sumOfLeftLeaves([1,2,3,4,5])
##########################
# why this does not work?
##########################
class Solution(object):
def isLeaf(self, node):
return node and not (node.left or node.right)
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# Note, this questions asks for the leaf leaves only
# (need to see whether it is leaf or not)
sum_ls = []
if root: # verify root is not None
queue = [root]
else:
return 0
while queue:
node = queue.pop()
if not self.isLeaf(node):
if self.isLeaf(node.left):
sum_ls.append(node.left.val)
else:
queue.extend([node.left])
if not self.isLeaf(node.right):
queue.extend([node.right])
if node and node.left and node.right:
queue.extend([node.left, node.right])
if node.left.left is None:
sum_ls.append(node.left.val)
return sum(sum_ls)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.