blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c0a863968583042a5256997c5363df0847a24650 | zhengxiaocai/jksj_core | /ch09/py0901_myfunction.py | 750 | 4.21875 | 4 | def my_func(message):
print('Got a message: {}'.format(message))
def my_sum(a, b):
return a + b
def find_largest_element(l):
if not isinstance(l, list):
print('input is not type of list')
return
if len(l) == 0:
print('empty list')
return
largest_element = l[0]
for item in l:
if item > largest_element:
largest_element = item
print('largest element is: {}'.format(largest_element))
if __name__ == '__main__':
my_func('Hello world')
result = my_sum(3, 5)
print(result)
find_largest_element([8, 1, -3, 2, 0])
# >>TODO: Python是动态语言,参数可以接受任意类型
print(my_sum([1, 2], [3, 4]))
print(my_sum('Hello', 'World'))
| true |
4b7c04a7109c76fbe4b4c949675c4ec5db3c853d | mzfr/Project-Euler | /In python/20.py | 398 | 4.125 | 4 | # Find the sum of the digits in the number 100!
import math
factorial = math.factorial(100)
print(factorial)
sumofnum = 0
# finding the sum of all the digits of number 100!
for i in str(factorial):
remain = factorial % 10
sumofnum = sumofnum + remain
factorial = factorial / 10
print ('The sum of the digit in the number 100! is ' , sumofnum)
"""problem in sum """
| true |
3dd5e39ce7ebd049eed0c064fece4462a921ec56 | AP-MI-2021/lab-1-andreigut | /main.py | 1,667 | 4.125 | 4 | '''
Returneaza true daca n este prim si false daca nu.
'''
from math import sqrt
def is_prime(n):
if n == 1 or n ==0:
return False
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
for i in range(3, n // 2, 2):
if n % i == 0:
return False
return True
'''
Returneaza produsul numerelor din lista lst.
'''
def get_product(lst):
prod = 1
for number in lst:
prod*=number
return prod
'''
Returneaza CMMDC a doua numere x si y folosind primul algoritm.
'''
def get_cmmdc_v1(x, y):
if x == 0:
return y
elif y == 0:
return x
while(x != y):
if(x > y):
x-=y
else:
y-=x
return x
'''
Returneaza CMMDC a doua numere x si y folosind al doilea algoritm.
'''
def get_cmmdc_v2(x, y):
while(x != 0):
aux = x
x = y % x
y = aux
return y
def main():
print('''
1.IS prime
2. Product
3. Cmmdc v1
4. Cmmdc v2''')
while(True):
x = int(input("Comanda="))
if(x == 1):
n=int(input("Introduceti n="))
print(is_prime(n))
if (x == 2):
n = int(input("Introduceti n="))
list = []
for i in range(0,n):
element = int(input())
list.append(element)
print(get_product(list))
if (x == 3):
n = int(input("Introduceti n="))
m = int(input("Introduceti m="))
print(get_cmmdc_v1(n, m))
if (x == 4):
n = int(input("Introduceti n="))
m = int(input("Introduceti m="))
print(get_cmmdc_v2(n, m))
if x not in [1,2,3,4]:
print("No identifiable option, bye.")
break
print("Loop is closed")
if __name__ == '__main__':
main()
| false |
da7b51cd730d0721a8d5741f92c3915416ca328c | ShahidAkhtar777/HACKTOBERFEST2020 | /Python/word-of-number.py | 699 | 4.4375 | 4 | #The below program is an optimized method for converting the integers to their English representations.
''' For example:
>>>Enter a number34
thirty four
For this conversion ,a package named n2w is used.If the package is not installed in your local machine,install it using the command :
>>>pip install n2w
'''
def int2word(integer): # A function is defined that will take integer value as an argument and will return the String output
return n2w.convert(num)
if __name__ == "__main__":
import n2w # the package n2w is imported for performing the number to word calculation
num=input("Enter a number:") # A number is taken as input from the user
print(int2word(num))
| true |
4449e49661a93160ebe5eee3a2b91f66910ff3fe | ian-garrett/CIS_122 | /Assignments/Week 7/Lab7-1.py | 1,166 | 4.15625 | 4 | # by Ian Garrett'
# Lab 7-1
print ("Welcome to my turtle program\n")
import turtle
turtle.speed(0)
def get_ok():
ok = input("Do again? Press y or n")
ok = ok.lower() + "x"
ok = ok[0]
return ok
def ask_y_or_n(question):
answer = ' '
while answer != 'y' and answer != 'n':
answer = input (question + "'Press y or n ")
answer = answer .lower() + "x"
answer = answer[0]
return answer
def get_float(prompt):
temp = input(prompt + ' ')
return float(temp)
def get_int(prompt):
temp = input(prompt + ' ')
return int(temp)
def get_str(prompt):
temp = input(prompt + ' ')
return str(temp)
rerun = 'y'
while rerun == 'y':
turtle.reset()
color = get_str("Enter line color ")
bg_color = get_str("Enter background color ")
angle = get_float("Enter angle to turn ")
number_of_lines = get_int("Enter number of lines ")
for i in range (number_of_lines):
turtle.color(color)
turtle.bgcolor(bg_color)
turtle.forward(100)
turtle.right(angle)
rerun = "n"
print ("Exiting program...")
| true |
5d3f575b4076931fea59e224edd2144e208fe0b3 | ian-garrett/CIS_122 | /Assignments/Week 4/Lab4-3.py | 1,292 | 4.125 | 4 | # Ian Garrett
# Lab4-3
def get_float(prompt_message):
"""(str) -> float
displays prompt message,
gets input from user
converts input string to float number,
returns number to caller
"""
prompt = prompt_message + ' '
temp = input(prompt) # get input from user
return float(temp)
limit = 10
do_again = 'y'
while do_again == 'y':
x = get_float("Enter x as a price from $-10.00 to $20.00(no $ sign):")
# is limit <x?
if limit < x:
print("Yes!", limit, "less than", x)
else:
print("No..", limit, "not less than", x)
# is limit <=x?
if limit <= x:
print ("Yes!", limit,"less than or equal to", x)
else: print("No..", limit,"not less than or equal to", x)
# is limit == x?
if limit == x:
print ("Yes!", limit,"equal to", x)
else:
print ("No..", limit,"not equal to", x)
# is is limit != x?
if limit != x:
print ("Yes!", limit,"not equal to", x)
else:
print ("No..", limit,"equal to", x)
# loop will end when you type in an n
do_again = input("try another? (y or n)")
# end while
# Results (4.37):
# No.. 10 not less than 4.37
# No.. 10 not less than or equal to 4.37
# No.. 10 not equal to 4.37
# Yes! 10 not equal to 4.37
| true |
22cfce0963e6a3cc5e9116819905e02e085b556a | moral50/Practicas | /PYHTON/LISTAS/unirse listas py.py | 591 | 4.40625 | 4 | #UNIR DOS LISTAS
#Hay varias formas de unir o concatenar dos o más listas en Python.
#Una de las formas más sencillas es utilizar el + operador.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
#Otra forma de unir dos listas es agregando todos los elementos de list2 a list1, uno por uno:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
#O puede usar el extend() método, cuyo propósito es agregar elementos de una lista a otra lista:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
| false |
ae4dc953095d2626a68ebd680237ad8204468724 | moral50/Practicas | /PYHTON/numeros py.py | 1,467 | 4.59375 | 5 | #Hay tres tipos numéricos en Python:
#int
#float
#complex
x = 1 #int
y = 2.8 #float
z = 1J #complex
print(type(x))
print(type(y))
print(type(z))
#INT
#Int, o entero, es un número entero, positivo o negativo,
#sin decimales, de longitud ilimitada.
x = 1
y = 357645763485766
z = -5151518548
print(type(x))
print(type(y))
print(type(z))
#FLOAT
#Float, o "número de coma flotante" es un número, positivo o negativo,
#que contiene uno o más decimales.
x = 1.10
y = 1.0
z = -35.5987
print(type(x))
print(type(y))
print(type(z))
#Float también pueden ser números científicos con una "e"
#para indicar la potencia de 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
#COMPLEX
#Los números complejos se escriben con una "j" como parte imaginaria:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
#CONVERSION DE UN TIPO A OTRO
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
#NUMERO ALEATORIO
#Importe el módulo aleatorio y muestre un número aleatorio entre 1 y 9:
import random
print(random.randrange(1, 10))
| false |
0c0dc79e6e68d5c7da5f70b2c5c63c2c5b654ba2 | moral50/Practicas | /PYHTON/LISTAS/listas de bucles py.py | 1,334 | 4.34375 | 4 | #RECORRER UNA LISTA
#Puede recorrer los elementos de la lista mediante un for bucle:
#Imprima todos los elementos de la lista, uno por uno:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
#Recorrer los números de índice
#También puede recorrer los elementos de la lista consultando su número de índice.
#Utilice las funciones range()y len()para crear un iterable adecuado.
#Imprima todos los elementos consultando su número de índice:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
#Usar un bucle while
#Puede recorrer los elementos de la lista mediante un whilebucle.
#Utilice la len()función para determinar la longitud de la lista, luego comience en 0 y recorra los elementos de la lista consultando sus índices.
#Recuerde aumentar el índice en 1 después de cada iteración.
#Imprima todos los elementos, usando un whilebucle para revisar todos los números de índice
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
#Bucle con lista completa
#List Comprehensive ofrece la sintaxis más corta para recorrer listas:
#Imprima todos los elementos, usando un whilebucle para revisar todos los números de índice
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
| false |
42911edacc97c1c2686ef73db4c2ff89886f3194 | moral50/Practicas | /PYHTON/python lambada py.py | 1,504 | 4.6875 | 5 | #python lambda
#Una función lambda es una pequeña función anónima.
#Una función lambda puede tomar cualquier número de argumentos, pero solo puede tener una expresión.
#Sintaxis
#lambda arguments : expression
x = lambda a : a + 10
print(x(5))
#Las funciones Lambda pueden tomar cualquier número de argumentos:
x = lambda a, b : a * b
print(x(5, 6))
#Resumir el argumento a, by cy devolver el resultado:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
#¿Por qué utilizar las funciones Lambda?
#El poder de lambda se muestra mejor cuando los usa como una función anónima dentro de otra función.
#Supongamos que tiene una definición de función que toma un argumento, y ese argumento se multiplicará por un número desconocido:
def myfunc(n):
return lambda a : a * n
#Usa esa definición de función para hacer una función que siempre duplique el número que envías:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
#O use la misma definición de función para hacer una función que siempre triplique el número que envía:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
#O use la misma definición de función para hacer ambas funciones, en el mismo programa:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
#Utilice funciones lambda cuando se requiera una función anónima durante un período corto de tiempo.
| false |
b7507ee33cc3d49f32314aede78a8d98d345d8a7 | ipero/python_learning_curve | /python_the_hard_way/ex42.py | 1,389 | 4.15625 | 4 | ## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Dog is-a Animal
class Dog(Animal):
def __init__(self, name):
## Dog has-a name
self.name = name
## Cat is-a Animal
class Cat(Animal):
def __init__(self, name):
## Cat has-a name
self.name = name
## Person is-a object
class Person(object):
def __init__(self, name):
## Person has-a name
self.name = name
## Person has-a pet of some kind
self.pet = None
## Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
## Employee can be someone else, maybe Robot or inharite methods from other classes
super(Employee, self).__init__(name)
## Employee has salary
self.salary = salary
## Fish is-a object
class Fish(object):
pass
## Salmon is-a Fish
class Salmon(Fish):
pass
## Halibut is-a Fish
class Halibut(Fish):
pass
## rover is-a Dog
rover = Dog("Rover")
## kat is-a Cat
kat = Cat("Kat")
## mary is-a Person
mary = Person("Mary")
## mary has pet kat
mary.pet = kat
## frank is-a Employee
frank = Employee("Frank", 120000)
## frank has pet rover
frank.pet = rover
## flipper is-a instance of Fish
flipper = Fish()
## crouse is-a instance of Salmon
crouse = Salmon()
## harry is-a instance of Halibut
harry = Halibut()
| true |
736cbd9d68cc70e933e97ff865caf28e84bcb561 | GiovanniBrunoS/intro-python | /lista-102.py | 1,875 | 4.625 | 5 | #!/usr/bin/python3
# LISTS
# https://docs.python.org/3/tutorial/introduction.html#lists
# list slicing [inicio:fim:passo]
weekdays = ['mon','tues','wed','thurs','fri']
# print(weekdays)
# print(type(weekdays))
days = weekdays[0] # elemento 0
days = weekdays[0:3] # elementos 0, 1, 2
days = weekdays[:3] # elementos 0, 1, 2
days = weekdays[-1] # ultimo elemento
test = weekdays[3:] # elementos 3, 4
weekdays
days = weekdays[-2] # ultimo elemento (elemento 4
days = weekdays[::] # all elementos
days = weekdays[::2] # cada segundo elemento (0, 2, 4)
days = weekdays[::-1] # reverso (4, 3, 2, 1, 0)
all_days = weekdays + ['sat','sun'] # concatenar
# print(all_days)
# Usando append
days_list = ['mon','tues','wed','thurs','fri']
days_list.append('sat')
days_list.append('sun')
# print(days_list)
# print(days_list == all_days)
list = ['a', 1, 3.14159265359]
# print(list)
# print(type(list))
# list.reverse()
# print(list)
#########
# Exercicios - Listas
# Faca sem usar loops
#########
# Como selecionar 'wed' pelo indice?
print(all_days[2])
# Como verificar o tipo de 'mon'?
print(type(all_days[0]))
# Como separar 'wed' até 'fri'?
print(all_days[2:5])
# Quais as maneiras de selecionar 'fri' por indice?
print(all_days[4])
# Qual eh o tamanho dos dias e days_list?
print(len(days))
print(len(days_list))
# Como inverter a ordem dos dias?
print(all_days[::-1])
# Como inserir a palavra 'zero' entre 'a' e 1 de list?
list.insert(1,"zero")
print(list)
# Como atribuir o ultimo elemento de list na variavel ultimo_elemento e remove-lo de list?
ultimo_elemento = list.pop(-1)
print(ultimo_elemento)
# Como limpar list?
list.clear()
print(list)
# Como deletar list?
del list
print(list)
| false |
8a0386a444c7621997f9347f374fa121ee7d880b | SoccerAL29/Frog1 | /review/elif.py | 209 | 4.1875 | 4 | num=120
if num<=30:
print("no num is not less than 30")
elif num>=31 and num<=75:
print("yesnum is greater than 31 and no num is not less than 75")
elif num>=76:
print("yes num is greater than 76") | true |
dea5260c38e4acbab6ea6c512eefc82521a86081 | ravi4all/PythonFebOnline_21 | /if_else_expression.py | 230 | 4.21875 | 4 | x = 6
y = 8
z = 10
'''
if x % 2 == 0:print("Even")
else:print("Odd")
'''
ans = "Even" if x % 2 == 0 else "Odd"
print(ans)
ans = "X" if x > y and x > z else "Y" if y > x and y > z else "Z"
print(ans,"is greatest")
| false |
3daf6f150be248a66ce2cdbffb16a0f217d892b4 | pang007/Python_Cookbook_Practice | /iterable_flattened.py | 656 | 4.125 | 4 | """
Input: a nested list consisting of integers -> list
Output: a flattened list consisting the element inside
"""
from collections import Iterable
nested_list = [1,[2,3,4],[5,6,7],[8,9]]
def flatten(nested_list, ignore_type = (str)):
for item in nested_list:
# str is an iterable so we have to check the item is not a str
if isinstance(item, Iterable) and not isinstance(item, ignore_type):
# as flatten is another iterable, hence we have to use yield from
yield from flatten(item)
else:
yield item
for x in flatten(nested_list):
print(x)
# yield from (a) where a is a iterable/ generator is equivalent to
# for i in a:
# yield i
| true |
ed9d77a1cc7380eb98026afc488337e21c8f1ee2 | nithyagundamaraju1/the_python_workbook | /ex_91.py | 688 | 4.15625 | 4 | def precedence(str):
ch=[]
oper=[]
pre=[]
for i in str:
oper.append(i) if i in op else ch.append(i)
print("Characters:",end=" ")
print(ch,end=",")
print("Operators:",end=" ")
print(oper,end=",")
for i in oper:
if i=='+' or i == '-':
pre.append(1)
elif i=='*' or i == '/':
pre.append(2)
elif i=='^':
pre.append(3)
else:
pre.append(0)
return pre
p=[]
op=['+','-','*','/','//','%','**','==','!=','<',' >','<=','>=','is','in','and','not','or','(','&','|','~','^','<<','>>',')','^']
str=input("Enter the expression: ")
p=precedence(str)
print(f"Precedence of operators is :",end=" ")
print(p) | false |
31c91dd9756f05f43e50af6fc967b39e84dcd417 | nithyagundamaraju1/the_python_workbook | /ex_52.py | 621 | 4.1875 | 4 | g=float(input("Enter your grade points:"))
if g>4.0:
print("Grade:A+ ")
elif g==4.0:
print("Grade:A")
elif g < 4.0 and g >= 3.7:
print("Grade:A-")
elif g>=3.3 and g <3.7:
print("Grade:B+")
elif g<3.3 and g>=3.0:
print("Grade: B")
elif g<3.0 and g >=2.7:
print("Grade:B-")
elif g >= 2.3 and g<2.7:
print("Grade:C+")
elif g >= 2.0 and g<2.3:
print("Grade:C")
elif g >= 1.7 and g<2.0:
print("Grade:C-")
elif g >= 1.3 and g<1.7:
print("Grade:D+")
elif g >= 1.0 and g<1.3:
print("Grade:D")
elif g < 1.0 and g>=0:
print("Grade: F")
else:
print("Invalid!!")
| false |
3255f8b741fe71617bdc228a4d87429998527021 | chaitumuppala/audio-sentiment-analysis-pipeline | /audio_sentiment_analysis/mp3_to_wav.py | 1,726 | 4.1875 | 4 | '''
Script to convert a directory of mp3s to WAVs. Utilizes pydub and FFMPEG library.
Usage: python mp3_to_wav.py INPUT_DIR OUT_DIR
If converting everything in a DIR, the files will retain their original names
and be placed in the OUT DIR if supplied. Otherwise in the INPUT DIR.
'''
import sys
import os
from pydub import AudioSegment
def convert_to_wav(inpath, inname, outdir):
'''
Converts the given mp3 file to wav.
'''
mp3 = AudioSegment.from_mp3(inpath)
if outdir is None:
# put in input dir
basename = os.path.splitext(inpath)[0]
mp3.export(basename + '.wav', format='wav')
else:
# put in output dir
if os.path.isdir(outdir):
basename = os.path.splitext(inname)[0]
mp3.export(os.path.join(outdir, basename) + '.wav', format='wav')
else:
sys.exit('Make sure the output dirctory exists.')
def main():
'''
Checks that proper arguments were given and runs conversion
'''
# check inputs
if len(sys.argv) < 2:
sys.exit('Must at least supply the input directory.\nUsage: python mp3_to_wav.py INPUT_DIR OUT_DIR')
elif len(sys.argv) < 3:
INPUT_DIR = sys.argv[1]
OUT_DIR = None
else:
INPUT_DIR = sys.argv[1]
OUT_DIR = sys.argv[2]
# check if it's a file or a directory to convert
if os.path.isdir(INPUT_DIR):
print('Working...')
for filename in os.listdir(INPUT_DIR):
if filename.endswith('.mp3'):
convert_to_wav(os.path.join(INPUT_DIR, filename), filename, OUT_DIR)
print('Done.')
else:
sys.exit('Make sure input directory exists.')
if __name__ == '__main__':
main()
| true |
9790292f29977c147a01da908c0890fac1fedc9f | Shanukusai/python_basics | /lesson03/task0301.py | 817 | 4.3125 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def division_f(my_numerator, my_denominator):
try:
division_result = round(my_numerator / my_denominator, 3)
except ZeroDivisionError:
return print('На ноль делить нельзя.')
return division_result
try:
a = float(input("Укажите числитель: "))
b = float(input("Укажите знаменатель: "))
print(division_f(a, b))
except ValueError:
print('Введите корректные данные.')
| false |
069303ab2522ea7bc4567fbda57e61038abb3227 | Borys-S/Python | /BT_homework/homework13.py | 563 | 4.125 | 4 | # Task 1
# Write a Python program to detect the number of local variables declared in a function.
# def inside_func():
# a = [54, 65, 'jhgk']
# b = 656462
# c = 'string'
#
#
# print(f'Function "{inside_func.__name__}" has {inside_func.__code__.co_nlocals} variables inside.')
# Task 2
# Write a Python program to access a function inside a function
# (Tips: use function, which returns another function)
def tax(x):
def percent(y):
return (y / 100 * x)
return percent
duty = tax(18.5)
print(duty(int(input('Enter your salary: '))))
| true |
5e5f8bba2d3970f3c9198111bf0ec501b57389a9 | everydaytimmy/seattle-python-401d16 | /class-35/demos/graph/test_graph.py | 2,714 | 4.25 | 4 | """
Implement your own Graph. The graph should be represented as an adjacency list, and should include the following methods:
add node
Arguments: value
Returns: The added node
Add a node to the graph
add edge
Arguments: 2 nodes to be connected by the edge, weight (optional)
Returns: nothing
Adds a new edge between two nodes in the graph
If specified, assign a weight to the edge
Both nodes should already be in the Graph
get nodes
Arguments: none
Returns all of the nodes in the graph as a collection (set, list, or similar)
get neighbors
Arguments: node
Returns a collection of edges connected to the given node
Include the weight of the connection in the returned collection
size
Arguments: none
Returns the total number of nodes in the graph
TESTS
An empty graph properly returns null
"""
from graph import Graph, Vertex
def test_add_node():
graph = Graph()
expected_value = "spam"
actual = graph.add_node("spam")
assert actual.value == expected_value
def test_get_nodes_one():
graph = Graph()
graph.add_node("spam")
actual = graph.get_nodes()
expected = 1
assert len(actual) == expected
assert isinstance(actual[0], Vertex)
assert actual[0].value == "spam"
# REFACTOR to not do so much
def test_get_nodes_two():
graph = Graph()
graph.add_node("spam")
graph.add_node("eggs")
actual = graph.get_nodes()
expected = 2
assert len(actual) == expected
assert isinstance(actual[0], Vertex)
assert isinstance(actual[1], Vertex)
assert actual[0].value == "spam"
assert actual[1].value == "eggs"
def test_size_two():
graph = Graph()
graph.add_node("spam")
graph.add_node("eggs")
actual = graph.size()
expected = 2
assert actual == expected
def test_add_edge_no_weight():
graph = Graph()
spam_vertex = graph.add_node("spam")
eggs_vertex = graph.add_node("eggs")
return_val = graph.add_edge(spam_vertex, eggs_vertex)
assert return_val is None
def test_get_neighbors():
graph = Graph()
spam_vertex = graph.add_node("spam")
eggs_vertex = graph.add_node("eggs")
graph.add_edge(spam_vertex, eggs_vertex, 5)
neighbors = graph.get_neighbors(spam_vertex)
assert len(neighbors) == 1
single_edge = neighbors[0]
assert single_edge.vertex.value == "eggs"
assert single_edge.weight == 5
def test_get_neighbors_solo():
graph = Graph()
spam_vertex = graph.add_node("spam")
graph.add_edge(spam_vertex, spam_vertex)
neighbors = graph.get_neighbors(spam_vertex)
assert len(neighbors) == 1
single_edge = neighbors[0]
assert single_edge.vertex.value == "spam"
assert single_edge.weight == 0
| true |
1bcc6cae2c7de8ad794c335c986aeab474a977a0 | jaeheeLee17/DS_and_Algorithms_summary | /Searching_and_Sorting/searching_method/Linearsearch.py | 1,644 | 4.40625 | 4 | # Implementation of the linear search on an unsorted sequence.
def linearSearch(theValues, target):
n = len(theValues)
for i in range(n):
# If the target is in the ith element, return True
if theValues[i] == target:
return True
return False # If not found, return False.
# Implementation of the linear search on an sorted sequence.
def sortedLinearSearch(theValues, item):
n = len(theValues)
for i in range(n):
# If the target is found in the ith element, return True
if theValues[i] == item:
return True
# If the target is larger than the ith element, it's not in the sequence.
elif theValues[i] > item:
return False
return False # The item is not in the sequence.
# Searching for the smallest value in an unsorted sequence.
def findSmallest(theValues):
n = len(theValues)
# Assume the first item is the smallest value.
smallest = theValues[0]
# Determine if any other item in the sequence is smaller.
for i in range(n):
if theValues[i] < smallest:
smallest = theValues[i]
return smallest # Return the smallest found.
# Testing the Linearsearch methods.
def main():
import random
num_counts = random.randint(1, 10)
num_list = []
for _ in range(num_counts):
num_list.append(random.randint(1, 50))
print("Num list: ", num_list)
print("First search")
print(linearSearch(num_list, 26))
print("Second search")
print(sortedLinearSearch(sorted(num_list), 18))
print("Smallest values:", end=' ')
print(findSmallest(num_list))
main()
| true |
bb12ea423e12192ea23631ac39053bbf8a842cf1 | jaeheeLee17/DS_and_Algorithms_summary | /Searching_and_Sorting/searching_method/Binarysearch.py | 1,665 | 4.40625 | 4 | # Implementation of the binary search algorithm.
def binarySearch(theValues, target):
# Start with the entire sequence of elements.
start = 0
end = len(theValues) - 1
# Repeatedly subdivide the sequence in half until the target is found.
while start <= end:
# Find the midpoint of the sequence.
mid = (start + end) // 2
# Does the midpoint contain the target?
if theValues[mid] == target:
return True
# Or does the target precede the midpoint?
elif target < theValues[mid]:
end = mid - 1
# Or does the target follow the midpoint?
else:
start = mid + 1
# If the sequence cannot be subdivided further, we're done.
return False
# Modified version of the binary search that returns the index within
# a sorted sequence indicating where the target should be located.
def findSortedPosition(theList, target):
start = 0
end = len(theList) - 1
while start <= end:
mid = (start + end) // 2
if theList[mid] == target:
return mid # Index of the target
elif target < theList[mid]:
end = mid - 1
else:
start = mid + 1
return low # Index where the target value should be.
# Testing the Binarysearch methods.
def main():
import random
num_counts = random.randint(1, 10)
num_list = []
for _ in range(num_counts):
num_list.append(random.randint(1, 50))
print("Num list: ", num_list)
print("Binary search")
print(binarySearch(num_list, 26))
print("Target Location")
print(findSortedPosition(sorted(num_list), 11))
main()
| true |
b00905c8ac473d23b68098063a43176f2f051a9e | arthursarah/mummy | /sign 3.py | 233 | 4.125 | 4 | def calculate():
a=int(input("enter a number"))
b=int(input("enter a number"))
add=a+b
multiply=a*b
divide=a/b
subtract=a-b
print(add)
print(multiply)
print(divide)
print(subtract)
calculate() | false |
f62c48b2581682f48197b5a7bf577130bcbee028 | rituc/Programming | /geesks4geeks/bit_algorithms/detect_sign.py | 263 | 4.28125 | 4 | # http://www.geeksforgeeks.org/detect-if-two-integers-have-opposite-signs/
def main():
num1 = int(raw_input("Enter First Number"))
num2 = int(raw_input("Enter second Number"))
print detect_sign(num1, num2)
def detect_sign(num1, num2):
return (num1^num2 < 0)
| false |
62a5e5c2abbfb3f442e7e4b142780672643c97a5 | dj-on-github/RNGBook_Code | /primedist.py | 365 | 4.15625 | 4 | #!/usr/bin/python
import math
def is_prime(n):
if n==2 or n==3: return True
if (n % 2 == 0) or (n < 2): return False # Reject even or negative
limit = int(n**0.5)+1
for i in xrange(3,limit,2): # list of odd numbers
if (n % i == 0):
return False
return True
for n in xrange(2**17):
if is_prime(n):
print n
| true |
cbaef2c52801070fbf0034f98cab33b511912856 | igoroya/pycodingkatas | /katas/may2018/primefactors.py | 658 | 4.28125 | 4 | '''
Created on 10 May 2018
@author: igoroya
'''
def get_prime_factors(number):
if number < 2:
return None
factors = []
remainder = number
while (remainder >= 2):
for possible_divisor in range(2, remainder + 1):
if remainder % possible_divisor == 0:
factors.append(possible_divisor)
remainder = remainder // possible_divisor
break
return factors
if __name__ == '__main__':
input_number = int(input('Insert a possitive integer\n'))
factors = get_prime_factors(input_number)
print('The prime factors of {} are {}'.format(input_number, factors))
| true |
c02255cc176b898f384d645f902ea6c285eb6ca7 | igoroya/pycodingkatas | /katas/august2018/getprimes.py | 744 | 4.25 | 4 | '''
Created on 27 Aug 2018
Finds the first N primes
@author: igoroya
'''
from math import sqrt
def is_prime(candidate):
if candidate < 2:
return False
if candidate == 2:
return True
if candidate % 2 == 0:
return False
i = 3
while i < sqrt(candidate):
if candidate % i == 0:
return False
i += 1
return True
def explore_and_check_if_primes(first, n):
primes = []
k = 0
i = first
while k < n:
if is_prime(i):
primes.append(i)
k += 1
i += 1
return primes
def print_first_primes(n):
primes = explore_and_check_if_primes(2, n)
print(primes)
if __name__ == '__main__':
print_first_primes(10)
| false |
2741bbc64eac45c9a3d3d3146c0079fd7b9cc692 | PavitraV/Python_Application | /app7.py | 2,599 | 4.125 | 4 | # Defines two classes, Point() and Disk().
# The latter has an "area" attribute and three methods:
# - change_radius(r)
# - intersects(disk), that returns True or False depending on whether
# the disk provided as argument intersects the disk object.
# - absorb(disk), that returns a new disk object that represents the smallest
# disk that contains both the disk provided as argument and the disk object.
from math import pi, hypot, sqrt
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return f'Point({self.x:.2f}, {self.y:.2f})'
class Disk:
area = 0
def __init__(self, *, centre=Point(0,0), radius=0):
self.radius = radius
self.centre = centre
self.area = pi * radius * radius
def __repr__(self):
return f'Disk({Point(self.centre.x,self.centre.y)}, {self.radius:.2f})'
def change_radius(self, r):
self.radius = r
self.area = pi * r * r
def intersects(self, disk):
flag = False
if (disk.centre.x == self.centre.x or disk.centre.y == self.centre.y):
if(self.centre.x>disk.centre.x):
x1 = self.centre.x
x2 = disk.centre.x
else:
x2 = self.centre.x
x1 = disk.centre.x
if (abs(disk.radius - self.radius) > 0 or x2+disk.radius == x1-self.radius ):
flag = True
return flag
def absorb(self, disk):
dist = sqrt((self.centre.x - disk.centre.x) ** 2 + (self.centre.y - disk.centre.y) ** 2)
maxrad = max(self.radius,disk.radius)
minrad = min(self.radius, disk.radius)
if(maxrad == self.radius):
newx = self.centre.x
newy = self.centre.y
else:
newx = disk.centre.x
newy = disk.centre.y
if(dist+minrad<=maxrad):
return Disk(centre = Point(newx,newy), radius = maxrad)
newrad = (self.radius + disk.radius + dist) / 2
d = dist + disk.radius - newrad
newx = self.centre.x + (d * (disk.centre.x - self.centre.x) / sqrt(
(disk.centre.x - self.centre.x) ** 2 + (disk.centre.y - self.centre.y) ** 2))
newy = self.centre.y + (d * (disk.centre.y - self.centre.y) / sqrt(
(disk.centre.x - self.centre.x) ** 2 + (disk.centre.y - self.centre.y) ** 2))
d = Disk(centre = Point(newx, newy), radius = newrad)
return d
disk_1 = Disk(centre = Point(7, -2), radius = 8)
disk_2 = Disk(centre = Point(4.5, 1), radius = 4)
print(disk_1.intersects(disk_2))
| true |
50b1f5606bf812f99ad4dc1052608d2f7cc546a2 | lamwilton/MATH-501-Numerical-Analysis | /PA2/PA2.py | 1,801 | 4.15625 | 4 | import math
def function1(x: float):
"""
Question 19
:param x:
:return:
"""
return x - math.tan(x)
def function2(x: float):
"""
Question 20
:param x:
:return:
"""
return x ** 8 - 36 * x ** 7 + 546 * x ** 6 - 4536 * x ** 5 + 22449 * x ** 4 - 67284 * x ** 3 + \
118124 * x ** 2 - 109584 * x + 40320
def function2a(x: float):
"""
Question 20 repeating with 36.001
:param x:
:return:
"""
return x ** 8 - 36.001 * x ** 7 + 546 * x ** 6 - 4536 * x ** 5 + 22449 * x ** 4 - 67284 * x ** 3 + \
118124 * x ** 2 - 109584 * x + 40320
def sign(x: float):
"""
Returns sign of a number
:param x: The number
:return: 1 if positive, -1 if negative
"""
return (x > 0) - (x < 0)
def bisection(func):
"""
The bisection algorithm
:param func: The math function
:return:
"""
a = float(input("Input a"))
b = float(input("Input b"))
M = int(input("Input M"))
delta = float(input("Input delta"))
epsilon = float(input("Input epsilon"))
u = func(a)
v = func(b)
e = b - a
print("a = " + str(a))
print("b = " + str(b))
print("u = " + str(u))
print("v = " + str(v))
print()
if sign(u) == sign(v):
return
for k in range(1, M - 1):
e = e / 2
c = a + e
w = func(c)
print("k = " + str(k))
print("c = " + str(c))
print("w = " + str(w))
print("e = " + str(e))
print()
if abs(e) < delta or abs(w) < epsilon:
return
if sign(w) != sign(u):
b = c
v = w
else:
a = c
u = w
if __name__ == '__main__':
bisection(function1)
bisection(function2)
bisection(function2a)
| false |
55696c81d4eb37bfeff8f66679a1f1d7a617d887 | augustomy/Curso-PYTHON-02-03---Curso-em-Video | /aula12.py | 355 | 4.15625 | 4 | nome = input('Qual é o seu nome? ')
if nome == 'Augusto':
print('Que nome bonito! {}!'.format(nome))
elif nome == 'Maria':
print('Que nome lindo! {}!'.format(nome))
elif nome == 'Jorge':
print('Que nome maravilhoso! {}!'.format(nome))
else:
print('Que nome comum! {}!'.format(nome))
print('Tenha um bom dia! {}!'.format(nome)) | false |
8a43f026583d7d9cb146a9a94af46dad0dd60290 | eastsidepyladies/learnpython3thehardway | /Jami/ex11.py | 624 | 4.125 | 4 | print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ')
weight = input()
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
print("What is your name?", end=' ')
name = input()
print("What is your favorite number?", end=' ')
number = input()
print("Where would you like to take a dream vacation?", end=' ')
vacation = input()
print(f"Hello, {name}. Your lucky number, {number}, was selected to win a dream vacation to {vacation}. All you need to do is master python and you can be on your way next week. Any questions?") | true |
a08d362711302da0135d9500bf444329812654d2 | eastsidepyladies/learnpython3thehardway | /kellyc/ex39.py | 2,607 | 4.3125 | 4 | # Dictionaries, Oh Lovely Dictionaries
# Create a mapping of state to abbreviation
states = {
'Oregon' : 'OR',
'Florida' : 'FL',
'California' : 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA' : 'San Francisco',
'MI' : 'Detroit',
'FL' : 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print mo citiies
print('-' * 10)
print("NY State has : ", cities['NY'])
print("OR State has : ", cities['OR'])
# print some states
print('-' * 10)
print("Michigan's abbeviation is ", states['Michigan'])
print("Florida's abbreviation is ", states['Florida'])
# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()) :
print(f"{state} is abbreviated {abbrev}.")
# print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()) :
print(f"{abbrev} has the city {city}.")
# do both - at the same time!
print('-' * 10)
for state, abbrev in list(states.items()) :
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('-' * 10)
# here's a safe way to try and retrieve an abbreviation that may not exist
state = states.get('Texas')
if not state :
print("Sorry, no Texas.")
# now have it deliver a default value when city doesn't exist
city = cities.get('TX', 'Does not Exist')
print(f"The city for the state 'TX' is : {city}.")
# Drills
items1 = {
'lemon' : 'produce',
'cod' : 'fresh meat and fish',
'laundry detergent' : 'cleaning supplies',
'aspirin' : 'health',
'yogurt' : 'dairy',
'green apple' : 'produce'
}
quantities = {
'lemon' : 3,
'cod' : 2,
'laundry detergent' : 1,
'aspirin' : 1,
'yogurt' : 5,
'green apple' : 8
}
items1['lemonade concentrate'] = 'freezer'
items1['red pepper flakes'] = 'spice'
items1['capers'] = 'canned goods'
print('~*~' * 10)
print("You can find lemons in the", items1['lemon'], "department.")
print("You can find cod in the", items1['cod'], "department.")
print('~*~' * 10)
print("I need to buy", quantities['green apple'], "green apples.")
print("I need to buy", quantities['cod'], "pieces of cod.")
print('~*~' * 10)
# assigns item to key and dept to value
for item, dept in list(items1.items()):
print(f"You can find {item} from the {dept} department.")
print('~*~' * 10)
for item, quant in list(quantities.items()):
print(f"I need to buy {quant} unit(s) of {item}.")
| false |
864d877d9e3e9bf5158bd1c5baadc8ba63e9ee9e | eastsidepyladies/learnpython3thehardway | /kellyc/ex21.py | 1,407 | 4.25 | 4 | def add(a, b):
# this just prints
print(f"ADDING {a} + {b}")
# this is where the math happens (note the value "returned" is calculated but not printed)
return a + b
def subtract(a,b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a,b):
print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a,b):
print(f"DIVIDING {a} / {b}")
return a / b
age = add(30,5)
height = subtract(78, 4)
weight = multiply(90,2)
iq = divide(100, 2)
print("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")
# what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
# what = add(age, subtract(height, multiply(weight, divide(50, 2))))
# what = add(age, subtract(height, multiply(weight, 25)))
# what = add(age, subtract(height, multiply(180, 25)))
# what = add(age, subtract(height, 4500))
# what = add(age, subtract(74, 4500))
# what = add(age, −4426)
# what = add(35, −4426)
# what = add(35, −4426)
# what = −4391
# Drill: 24 + 34 / 100 - 1023
first_part = add (24,43)
second_part = subtract(100,1023)
combined = divide(first_part,second_part)
print(combined)
# the below returns 'TypeError: must be str, not set'
# print(f"Tada ---->" + {combined})
# the below returns 'TypeError: must be str, not float'
# print(f"Tada ---->" + combined)
| true |
be5c6b1b55d12fd0b4722b7e9a5a5f5bb462ccac | kit-ai-club/ReiLa_intro | /python_intro_HW/list_intro.py | 2,420 | 4.34375 | 4 | # 参考:https://spjai.com/python-tutorial/
"""
4. 配列
4-1. 他のプログラム言語でいう配列(list)
"""
list = [1, 2, 3, 4] # 配列の宣言と初期化
print(list)
list1 = [1, 2, 3, 4, 5]
list1 = list1 + [6, 7, 8] # 要素の追加
print(list1)
list2 = [1, 2, 3, 4, 5]
print(len(list2)) # 要素数の取得
# in演算子を用いた要素の検索
# 出力結果を比較してみましょう!
list3 = [1, 2, 3, 4, 5]
print(3 in list3)
list4 = [1, 2, 3, 4, 5]
print(500 in list4)
# for文との組み合わせ
my_list5 = [1, 2, 3, 4]
for value in my_list5:
print(value)
# 【演習】
# 1〜10までをリストに格納し、それぞれの値を2乗した値を出力してみましょう!
"""
4-2. 辞書構造(dictionary)
"""
# 辞書型は { から } までの間に複数の要素をカンマ(,)で区切って定義します。
# 要素はキーと対応する値の組み合わせを キー:値 の形式で記述します。
# {キー1:値1, キー2:値2, ...}のようになります。
mydict = {"apple": 1, "orange": 2, "banana": 3}
# 辞書型オブジェクトには順序がないので、要素を取り出すためにはkeyを使うことになります。
val = mydict["apple"]
print(val)
# 【演習】
# 下記のdictionaryオブジェクトを使用してそれぞれのkeyとvalueを取得し
# valueが20以上の場合{keyの中身}:hotと出力し
# 超えていない場合は{keyの中身}:coldと出力してみましょう!
temperatures = {'x': 24, 'y': 18, 'x': 30}
"""
4-3. 変更を許可しない変数等に使う配列(tuple)
"""
# リストは要素を消したり追加したり編集したりできるのに対し、タプルはできない。
# タプルはリストとよく似ているがリストは[]でタプルは()で作成する。
tuple_1 = (1, 2, 3)
tuple_2 = tuple_1 + (4, 5) # 要素の追加
print(tuple_2)
"""
4-6. リストの内包表記
"""
# 内包表記とはリストのようなシーケンスオブジェクトの各要素に対して処理を行いたい時に便利
# 例として1~5のうち、4と5に2をかけたリストを生成してみる
list1 = [1, 2, 3, 4, 5]
list1 = [x * 2 for x in list1 if x > 3]
print(list1) # [8, 10]が出力される
# 【演習】
# for文を用いた内包表記で、1~10の数字の内2の倍数のものだけを含むリストを作成してみましょう!
| false |
5e64168605af055402d828c39be4b9bde8b3d943 | prerakpanwar/Training-With-Acadview | /assignment19.py | 1,086 | 4.3125 | 4 | import pandas as pd
#Q1-Create a dataframe with your name, age, mail-id and phone number and add your friendss information to the same.
data = {'Name':['Prerak'],'Age':[21],'mail id':['panwarprerak98@gmail.com'],'phone no':['8126xxxxxx']}
df = pd.DataFrame(data)
df.loc[1]=['Shitiz',21,'shitiz11@gmail.com','8129xxxxxx'] #Add detail of friend 1
df.loc[2]=['Ramu',21,'ramu456788@gmail.com','7033xxxxxx'] #Add detail of friend 2
print(df)
print("\n")
#Q2-Import the data from "https://raw.githubusercontent.com/Shreyas3108/Weather/master/weather.csv" and print:
df=pd.read_csv('weather.csv')
#print(df)
#a.) First 5 rows of Dataframe
print(df.head(5))
#b.) First 10 rows of the Dataframe
print(df.head(10))
#c.) Find basic statistics on the particular dataset.
print(df['MinTemp'].describe())
print(df['MaxTemp'].describe())
#d.) Find the last 5 rows of the dataframe
print(df.tail(5))
#e.) Extract the 2nd column and find basic statistics on it.
finaldata=[df.iloc[:,2].sum(),
df.iloc[:,2].mean(),
df.iloc[:,2].median(),
df.iloc[:,2].nunique(),
df.iloc[:,2].max(),
df.iloc[:,2].min()]
print(finaldata) | true |
327902e21541b44947e3491c9af7c586996d6c67 | bsavio/ProjectEuler | /Problem4.py | 674 | 4.125 | 4 | """
Largest palindrome product
Problem 4
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
pals = []
for x in reversed(range(100, 999)):
for y in reversed(range(100, x)):
xy = str(x * y)
if xy == xy[::-1]:
pals.append(x * y)
print(max(pals))
def is_palindrome(number):
"""
Tests if a number is a palindrome
:type number: int
:param number:
:return:
"""
str_input = str(number)
return str_input == reversed(str_input) | true |
4a96888286d4fc4cfffb6955688eba10bc62e358 | GopalMule/python_basics | /string_assignments/verbing.py | 561 | 4.4375 | 4 | #!/usr/bin/python
# D. verbing
# Given a string, if its length is at least 3,
# add 'ing' to its end.
# Unless it already ends in 'ing', in which case
# add 'ly' instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.
def verbing(s):
if (len(s)<=2):
print s
elif s[-3:]=='ing':
print s + 'ly'
else:
print s + 'ing'
def main():
verbing('swiming')
verbing('hail')
verbing('do')
if __name__=='__main__':
main()
#output:
#python verbing.py
'''
swimingly
hailing
do
'''
| true |
75af324ce562f85c792e29ccb0e4760dc5dc01dc | GopalMule/python_basics | /string_assignments/donut.py | 801 | 4.1875 | 4 | #!/usr/bin/python
import sys
import test
# A. donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'
def donuts(count):
if count >=10:
print 'Donuts count: many'
else:
print 'Number of donuts',count
def main():
donuts(11)
donuts(5)
donuts(0)
donuts(9)
donuts(10)
donuts(100)
if __name__=='__main__':
main()
#Output:
#python donut.py
'''
Donuts count: many
Number of donuts 5
Number of donuts 0
Number of donuts 9
Donuts count: many
Donuts count: many
'''
| true |
169dfdd24be42b8dc7f5fca0fb9acf42265afb81 | GopalMule/python_basics | /string_assignments/both_ends.py | 616 | 4.4375 | 4 | #!/usr/bin/python
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
if len(s) <=2:
print s
else:
newstring=s[:2] + s[-2:]
print newstring
def main():
both_ends('Gopal')
both_ends('aa')
both_ends('hello')
both_ends('spring')
both_ends('xyz')
both_ends('a')
if __name__=='__main__':
main()
#Output:
#python both_ends.py
'''
Goal
aa
helo
spng
xyyz
a
'''
| true |
29b00465df991eede20d470dc61facff62fe3d21 | xerocrypt/Python | /Python-SQLite/AddHash.py | 629 | 4.34375 | 4 | #This program reads passwords and adds their hash values to
#an SQLite application database.
#Michael, January 2014
#michael@ipv6secure.co.uk
import sqlite3
import hashlib
#Connect to database
conn = sqlite3.connect('hashBase.db')
c = conn.cursor()
#Get username and password
currentUser = raw_input("User name: ")
txtPassword = raw_input("Password: ")
#Hash the user's password
currentPassword = hashlib.sha256(txtPassword).hexdigest()
#Write entry to database table and commit
c.execute("insert into Hashes values (?, ?)", (currentUser, currentPassword))
conn.commit()
print "Password added."
#Close connection to database
conn.close()
| true |
25c0d0f9f4dd792135cd32327c5ba5b3ed3ad2cf | talm8994/Python-Challenges | /MathFunc1.py | 840 | 4.15625 | 4 | def subtract (num1, num2):
return num1 - num2
def multiply (num1, num2):
return num1 * num2
def divide (num1, num2):
return num1 / num2
print ("select an operation -\n "
"1. Add\n"\
"2. subtract\n"\
"3. multipy\n"\
"4. divide\n")
select: str = input("Select operations form 1, 2, 3, 4 :")
number_1 = int(input("Enter a number: "))
number_2 = int(input("Enter second number: "))
if select == '1':
print(number_1, "+", number_2, "=", number_1 + number_2)
elif select == '2':
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif select == '3':
print (number_1, "*",number_2, "=",
multiply (number_1, number_2))
elif select == '4':
print (number_1, "/", number_2, "=",
divide(number_1, number_2))
else:
print("Invalid input") | false |
f61c63306da10246202eb0b639ef379b154bdf56 | boustrophedon/algorithms_playground | /algo/topo_sort.py | 2,453 | 4.125 | 4 | from collections import defaultdict
# Creates a directed graph stored as an adjacency list, where each element in
# the list contains a list of incoming and outgoing edges, represented by the
# vertex on the other end. Technically I guess the vertices can be anything
# because we're storing them in a dict but they should ideally be integers.
class Graph:
""" A directed graph with adjacency list/dict storage. Each element in its
adjacency list contains a tuple of two lists, the first the outgoing edges
and the second the incoming edges. The edges are represented by the
index/element on the other end of the list.
"""
def __init__(self, edges=None):
""" Edges is a list of tuples of vertices `(v1, v2)` representing a
directed edge from `v1` to `v2`.
"""
# outgoing edges are adj_list[v][0]
# incoming edges are adj_list[v][1]
self.adj_list = defaultdict(lambda: (list(), list()))
if edges:
for v1, v2 in edges:
self.add_edge(v1, v2)
def add_edge(self, v1, v2):
""" Creates a directed edge between `v1` and `v2` if it does not
already exist. """
# outgoing
self.adj_list[v1][0].append(v2)
# incoming
self.adj_list[v2][1].append(v1)
def out(self, v):
""" Get the outgoing edges from vertex `v` """
return self.adj_list[v][0]
def inc(self, v):
""" Get the incoming edges from vertex `v` """
return self.adj_list[v][1]
def topo_sort(self):
""" Returns a list of the vertices representing at topological ordering
obeying the graph's structure. The algorithm in Kozen, and the one we
implement here, is the Kahn algorithm, not the DFS algorithm.
This version is modified from the one in the book to not modify the graph
in-place, at the expense of using O(n) more memory. """
queue = list()
order = list()
inc_remaining = dict()
for v, (out, inc) in self.adj_list.items():
if len(inc) == 0:
queue.append(v)
else:
inc_remaining[v] = len(inc)
while queue:
current = queue.pop()
order.append(current)
for v in self.out(current):
inc_remaining[v] -= 1
if inc_remaining[v] == 0:
queue.append(v)
return order
| true |
ccbab5b25c586c8374c1c18152715282c71383fa | noelis/coding_challenges | /anagram_palindrome.py | 1,580 | 4.125 | 4 | from collections import Counter
def is_anagram_of_palindrome(word):
""" Is the word an anagram of a palindrome?
anagram: a word formed by rearranging the letters of another.
ie: Cinema > iceman
palindrome: a word that reads the same backwards/forwards.
ie: madam, racecar
>>> is_anagram_of_palindrome("a")
True
>>> is_anagram_of_palindrome("ab")
False
>>> is_anagram_of_palindrome("aab")
True
>>> is_anagram_of_palindrome("arceace")
True
>>> is_anagram_of_palindrome("arceaceb")
False
>>> is_anagram_of_palindrome("aaa")
True
"""
word_cnt = Counter(word)
single_letter = 0
for count in word_cnt.values():
if count == 1:
single_letter += 1
if single_letter > 1:
return False
else:
return True
def check_word_palindrome(word):
"""Check if given word is a palindrome?
palindrome: a word that reads the same backwards/forwards.
ie: madam, racecar
>>> check_word_palindrome("a")
True
>>> check_word_palindrome("ab")
False
>>> check_word_palindrome("aab")
False
>>> check_word_palindrome("racecar")
True
>>> check_word_palindrome("tacocat")
True
"""
word = word.lower()
listify = list(word)
new_word = ""
listify.reverse()
if new_word.join(listify) == word:
return True
return False
if __name__ == '__main__':
import doctest
print
result = doctest.testmod()
if not result.failed:
print "All test cases passed."
print
| true |
5a5d3a96f9ffb49a929cdac8386081a878dd88e0 | patelrohan750/python_practicals | /Practicals/practicals3_A.py | 531 | 4.625 | 5 | # A.To add 'ing' at the end of a given string (length should be at least 3). If the given string
# already ends with 'ing' then add 'ly' instead. If the string length of the given stringis less than
# 3, leave it unchanged.
# Sample String : 'abc' Sample String : 'string'
# Expected Result :'abcing' Expected Result: 'stringly'
s=input("Enter the String: ")
if len(s)>2:
if s.endswith("ing"):
s+="ly"
print(s)
else:
s+="ing"
print(s)
else:
print("No change in String")
| true |
b28886450106d1330a8bc7368d87525227a9b380 | patelrohan750/python_practicals | /Practicals/practical8.py | 1,573 | 4.53125 | 5 | # to write a python program to create,slice,change,delete,and indexing elemnts using tuple
print("1.create")
print("2.slice")
print("3.change")
print("4.delete")
print("5.index")
print("6.display")
print("7.Exit")
user_choice = ''
tuple1 = ()
while user_choice != 7:
user_choice = int(input("select the choice:\n "))
if user_choice == 1:
elemnts_number = int(input("How many elemnts you want to Enter\n"))
elemnts = print("enter The Elemnts:")
for i in range(elemnts_number):
ele = input()
tuple1 = tuple1 + (ele,)
print("tuple is: ", tuple1)
elif user_choice == 2:
start_point = int(input("Enter The Starting point: "))
End_point = int(input("Enter The Ending point: "))
if start_point == 0 and End_point == 0:
print(tuple1[:])
elif start_point == 0:
print(tuple1[:End_point])
elif End_point == 0:
print(tuple1[start_point:])
else:
print(tuple1[start_point:End_point])
elif user_choice == 3:
print(
"tuples are immutable.\nThis means that elements of a tuple cannot be changed once they have been assigned. ")
elif user_choice == 4:
print("Tuple are immutable\n")
elif user_choice == 5:
tuple_index = int(input("Enter index: "))
print(tuple1[tuple_index])
elif user_choice == 6:
print(tuple1)
elif user_choice == 7:
exit()
else:
print("you Enter Wrong Choice...")
| false |
3d927a1717c751934c3cc5e9748cb1b83b4bf25f | patelrohan750/python_practicals | /Practicals/practical11_D.py | 782 | 4.375 | 4 | #D. write a python program to demonstrate inheritance
class Employee:
def __init__(self, name, salary, role):
self.name = name
self.salary = salary
self.role = role
def Dispaly_Emp_Details(self):
print(f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}")
class Programmer(Employee):
def __init__(self, name, salary, role, languages):
super().__init__(name,salary,role)
self.languages = languages
def Display_Pro_Deatails(self):
print(f"The Programmer's Name is {self.name}. Salary is {self.salary} and role is {self.role}."
f"The languages are {self.languages}")
p1=Programmer("rohan",20000,"Developer","python")
p1.Display_Pro_Deatails()
| false |
0770543b4b5dad1eb774f0d7d4025f8ed94f40a8 | nyanyehtun-simon/CP1404Prac | /Prac_03/word_generator.py | 1,208 | 4.21875 | 4 | """
CP1404/CP5632 - Practical
Random word generator - based on format of words
Another way to get just consonants would be to use string.ascii_lowercase
(all letters) and remove the vowels.
"""
import random
def main():
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
ALPHABETS = "abcdefghijklmnopqrstuvwxyz"
word_format = "ccvcvvc"
word = ""
word_format = input('Enter the word format % (for CONSONANTS) or # (for VOWELS)?: ').lower()
while not is_valid_format(word_format):
print('Enter only valid format V and C')
word_format = input('Enter the word format % (for CONSONANTS) or # (for VOWELS)?: ').lower()
for kind in word_format:
if kind == "%": # % for consonants
word += random.choice(CONSONANTS)
elif kind == '#': # # for vowels
word += random.choice(VOWELS)
elif kind == '*': # * for any alphabets
word += random.choice(ALPHABETS)
elif ALPHABETS.find(kind) >= 0: # if specific characters are provided
word += kind
print(word)
def is_valid_format(word_format):
if word_format in 'vc':
return True
else:
return False
main()
| true |
50894bed5b7fbfe2f78f353b33c4bf28f95c8c8f | m4rm0k/Python-Code-GitHUB | /neural_networks/perceptron.py | 2,318 | 4.21875 | 4 | """
Source:
https://natureofcode.com/book/chapter-10-neural-networks/
"""
import random
class Perceptron:
"""
A perceptron is the simplest type of a neural network:
A single node.
Given two inputs x1 and x2, the preceptron outputs a value, depending on the weighting.
"""
def __init__(self, nx=2, bias=0, c=0.01):
"""
Create the preceptron.
Parameters:
nx = Number of inputs, standard is 2. One will be added as bias
bias = Bias input starting value, standard value is 0, might change with evolution
c = learning speed, default is 0.01
"""
self.num_inputs = nx
self.weights = []
for _ in range(self.num_inputs):
self.weights.append(random.randint(-1, 1))
# bias gives a usefull output when all inputs are 0
self.weights.append(bias)
self.learning_rate = c
def activate(self, result):
"""
Activation function is simply: is it greater or smaller than 0?
"""
if result > 0:
return 1
else:
return -1
def feedforward(self, inputs):
"""
Processes the inputs and returns a single output
"""
processsum = 0
for i in range(len(inputs)):
processsum = processsum + inputs[i] * self.weights[i]
return self.activate(processsum)
def train(self, inputs, desired):
"""
Gets output for given input.
Then compares to desired result.
Adjusts weights if neccessary.
"""
inputs.append(1) # bias input
guess = self.feedforward(inputs)
error = desired - guess
for i in range(len(self.weights)):
self.weights[i] = self.weights[i] + \
self.learning_rate * error * inputs[i]
def debug_weights(self):
"""
This debug function returns all current weights.
"""
return self.weights
# this is purely test code:
if __name__ == '__main__':
print("Example training code...")
PTRON = Perceptron(2)
x_pos = random.random() * 20 - 10
y_pos = random.random() * 20 - 10
test_inptus = [x_pos, y_pos]
test_answer = 1
if y_pos < 2*x_pos + 1:
test_answer = -1
PTRON.train(test_inptus, test_answer)
| true |
a1d641457dfd8c6959a22f46d524fd1293a9cab7 | jfrichter4/Copy-of-Programming-Project | /Linear_equation_program.py | 526 | 4.3125 | 4 | #Simon Phipps
#3/4/21
#Point Connection program
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
#Input points
if (y2-y1)==0:
print("y=",y2)
print("Your line is horizantal!")
#If slope is 0, line is horizantal
elif(x2-x1)==0:
print("x=",x2)
print("Your line is vertical!")
#If slope is undefined, line is vertical
else:
m = (y2-y1)/(x2-x1)
print("Your line is", "y-",y1,"=",m,"(x-",x1,")")
#If not, solve for slope
| false |
bacd7e00852216c05d5406d2341653abe0e89d25 | yurijiao/python-homework | /PyBank/main.py | 1,226 | 4.21875 | 4 | # Import the pathlib and csv library
# set the file path
# initialize total month variable
# initialize variable to hold the monthly pnl list
# open the input path as a file object
# pass in the csv file to the csv.reader() function
# print the datatype of the csvreader
# read the header
# print the header
# read each row of data after the header with for loop
# print the row
# set monthly pnl variable to the second column of each row, change the data type fo integer
# append the rwo monthly pnl value to the list of monthly pnl
#initialize metric variables
min_mpnl = 0
max_mpnl = 0
avg_change = 0
total_change = 0
count_month = 0
# calculate the max, min, mean of the list of monthly pnl with for loop
# sum the total and count variables
# logic to determin min and max
# calculate the average and round
# print the metrics
# set the output file path
# open the output path as a file object
# set the file object as a csvwriter object
# write the header to the output file
# write the list of metrics to the output file
| true |
459df39eedc58b90f1e71e1215aa23c78257571d | ihuanglei/classical-algorithm | /python/algorithm/narcissisticnumber.py | 625 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: huanglei
# 水仙花数
# 小技巧:
#
# 如果要取一个数的每一位数字,用当前数字除以单位取整然后再和10取余
# 举例说明:
# 数字:123
# 个位: int(123 / 1) % 10
# 十位: int(123 / 10) % 10
# 百位: int(123 / 100) % 10
for i in range(100, 1000):
# 个位
units = i % 10
# 十位
tens = int(i / 10) % 10
# 百位
hundreds = int(i / 100) % 10
# 3次幂之和等于它本身,python中幂使用 **
if (units ** 3 + tens ** 3 + hundreds ** 3) == i:
print('{} 是水仙花数'.format(i))
| false |
7bfabf7d61b358947084cfe41e5bbf1bcf93be2b | E-Ozdemir/Python_Assignments | /prime_number.py | 228 | 4.125 | 4 | ###Prime Number###
x = int(input('Write a number: '))
count = 0
for i in range(1,x+1):
if not x % i:
count += 1
if (x == 0) or (x==1) or (count>=3):
print(x,'is not a prime number')
else:
print(x,'is a prime number')
| true |
b333f8ad268cdf96b38585f7d0c6d2ae1055912e | saisuma98/Sample-Python-Programs | /venv/aq4_sqlite.py | 1,675 | 4.53125 | 5 | # Python code to demonstrate table creation and
# insertions with SQL
# importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect("Emp.db")
# cursor
crsr = connection.cursor()
# SQL command to create a table in the database
sql_command = """CREATE TABLE emp (
EmpID INTEGER PRIMARY KEY,
DeptName VARCHAR(20),
Gross_Salary INTEGER);"""
# execute the statement
crsr.execute(sql_command)
# SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (1, "Quality Control", 10000);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (2, "Finance", 20000);"""
crsr.execute(sql_command)
sql_command = """INSERT INTO emp VALUES (3, "Quality Control", 50000);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (4, "Finance", 60000);"""
crsr.execute(sql_command)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
#Till here not requiired
# from here onwards answers the question
# connecting to the database
connection = sqlite3.connect("Emp.db")
# cursor
crsr = connection.cursor()
#sql command to find the sum of gross salary of employees working under Quality Control Department
sql_command = """SELECT sum(Gross_Salary) FROM emp where DeptName = "Quality Control"; """
crsr.execute(sql_command)
ans = crsr.fetchall()
# loop to print all the data
for i in ans:
print(i)
# close the connection
connection.close()
| true |
a79897d69d9e864c91e9e8c3d79faba43e4608e8 | Klimushin/HW | /Lesson5+HW/squared_numbers.py | 759 | 4.4375 | 4 | # Написать функцию которая будет простое число
# возводить в квардрат. Необходимо возвести в
# квадрат все простые числа в списке,
# используя функцию map. Список задается последним
# его числом.
a=int(input("Укажите последнее число списка: \n"))
numbers = []
for num in range(2,a+1):
if all(num%i!=0 for i in range(2,num)):
numbers.append(num)
print('Простые числа:','\n',numbers)
def my_square(num):
return num ** 2
squared_numbers = list(map(my_square, numbers))
print('Квадраты простых чисел:','\n', squared_numbers, end="")
| false |
a47c17de8c225e684ae23e3c95166f711b2ec649 | HolaAmigoV5/Python | /Filter.py | 545 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#һ
def _odd_iter():
n=1
while True:
n=n+2
yield n
#һɸѡ
def _not_divisible(n):
return lambda x:x%n>0
#һϷһ
def primes():
yield 2
it=_odd_iter() #ʼ
while True:
n=next(it) #еĵһ
yield n
it=filter(_not_divisible(n),it) #
for n in primes():
if n<1000:
print(n)
else:
break | false |
1a7da262b65302fc244d25dd2faf9b8f28ba6a69 | Ayush-Malik/PracAlgos | /link_list/linked_list_length_is_even_or_odd.py | 1,185 | 4.1875 | 4 | # https://practice.geeksforgeeks.org/problems/linked-list-length-even-or-odd/1/?category[]=Linked%20List&category[]=Linked%20List&page=1&query=category[]Linked%20Listpage1category[]Linked%20List#
class Node:
def __init__(self , data) -> None:
self.data = data
self.next = None
class LinkedList:
def __init__(self) -> None:
self.head = None
def insert(self , data):
if self.head == None:
self.head = Node(data)
else:
temp = self.head
while temp.next != None:
temp = temp.next
temp.next = Node(data)
def display(self):
temp = self.head
while temp != None:
print(temp.data)
temp = temp.next
def linked_list_length_is_even_or_odd(head):
temp = head
while temp != None:
if temp.next != None and temp.next.next != None:
temp = temp.next.next
else:
break
if temp.next == None:
print("ODD")
else:
print("EVEN")
ll = LinkedList()
ll.insert(36)
ll.insert(10)
ll.insert(40)
ll.insert(5)
ll.insert(50)
ll.display()
linked_list_length_is_even_or_odd(ll.head)
| true |
a75ebb682e9b74c6d99fd3a1f60c424c478df682 | Ayush-Malik/PracAlgos | /find_the_two_repeating_elements_in_a_given_array.py | 550 | 4.15625 | 4 | # https://www.geeksforgeeks.org/find-the-two-repeating-elements-in-a-given-array/
# [1]
# 2, 3, 1, 3, 9, 4, 5, 9, 6, 7, 8
# Duplicate elements are : 3 9
# O(N) Time => 2 Traversals
# O(1) Constant space
arr = list(map(eval , input().split(', ')))
def get_two_duplicates_from_(arr):
for i in range(len(arr)):
arr[ abs(arr[i]) - 1 ] = -arr[ abs(arr[i]) - 1]
print("Duplicate elements are :" , end = " ")
for i in range(len(arr) - 2):
if arr[i] > 0:
print(i + 1 , end = " ")
get_two_duplicates_from_(arr) | false |
335d10789f74b0f213caddf85685b2cbbf86d095 | Rameshtech17/Python_Assignment | /2.py | 514 | 4.28125 | 4 | """
2.Printing Star sequence (take n=4). The Program should be able to print for any number (n - 5,6,7, etc..)
*
* *
* * *
* * * *
"""
i = int(input("Enter The i Value:"));
n = i + 1
for j in range(1, i + 1, 1):
for l in range(n, 1, -1):
print(" ", end="")
for k in range(j):
print("* ", end="")
print()
n -= 1
"""
Output:
Enter The i Value:8
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
"""
| true |
c8da325da735dca95870597067cbb226cec9e52b | WuLC/show-me-the-code | /0006/count_words.py | 1,670 | 4.375 | 4 | # -*- coding: utf-8 -*-
# @Author: WuLC
# @Date: 2016-04-27 22:37:47
# @Last modified by: WuLC
# @Last Modified time: 2016-05-06 17:25:34
# @Email: liangchaowu5@gmail.com
# @Function: remove stopwords and count the words in a English File
import re
import os
def load_stopwords(file_path):
"""load the stop words in English
Args:
file_path (str):stop words file path
Returns:
set:a set containing all the stop words
"""
if not os.path.isfile(file_path):
print '%s not found'%file_path
return
with open(file_path) as f:
words = f.readlines()
for i in xrange(len(words)):
words[i]=words[i].rstrip()
return set(words)
def count_words(file_path):
"""count the number of occurance for each word in a file except stopwords
Args:
file_path (str):path of a file to be checked
Returns:
dictionary: number of occurance for each word
"""
if not os.path.isfile(file_path):
print '%s not found'%file_path
return
stopword_file = 'StopWords.txt'
stopwords = load_stopwords(stopword_file)
with open(file_path) as f:
text = f.readlines()
str_text = ''.join(text)
pattern = re.compile('[a-zA-Z-]+')
word_list = re.findall(pattern,str_text)
result_dict = {}
for word in word_list:
if word.lower() in stopwords or len(word) == 1:
continue
if word not in result_dict:
result_dict[word] = 0
result_dict[word] += 1
return result_dict
if __name__ == '__main__':
file = 'test.txt'
result = count_words(file)
for i in result:
print i,result[i]
| true |
55d380ef8c797b34f914b2c66fa3880c405e3a2a | Pushss/tkinter_basic_app | /script.py | 1,856 | 4.15625 | 4 | from tkinter import * #import all from tkinter libary. allows use of Button() instead of tkinter.Button()
window=Tk() #create window
def conversion(): #function used to for onClick on button command=
value = e1_value.get() #value from value(editText) need to use .get()
grams= float(value) * 1000 #convert value to float multiply
pounds=float(value) * 2.20462
ounces=float(value) * 35.274
t1.insert(END,grams) #insert something in to t1 ,param's where to put text, e1_value variable wanting to insert
t2.insert(END,pounds) #insert something in to t2 ,param's where to put text, e1_value variable wanting to insert
t3.insert(END,ounces) #insert something in to t3 ,param's where to put text, e1_value variable wanting to insert
l1=Label(window, text="Kg:") #Label (call to window, display text "Kg:")
l1.grid(row=0,column=0) #postions Label widget on grid
e1_value=StringVar() #declare string variable to store Entry() data
e1=Entry(window, textvariable=e1_value) #entry widget (editText)(textvariable = e1_value)
e1.grid(row=0,column=1) #postions entry widget on grid
b1=Button(window, text="Convert",command=conversion) #create button (places in window, text="String",command=call's function without ())
b1.grid(row=0,column=2) #places the button on the window can define postion with .grid(grid can have row=0, column=0 for easier placement, rowspan=number of grid row the button will span) or .pack
t1=Text(window,height=1,width=20) #text widget(textView)
t1.grid(row=1,column=0) #postions text widget on grid
t2=Text(window,height=1,width=20) #text widget(textView)
t2.grid(row=1,column=1) #postions text widget on grid
t3=Text(window,height=1,width=20) #text widget(textView)
t3.grid(row=1,column=2) #postions text widget on grid
window.mainloop() #allows window to remain open permentaly keep this at end of code
| true |
3a4216f7e38babb7ac07f81774469f0f6d598762 | zhongmb/python3_learning | /green_hand_tutorail/ght_011_loop.py | 1,565 | 4.3125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
Python3 循环语句
Python中的循环语句有 for 和 while。
同样需要注意冒号和缩进。另外,在Python中没有do..while循环。
无限循环
我们可以通过设置条件表达式永远不为 false 来实现无限循环
你可以使用 CTRL+C 来退出当前的无限循环。
无限循环在服务器上客户端的实时请求非常有用。
while 循环使用 else 语句
简单语句组
类似if语句的语法,如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中
range()函数
如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列
break和continue语句及循环中的else子句
break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。
'''
import sys
def find_prime_number(max_number):
'''查找质数'''
print(2, '是质数')
for check_num in range(3, max_number, 2):
for factor_num in range(3, check_num, 2):
if check_num % factor_num == 0:
print(check_num, '等于', factor_num, '*', check_num // factor_num)
break
else:
# 循环中没有找到元素
print(check_num, '是质数')
def main(argv):
'''主函数'''
print("运行参数", argv)
print(__doc__)
find_prime_number(100)
if __name__ == "__main__":
main(sys.argv)
| false |
7feb11485aa268bd25e948fc781485fd20b09a36 | cookToCode/PythonCashier | /PythonCashier/PythonCashier/PythonCashier.py | 1,989 | 4.25 | 4 | #cookToCode
#Created for School
#12/10/2018
#This program will total purchased items, tax if need be, and calculate change
#Variable Dictionary:
#cost -Cost of an individual item
#totalCost -The cost of all items
#finalCost -The total amount of all items and tax
#tax -The tax on an indiviudal item if applicable
#totalTax -The total tax on all taxable items
#payment -User inputed payment to the cashier
#change -The change due to the user
#more -Variable used to indicate if the user has more items to add
#taxable -Variable used to indicate if the user's item is taxable
#------------------------------Functions-----------------------------------------------
#This will take the price of the item and return the amount added in tax
def taxFunc():
tax = cost * .07
return tax
#This will calculate and print the change given to the user
def changeFunc():
change = payment - finalCost
print(f'Your change is ${change:.2f}')
#-----------------------Program Begins----------------------------------
#more starts the loop
more = 'y'
#This sets a spot for the totals to add up
totalTax = float(0.0)
totalCost = float(0.0)
finalCost = float(0.0)
#loop begins
while more == 'y' or more == 'Y':
taxable = input('If the item is taxable please enter a t for taxable or an n for not taxable.\t:')
cost = float(input('Enter the price of the item.\t:$'))
if taxable == 't' or taxable == 'T':
tax = taxFunc()
totalTax = tax + totalTax
totalCost = cost + totalCost
finalCost = totalCost + totalTax
more = input('Do you have anymore items to purchase (y/n)?\t:')
#Loop ends
print('\n\n') #This just adds space
print(f'Cost of items is ${totalCost:.2f}')
print(f'Tax ${totalTax:.2f}')
print(f'Total ${finalCost:.2f}')
print('\n\n') #This just adds space
payment = float(input('How much money are you giving the clerk?\t:$'))
changeFunc()
| true |
7be3ebf22968c0c238551a123e68174ee6124abd | aaditjain-official/Pythonproject | /stringbasic.py | 1,169 | 4.21875 | 4 | #print("I am Aadit")
#y= "My Name is {name}".format(name="Aadit") # that's how format() works in string
#z="I lives in {country}"
s="string is good"
#a="Allthingsinalphabet"
#n="90"
print(s.replace("g","bad"))
#print(y)
#print(z.format(country="India")) # format() sets a placeholder value in string
#print(s.index("o")) # sames as find()
#print(s.find("o"))# Returns the position of character in string , o exists at 11th position in string
#print(s[10:14]) #slicing
#print(s.count("z")); #z doesn't exist
#print(s.count("o")) # o exists 2 times
#print(s.count("o",12)) # o exists 2 times , but the count starts from 12th position
#print(s.endswith("d"))
#print(s.endswith("o"))
#print(s.startswith("s"))
#print(s.encode())
#print(s.islower())
#print(s.isalpha()) # Returns False
#print(a.isalpha()) #Returns True
#print(s.isupper())
#print(s.casefold())
#print(s.upper())
#print(s.center(50))
#print((s.center(100,"-")).upper())
#print(s[0])
#print(s.capitalize())
#print(len(s))
#print(s.replace("good","bad"))
#print(s.count())
#import math
#print(math.ceil(9.2))
#print(n.isdigit()) # Returns True , if numbers are in string | true |
0088475564c4c075f761dee04ba1b56aeb1af25b | ujasmandavia/mit6.006 | /lecture02/docdist6.py | 2,880 | 4.3125 | 4 | """
Lecture 2:
Document Distance
-----------------
This iteration uses a more efficient sorting
algorithm to sort the terms in the documents.
"""
from get_documents import get_documents
import math
import string
translation_table = string.maketrans(
string.punctuation + string.uppercase,
" " * len(string.punctuation) + string.lowercase
)
def get_words_from_string(line):
"""
Split a string into a list of words.
"""
line = line.encode('utf-8')
line = line.translate(translation_table)
word_list = line.split()
return word_list
def get_words_from_line_list(L):
"""
Transform the lines in the document, a list
of strings, into a list of words.
"""
word_list = []
for line in L:
words_in_line = get_words_from_string(line)
word_list.extend(words_in_line)
return word_list
def count_frequency(word_list):
"""
Count the frequency of each word in the list
by scanning the list of already encountered
words.
"""
D = dict()
for new_word in word_list:
if new_word in D:
D[new_word] = D[new_word] + 1
else:
D[new_word] = 1
return D.items()
def merge(left, right):
"""
Merge two sorted lists into a single
sorted list.
"""
i = 0
j = 0
result = []
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
if i < len(left):
result.extend(left[i:])
if j < len(right):
result.extend(right[j:])
return result
def merge_sort(L):
"""
Merge sort, a sorting algorithm
for lists.
"""
n = len(L)
if n < 2:
return L
left = merge_sort(L[:n / 2])
right = merge_sort(L[n / 2:])
return merge(left, right)
def word_frequencies_for_file(line_list):
"""
Transform the document into a frequency map
for each term.
"""
word_list = get_words_from_line_list(line_list)
freq_map = count_frequency(word_list)
freq_map = merge_sort(freq_map)
return freq_map
def inner_product(L1, L2):
"""
Take the inner product of the frequency maps.
"""
result = 0.
i = 0
j = 0
while i < len(L1) and j < len(L2):
if L1[i][0] == L2[j][0]:
result += L1[i][1] * L2[j][1]
i += 1
j += 1
elif L1[i][0] < L2[j][0]:
i += 1
else:
j += 1
return result
def vector_angle(L1, L2):
"""
Compute the angle between two frequency vectors.
"""
numerator = inner_product(L1, L2)
denominator = math.sqrt(inner_product(L1, L1) * inner_product(L2, L2))
return math.acos(numerator / denominator)
def main():
"""
Compute the document distance.
"""
doc1, doc2 = get_documents()
freq_map1 = word_frequencies_for_file(doc1)
freq_map2 = word_frequencies_for_file(doc2)
distance = vector_angle(freq_map1, freq_map2)
print 'The distance between the documents is %0.6f (radians)' % distance
| true |
3f808fbbc17ff3926fbc7dcbc6536ac1b0709b84 | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex4/ex4.4.py | 713 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Exercise 4.4.
The letters of the alphabet can be constructed from a moderate number of basic
elements, like vertical and horizontal lines and a few curves. Design an alphabet
that can be drawn with a minimal number of basic elements and then write functions
that draw the letters.
You should write one function for each letter, with names draw_a, draw_b, etc.,
and put your functions in a file named letters.py.
You can download a “turtle typewriter” from http://thinkpython2.com/code/typewriter.py
to help you test your code.
You can get a solution from http://thinkpython2.com/code/letters.py ; it also requires
http://thinkpython2.com/code/polygon.py
"""
# Skipped that one.
| true |
99a3986dc06c9adbbb83a19b789b767b5f2e6e91 | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex9/ex9.9.py | 1,019 | 4.125 | 4 | #!/usr/bin/env python3
"""
Exercise 9.9.
Here’s another Car Talk Puzzler you can solve with a search
(http://www.cartalk.com/content/puzzlers):
“Recently I had a visit with my mom and we realized that the two digits that make
up my age when reversed resulted in her age. For example, if she’s 73, I’m 37. We
wondered how often this has happened over the years but we got sidetracked with other
topics and we never came up with an answer."
“When I got home I figured out that the digits of our ages have been reversible
six times so far. I also figured out that if we’re lucky it would happen again in
a few years, and if we’re really lucky it would happen one more time after that.
In other words, it would have happened 8 times over all. So the question is,
how old am I now?”
Write a Python program that searches for solutions to this Puzzler.
Hint: you might find the string method zfill useful.
Solution: http://thinkpython2.com/code/cartalk3.py
"""
# Couldn't figure it out by myself ;<
| true |
b46be965d7bc703b4173ca42bb246c55f7114573 | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex10/ex10.1.py | 398 | 4.3125 | 4 | #!/usr/bin/env python3
"""
Exercise 10.1.
Write a function called nested_sum that takes a list of lists of integers and
adds up the elements from all of the nested lists. For example:
>>> t = [[1, 2], [3], [4, 5, 6]]
>>> nested_sum(t)
21
"""
def nested_sum(li):
result = 0
for elem in li:
result += sum(elem)
return result
t = [[1, 2], [3], [4, 5, 6]]
print(nested_sum(t))
| true |
da75928722946729249f137b5326687dd630b099 | adwanAK/adwan_python_core | /think_python_solutions/chapter-18/exercise-18.1.py | 1,847 | 4.25 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
exercise-18.1.py
Created by Terry Bates on 2014-08-02.
Copyright (c) 2014 http://the-awesome-python-blog.posterous.com. All rights reserved.
"""
import sys
import os
class Time(object):
"""Represents the time of day.
attributes: hour, minute, second
"""
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
# Use join to quickly print out string colon separated
return ':'.join([str(self.hour).zfill(2), str(self.minute).zfill(2), str(self.second).zfill(2)])
def time_to_int(self):
# We create fractional portions of the "hour" attribute
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds
def increment(self, seconds):
# Turn the time object into seconds
"""
:rtype : object
"""
self_seconds = self.time_to_int()
ret_time_seconds = self_seconds + seconds
return self.int_to_time(ret_time_seconds)
def is_after(self, other):
# Return result from comparing via compute_scalar_time
return self.time_to_int() < other.time_to_int()
def __add__(self, other):
if isinstance(other, Time):
return self.increment(other.time_to_int())
else:
return self.increment(other)
def __cmp__(self, other):
return cmp(self.time_to_int() - other.time_to_int())
@staticmethod
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def main():
t1 = Time(12, 59, 30)
t2 = Time(11, 59, 30)
t
if __name__ == '__main__':
main()
| true |
1db5398cb69952da6369f6e642b1496b9cec49e7 | adwanAK/adwan_python_core | /week_03/labs/10_classes_objects_methods/10_01_try_methods.py | 884 | 4.40625 | 4 | '''
Read the documentation of the string methods at:
http://docs.python.org/3/library/stdtypes.html#string-methods.
You might want to experiment with some of them to make sure you
understand how they work. strip and replace are particularly useful.
The documentation uses a syntax that might be confusing.
For example, in find(sub[, start[, end]]), the brackets indicate
optional arguments. So sub is required, but start is optional, and if
you include start, then end is optional.
Demonstrate below:
- strip
- replace
- find
Source: Exercise in chapter "Strings" in Think Python 2e:
http://greenteapress.com/thinkpython2/html/thinkpython2009.html
'''
str_1 = "Hello# Worl#d#"
print("")
print(str_1.strip("#"))
print(str_1.replace("#",""))
print(f"'W' Found at position:{str_1.find('W')}")
print(f"'l' is found at {str_1.find('l', 5)} where we started search at index 5")
| true |
01ebb1f858f87c5210d1117237e672e3d7651186 | adwanAK/adwan_python_core | /think_python_solutions/chapter-15/exercise-15.2.py | 1,568 | 4.28125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
exercise-15.2.py
Created by Terry Bates on 2014-02-19.
Copyright (c) 2014 http://the-awesome-python-blog.posterous.com.
All rights reserved.
"""
import sys
import os
import math
class Point(object):
"""Represent point in 2-D space"""
class Rectangle(object):
"""Represents a rectangle.
attributes: width, height, corner.
"""
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width/2.0
p.y = rect.corner.y + rect.height/2.0
return p
def distance_between_points(p,q):
y_diff = p.y - q.y
x_diff = p.x = q.x
y_sqr = math.pow(y_diff,2)
x_sqr = math.pow(x_diff,2)
x_y_sum = y_sqr + x_sqr
return math.sqrt(x_y_sum)
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
def move_rectangle(rect, dx, dy):
rect.corner.x += dx
rect.corner.y += dy
return rect
def main():
# Create first Point object
first = Point()
first.x = 5
first.y = 6
# Create second Point object
second = Point()
second.x = 10
second.y = 15
print distance_between_points(first, second)
# Create rectangle object
my_rect = Rectangle()
# Add a point as an attribute
my_rect.corner = Point()
my_rect.width = 10.0
my_rect.height = 20.0
# Create the Point's values
my_rect.corner.x = 15
my_rect.corner.y = 10
print_point(my_rect.corner)
# Move the rectangle around
moved_rect = move_rectangle(my_rect, 5, 8)
print_point(moved_rect.corner)
if __name__ == '__main__':
main()
| false |
2ec74b3ae19c1d2ddcdc4cde690030bb492d13eb | adwanAK/adwan_python_core | /week_03/labs/06_strings/Exercise_06.py | 438 | 4.375 | 4 | '''
Complete exercises in section 8.7 (p.75)
CODE:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
1) - Encapsulate this code in a function named count,
and generalize it so that it accepts the string and the letter as arguments.
2) - Rewrite this function so that instead of traversing the string,
it uses the three-parameter version of find from the previous section.
'''
| true |
e15278fb9c2fcff995824b9b3e2c9a7bcfa15c38 | adwanAK/adwan_python_core | /week_03/labs/07_lists/Exercise_02.py | 598 | 4.25 | 4 | '''
Given the two lists below, find the elements that are the same
and put them in a new list.
Put the elements that are different in another list.
Print both.
'''
list_one = [0, 4, 6, 18, 25, 42, 100]
list_two = [1, 4, 9, 24, 42, 88, 99, 100]
common_list = []
diff_list = []
# make the lists of set objects for easier computations
set_one = set(list_one)
set_two = set(list_two)
set_common = set_one.intersection(set_two)
set_difference = set_one.symmetric_difference(set_two)
# print as a list
print("Common elements:", list(set_common))
print("Different elements:", list(set_difference))
| true |
fbcead16cd4618e05d552415ff14303013fb58db | adwanAK/adwan_python_core | /think_python_solutions/chapter-06/exercise-6.7.py | 846 | 4.46875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
exercise-6.7.py
First, and likely last, commit of Exercise 6.7. Create an 'is_power' function such that it will return True, if given parameters (a,b), it will return True if a is divisible by b and if a/b is a power of b.
Created by Terry Bates on 2012-08-16.
Copyright (c) 2012 http://the-awesome-python-blog.posterous.com.
All rights reserved."""
import sys
import os
def is_power(a,b):
# print "a:%s b:%s" % (a, b)
# print "a % b " + str(a % b)
# print "a/b " + str(a/b)
# print "#" * 20
if (a % b == 0):
return True
if (a/b == 1):
return True
#print "a/b %s Return TRUE" % (a/b)
else:
(is_power (a/b, b) )
else:
return False
if __name__ == '__main__':
print is_power(64,2)
print is_power(9,2)
| true |
c676b306ef611a7c40dfde5764e964797fb1eb97 | adwanAK/adwan_python_core | /think_python_solutions/chapter-18/exercise-18.2.py | 1,657 | 4.15625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
exercise-18-2.py
Created by Terry Bates on 2014-08-02.
Copyright (c) 2014 http://the-awesome-python-blog.posterous.com. All rights reserved.
"""
import sys
import os
import random
class Card(object):
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7','8',
'9', '10', 'Jack', 'Queen', 'King']
def __str__(self):
return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit])
"""Represents a standard playing card."""
def __init__(self, suit=0, rank=2):
self.suit = suit
self.rank = rank
def __cmp__(self, other):
t1 = self.suit, self.rank
t2 = other.suit, other.rank
return cmp(t1, t2)
class Deck(object):
# Alternative with nasty list comprehension
# self.cards = [Card(suit,rank) for suit in range(4)
# for rank in range(1, 14)]
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
def __str__(self):
# Or use a list comprehension
# res = [str(card) for card in self.cards]
res=[]
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
def shuffle(self):
random.shuffle(self.cards)
def add_card(self, card):
self.cards.append(card)
def sort(self):
# Method to have deck sort itself.
self.cards.sort(cmp=Card.__cmp__)
def main():
pass
if __name__ == '__main__':
main()
| true |
eb96f55812d0274e6c26876207b7f6e236e105a3 | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex8/ex8.5.py | 1,671 | 4.59375 | 5 | #!/usr/bin/env python3
"""
Exercise 8.5.
A Caesar cypher is a weak form of encryption that involves “rotating” each letter
by a fixed number of places. To rotate a letter means to shift it through the
alphabet, wrapping around to the beginning if necessary, so ’A’ rotated by 3 is ’D’
and ’Z’ rotated by 1 is ’A’. To rotate a word, rotate each letter by the same amount.
For example, “cheer” rotated by 7 is “jolly” and “melon” rotated by -10 is “cubed”.
In the movie 2001: A Space Odyssey, the ship computer is called HAL, which is
IBM rotated by -1.
Write a function called rotate_word that takes a string and an integer as parameters,
and returns a new string that contains the letters from the original string rotated
by the given amount.
You might want to use the built-in function ord, which converts a character to
a numeric code, and chr, which converts numeric codes to characters. Letters of
the alphabet are encoded in alphabetical order, so for example:
>>> ord('c') - ord('a')
2
Because 'c' is the two-eth letter of the alphabet.
But beware: the numeric codes for upper case letters are different.
Potentially offensive jokes on the Internet are sometimes encoded in ROT13,
which is a Caesar cypher with rotation 13. If you are not easily offended,
find and decode some of them.
Solution: http://thinkpython2.com/code/rotate.py
"""
def rotate_word(word, shift):
"""Uses Ceasar cypher to encrypt given word using given shift."""
rotated_word = ''
for letter in word:
rotated_word += chr(ord(letter) + shift)
return rotated_word
print(rotate_word('cheer', 7))
print(rotate_word('IBM', -1))
| true |
cbdcfe9612fa88f34af67ff5a18d6c5c2d260513 | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex9/ex9.8.py | 1,523 | 4.375 | 4 | #!/usr/bin/env python3
"""
Exercise 9.8.
Here’s another Car Talk Puzzler (http://www.cartalk.com/content/puzzlers):
“I was driving on the highway the other day and I happened to notice my odometer.
Like most odometers, it shows six digits, in whole miles only. So, if my car had
300,000 miles, for example, I’d see 3-0-0-0-0-0."
“Now, what I saw that day was very interesting. I noticed that the last 4 digits
were palindromic; that is, they read the same forward as backward. For example,
5-4-4-5 is a palindrome, so my odometer could have read 3-1-5-4-4-5."
“One mile later, the last 5 numbers were palindromic. For example, it could have
read 3-6-5-4-5-6. One mile after that, the middle 4 out of 6 numbers were palindromic.
And you ready for this? One mile later, all 6 were palindromic!"
“The question is, what was on the odometer when I first looked?”
Write a Python program that tests all the six-digit numbers and prints any numbers
that satisfy these requirements.
Solution: http://thinkpython2.com/code/cartalk2.py
"""
def is_palindrome(word):
return word == word[::-1]
def searched_number(number):
if is_palindrome(str(number)[2:]):
number += 1
if is_palindrome(str(number)[1:]):
number += 1
if is_palindrome(str(number)[1:5]):
number += 1
if is_palindrome(str(number)):
return True
return False
for num in range(100000, 1000000):
if searched_number(num):
print(num)
| true |
eb8ddf21b0ae313870c8b0bd2e8f0642d11313ca | adwanAK/adwan_python_core | /week_02/labs/03_variables_statements_expressions/Exercise_05.py | 288 | 4.21875 | 4 | '''
Write the necessary code to display the area and perimeter of a rectangle
that has a width of 2.4 and a height of 6.4
'''
width = 2.4
height = 6.4
area = width * height
print("area is: ")
print(area)
print("perimeter is: ")
perimeter = (2 * width) + (2 * height)
print(perimeter)
| true |
f0cd3aad0c552b3717fc319934923415fb449728 | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex5/ex5.1.py | 1,258 | 4.53125 | 5 | #!/usr/bin/env python3
"""
Exercise 5.1.
The time module provides a function, also named time, that returns the current
Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a
reference point. On UNIX systems, the epoch is 1 January 1970.
>>> import time
>>> time.time()
1437746094.5735958
Write a script that reads the current time and converts it to a time of day
in hours, minutes, and seconds, plus the number of days since the epoch.
"""
import time
last_epoch = time.time()
def current_time(since_epoch):
"""Calculates current hour, minute, and second since given epoch;
since epoch - in seconds.
"""
hours_since = since_epoch // 60 // 60
current_hour = hours_since - (hours_since // 24) * 24
minutes_since = since_epoch // 60
current_minute = minutes_since - (minutes_since // 60) * 60
second_since = since_epoch // 1 # to round down seconds
current_second = second_since - (second_since // 60) * 60
return current_hour, current_minute, current_second
def days_since_epoch(epoch):
"""Returns number of days since given epoch;
epoch - in seconds.
"""
days = epoch // 60 // 60 // 24
return days
print(current_time(last_epoch))
print(days_since_epoch(last_epoch))
| true |
10e372fd95aab7e987aed84701c3d1624d1a00ca | adwanAK/adwan_python_core | /week_03/labs/06_strings/Exercise_03.py | 1,167 | 4.1875 | 4 | '''
Complete Exercise 8.4 (p.96) from the textbook by writing out the docstrings for the functions.
'''
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
# any_lowercase1() will return on first character which doesn't produce what we want
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
# any_lowercase2() will only evaluate the letter 'c' not the parameter we are passing
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
# any_lowercase3() will run through the whole string and return on last character value only.
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
# This one works and I do not know why. I have to ask instructor
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
# any_lowercase5() Not doing what we want.
# Checks every letter if it is not lowercased and returns boolean if all the
# letters in string are lowercased or not;
| true |
d5f26c7a4a6a006ac92c2f8661e139f7126ac22f | adwanAK/adwan_python_core | /solutions/labs_w1_w2/04_Loops_10.py | 521 | 4.28125 | 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.
'''
# a nice way to gather multiple use inputs at once
lower, upper = input("Enter lower and upper bound (both inclusive), \
separated by a space: ").split()
for n in range(int(lower), int(upper)+1):
# input() collects str type, so we'll have to convert it to int
# +1 because range() upper bound is exclusive
print(n**2)
| true |
2cade87f7ab307a670aa9ac69b0afa0a88f17d4b | patrenaud/Python | /CoursPython/stringDelete.py | 377 | 4.25 | 4 | # Fuck vowels
# Demonstrates creating a new string with a for loop
message = input("Enter a message: ")
newMessage = ""
VOWELS = "aeiou"
print()
for letter in message:
if letter.lower() not in VOWELS:
newMessage += letter
#print("New string created: ", newMessage)
print("\nYour message without vowels is: ", newMessage)
input("\n\nPress enter to quit")
| true |
88a532d011cf1cf264d27b7c353438a205d662a5 | GeorgeDonchev/Homework-Assignments | /Password.py | 351 | 4.125 | 4 | import re
pattern = r"^(\S+)>([0-9]{3})\|([a-z]{3})\|([A-Z]{3})\|(\S[^<>]{2})<(\1)"
n = int(input())
for _ in range(n):
text = input()
matches = re.findall(pattern, text)
if not matches:
print("Try another password!")
continue
for match in matches:
print(f"Password: {match[1]}{match[2]}{match[3]}{match[4]}") | false |
2a6c704efe46d9a1c49eb03aabff35325f336336 | joshuatvernon/COMP3308-Assignemnt-1 | /State.py | 1,459 | 4.21875 | 4 | class State(object):
"""
Implementation of a State in Python.
"""
# Initalise state with optional parent and children
def __init__(self, state, parent_state=None, children_states=None):
# Initalise state
self.state = state
# Initalise parent state
self.parent_state = parent_state
# Initalise depth
if self.parent_state == None or self.parent_state == State(None):
self.depth = 0
else:
self.depth = self.parent_state.get_depth() + 1
# Initalise children states
if children_states:
self.children_states = children_states
else:
self.children_states = []
# return state
def get_state(self):
return self.state
# return parent state
def get_parent(self):
return self.parent_state
# return depth
def get_depth(self):
return self.depth
# return children states
def get_children(self):
return self.children_states
# set state
def set_state(self, state):
self.state = state
# set parent state
def set_parent(self, parent_state):
self.parent_state = parent_state
# set children states
def set_children(self, children_states):
self.children_states = children_states
# return true if same state value, parent state value and children state values, else false
def __cmp__(self, other_state):
return other_state.get_state() == self.state and \
other_state.get_parent() == self.parent_state and \
other_state.get_children() == self.children_states
| false |
36dc5d4e17d98cca76b1ba06be88f88a20b7fc2e | SallyMj0325/Python_Study | /list.py | 1,187 | 4.1875 | 4 | odd = [1, 3, 5, 7, 9]
print(odd)
print(odd[0])
# 리스트 인덱싱
a = [1, 2, 3]
print( a )
# 리스트의 슬라이싱
a = [1, 2, 3, 4, 5]
b = a[0:2]
print( a[0:2] )
a = "12345"
b = a[0:2]
print( a[0:2] )
a = [1, 2, 3, 4, 5]
b = a[:2]
c = a[2:]
print( a[:2] )
print( a[2:] )
a = [1, 2, 3, 4, 5]
b = a[1:3]
print( a[1:3])
# 리스트 더하기(+)
a = [1, 2, 3]
b = [4, 5, 6]
print( a + b )
# 리스트 반복하기(*)
a = [1, 2, 3]
print( a * 3 )
# 리스트 길이 구하기
a = [1, 2, 3]
b = len(a)
print( len(a) )
# 리스트에서 값 수정하기
a = [1,2,3]
a[2] = 4
print( a )
# del 함수 사용해 리스트 요소 삭제하기
a = [1, 2, 3]
del a[1]
print( a )
a = [1, 2, 3, 4, 5]
del a[2:]
print( a )
# 리스트에 요소 추가(append)
a = [1, 2, 3]
a.append(4)
print( a )
a.append([5,6])
print( a )
# 리스트 정렬(sort)
a = [1, 4, 3, 2]
a.sort()
print( a )
a = ['a', 'c', 'b']
a.sort()
print( a )
# 리스트 뒤집기(reverse)
a = ['a', 'c', 'b']
a.reverse()
print( a )
# 위치 변환(index)
a = [1,2,3]
a = a.index(3)
print( a )
a = [1,2,3]
a = a.index(1)
print( a )
# 리스트에 요소 산입(insert)
a = [1, 2, 3]
a.insert(0, 4)
print( a ) | false |
983e97e23d554be430a04e97f3e0c2bf4535c227 | az1115/ultimate-python | /ultimatepython/conditional.py | 815 | 4.15625 | 4 | def main():
x = 1
x_add_two = x + 2
# This condition is obviously true
if x_add_two == 3:
print("math wins") # ran
# A negated condition can also be true
if not x_add_two == 1:
print("math wins here too") # ran
# There are else statements as well, which get run
# if the initial condition fails
if x_add_two == 1:
print("math lost here...")
else:
print("math wins otherwise") # ran
# Or they get run once every other condition fails
if x_add_two == 1:
print("nope not this one...")
elif x_add_two == 2:
print("nope not this one either...")
elif x_add_two < 3 or x_add_two > 3:
print("nope not quite...")
else:
print("math wins finally") # ran
if __name__ == "__main__":
main()
| true |
577cba87b3c96cb212441ed9125651644ca05a88 | dmcdekker/cracking-the-coding-interview | /linked-lists/remove_dups.py | 2,083 | 4.1875 | 4 | class Node(object):
"""Node in a linked list."""
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return "<Node {data}>".format(data=self.data)
class LinkedList(object):
"""Linked List using head and tail."""
def __init__(self):
self.head = None
self.tail = None
def list_print(self):
node = self.head
while node:
print node.data
node = node.next
def add_node(self, data):
"""Add node with data to end of list."""
new_node = Node(data)
if self.head is None:
self.head = new_node
if self.tail is not None:
self.tail.next = new_node
self.tail = new_node
def remove_dups(ll):
# check if linked list exists
if not ll.head:
return
# current is head
current = ll.head
# set for easy lookup
seen = set([current.data])
# iterate through list; if already seen (dupe)
# make pointers point to next.next elem
# otherwise add to set if not dupe
while current.next:
if current.next.data in seen:
current.next = current.next.next
else:
seen.add(current.next.data)
current = current.next
return ll
# use auxilliary pointer to travel behind the linked list pointer
def remove_dups_followup(ll):
if not ll.head:
return
current = ll.head
while current:
aux = current
while aux.next:
if aux.next.data == current.data:
aux.next = aux.next.next
else:
aux = aux.next
current = current.next
return ll
#----with buffer-----
ll = LinkedList()
ll.add_node(100)
ll.add_node(20)
ll.add_node(10)
ll.add_node(100)
remove_dups(ll)
print '______remove_dups______'
ll.list_print()
#----without buffer-----
ll = LinkedList()
ll.add_node(300)
ll.add_node(20)
ll.add_node(300)
ll.add_node(10)
remove_dups_followup(ll)
print '______remove_dups_followup______'
ll.list_print()
# print(ll)
| true |
d782984933ca04368dba9069848570baa158201d | AchaRhaah/Cipher-text- | /main.py | 834 | 4.21875 | 4 | alphabet = ['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']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
if direction =='encode':
def encrypt(plain_text,shift):
encrypted_word=""
for letter in text:
letter_position=alphabet.index(letter)
encrypted_word+=alphabet[letter_position+shift]
print(encrypted_word)
encrypt(plain_text=text,shift=shift)
else:
def decrypt(plain_text,shift):
decrypted_word=""
for letter in text:
letter_position=alphabet.index(letter)
decrypted_word+=alphabet[letter_position-shift]
print(decrypted_word)
decrypt(plain_text=text,shift=shift)
| false |
ea9814788ade7185116c2cc1293d9381edde6162 | Ngomes1/tip_calculator | /#tip_calculator.py | 1,795 | 4.46875 | 4 | # Tip_calulator
# 1) In the line below I will add variables that will prompt user inputs.
# 2) Everything is a float because dividing ints. may lead to decimal places so floats work best for both.
num_people = float(input("Welcome, how many people ate with you?: "))
cost_of_meals = float(input("How much did it all cost?: "))
# 3) The line below is showing those who use the app, what each person would owe splitting the bill evenly.
if num_people >= 1:
print(f"The cost person should be {cost_of_meals / num_people} person before tip and taxes.")
# Thus creating another variable that has the values of the cost before taxes and tip bellow will hold the same value stated above.
sum_per_person = cost_of_meals / num_people
# We will also set that variable so that it will not exceed 2 decimal places over making calculations easier.
round(sum_per_person, 2)
# New variable showing 'taxes' will show what tax would be for each person splitting the bill.
# Where total will equal each persons true total
tax = sum_per_person * 0.1
total = tax + sum_per_person
# Rounding the total to 2 decimal places to ensure easier calculations when it comes to tips.
round(total, 2)
print(f"After taxes the total is {total}$ per person.")
# The line below will run how much each person is willing to tip depending on how many people are inputed.
# The 'total_cost_each' variable carries what each person will want to tip and add it to how much the bill costs each of the individuals that were inputed.
for tip in range(int(num_people)) :
tip = input("How much would you each like to tip? (Please insert a decimal equivalent of percentage.): ")
total_cost_each = (total * float(tip)) + total
print(f"{round(total_cost_each, 2)}$ is how much you owe!")
| true |
55920c694144166ad301aaf50178969c7653d7c1 | pauloMateos95/python_basico | /ejemplos.py | 2,163 | 4.15625 | 4 | # -----------------------
# Cambiar tipo de dato
# -----------------------
n = 5
print(type(n))
n_string = str(n)
print(type(n_string))
print(float(n))
# -------------------------------------
# Operadores lógicos y de comparasión
# -------------------------------------
studies = True
works = False
print(studies and works)
print(studies or works)
print(not studies)
print(not works)
n1 = 5
n2 = 5
n3 = 7
print(n1 == n2)
print(n1 == n3)
print(n1 != n2)
print(n1 != n3)
print(n1 < n2)
print(n1 <= n2)
# ---------------------------
# Funciones y condicionales
# ---------------------------
def par(n):
if n % 2 == 0:
return True
else:
return False
def half(n):
if par(n):
result = int(n / 2)
return result
elif n == 11:
return 'Ok'
else:
return "It's not a pair number"
print(half(10))
print(half(13))
# ----------
# Ciclos
# ----------
def loop(n):
for i in range(1, n + 1):
print(i)
def times_two(l):
l_times_two = []
for i in l:
if i % 2 == 0:
l_times_two.append(i)
return l_times_two
def loop2(n):
n2 = 0
while n2 < n:
print(n2 + 1)
n2 += 1
l = [1, 4, 6, 3, 7, 39, 16, 4, 2]
loop(20)
print(times_two(l))
loop2(20)
# --------------
# Diccionarios
# --------------
my_dictionary = {
'llave1': 1,
'llave2': 2,
'llave3': 3,
}
print(my_dictionary)
print(my_dictionary['llave2'])
country_poblation = {
'Argentina': 44938712,
'Brasil': 210147125,
'Colombia': 50372424,
}
print(f"La población de brasil es de {country_poblation['Brasil']} habitantes")
for country in country_poblation.keys():
print(country)
for poblation in country_poblation.values():
print(poblation)
for country, poblation in country_poblation.items():
print(f"La población de {country} es de {poblation} habitantes")
# ------------------------
# función con condiciones
# ------------------------
def ejemplo():
n = input('Que quieres hacer? ')
if n == 'suma':
return print('suma')
if n == 'resta':
return print('resta')
print('escoge entre suma o resta')
ejemplo() | false |
d4c91a0ec110811969748283cda587e551b37fa6 | gustavohsr/python | /sem7/sem7-exe2.py | 658 | 4.15625 | 4 | def retangulo(largura,altura):
#print("Criando Retangulo")
x = 1
while x <= altura:
#y = 1
#while y <= largura:
if x == 1 or x == altura: # para preencher a primeira e a ultima linha
y = 1
while y <= largura:
print("#",end='')
y = y + 1
print()
else:
z = 1
print("#",end='')
while z < largura-1:
print(" ",end='')
z = z + 1
print("#")
x = x + 1
largura = int(input("Informe a largura: "))
altura = int(input("Informe a altura: "))
retangulo(largura,altura) | false |
970264157e9cca2cd98f2e2e603bf515cf1c15ec | nuga99/daily-coding-problem | /Problem 16/solve.py | 1,232 | 4.21875 | 4 | #!/usr/bin/python
'''
Good morning! Here's your coding interview problem for today.
This problem was asked by Twitter.
You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API:
record(order_id): adds the order_id to the log
get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N.
You should be as efficient with time and space as possible.
Upgrade to premium and get in-depth solutions to every problem. Since you were referred by one of our affiliates, you'll get a 10% discount on checkout!
If you liked this problem, feel free to forward it along so they can subscribe here! As always, shoot us an email if there's anything we can help with!
'''
recordId = {}
def solve(order_id,i):
record(order_id)
get_last(i)
# using set
def record(order_id_list):
orderBuy = 0
for orderBuy,order_id in enumerate(order_id_list):
recordId[orderBuy] = order_id.rstrip() # remove trailing whitespace and tabs \n \t
def get_last(i):
print recordId.get(i,"There's no id")
if __name__ == "__main__":
logsRecord = open('logs.txt','r')
solve(logsRecord,11) | true |
24eae50330da3ddd5fb34b567cbdc81e307d2cad | vitaliytsoy/problem_solving | /python/easy/intersections.py | 1,440 | 4.15625 | 4 | """
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
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]
Explanation: [4,9] is also accepted.
"""
from typing import List
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1).intersection(set(nums2)))
def intersection_manual(self, nums1: List[int], nums2: List[int]) -> List[int]:
unique_nums_1= set(nums1)
unique_nums_2= set(nums2)
dict = {}
for i in range(0, max(len(unique_nums_1), len(unique_nums_2))):
if (len(unique_nums_1) > 0):
value = unique_nums_1.pop()
if value not in dict:
dict[value] = 1
else:
dict[value] += 1
if (len(unique_nums_2) > 0):
value = unique_nums_2.pop()
if value not in dict:
dict[value] = 1
else:
dict[value] += 1
result = []
for key, value in dict.items():
if (value > 1):
result.append(key)
return result
solution = Solution()
print(solution.intersection_manual([1,2,2,1,5], [2,2]))
| true |
54561d6e46dd5db066b0c692cb86adca518427fc | vitaliytsoy/problem_solving | /python/medium/next_right_pointer.py | 2,843 | 4.15625 | 4 | """
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = []
Output: []
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
from typing import Optional, List
from collections import deque
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if root == None:
return None
root.next = None
if (root.left and root.right):
self.connect_nodes(self.link_nodes_list([root.left]), self.link_nodes_list([root.right]))
root.left.next = root.right
root.right.next = None
return root
def connect_nodes(self, l_nodes: List['Optional[Node]'], r_nodes: List['Optional[Node]']):
if len(l_nodes) == 0 and len(r_nodes) == 0:
return
l_children = self.link_nodes_list(l_nodes)
r_children = self.link_nodes_list(r_nodes)
l_nodes[-1].next = r_nodes[0]
self.connect_nodes(l_children, r_children)
def link_nodes_list(self, nodes: List['Optional[Node]']):
pointer = 0
children = []
while pointer < len(nodes) - 1:
current_node = nodes[pointer]
next_node = nodes[pointer + 1] if (pointer + 1) < len(nodes) else None
current_node.next = next_node
if current_node.left:
children.append(current_node.left)
if current_node.right:
children.append(current_node.right)
pointer += 1
return children
# queue = deque([root])
# root.next = None
# while (queue):
# node = queue.popleft()
# if (node.left):
# node.left.next = node.right
| true |
ea79255203f7bee587629f463becd22d252e82d6 | vitaliytsoy/problem_solving | /python/medium/subsets_bitwise.py | 895 | 4.125 | 4 | """
Given an integer array nums of unique elements, return all possible
subsets(the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
"""
from typing import List
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
result = []
for i in range(2**n):
subset = []
for j in range(n):
print(f"i {i} j {j} shift {1 << j} num {i & (1 << j)}")
if i & (1 << j):
print(nums[j])
subset.append(nums[j])
print(subset)
result.append(subset)
return result
s = Solution()
print(s.subsets([1,2,3,4]))
| true |
338632b2ea8bc771b6831c7056ec217055effd10 | vitaliytsoy/problem_solving | /python/medium/group_anagrams.py | 919 | 4.3125 | 4 | """
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
"""
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict = {};
for word in strs:
normalized_key = ''.join(sorted(list(word)))
if normalized_key not in dict:
dict[normalized_key] = [word]
else:
dict[normalized_key].append(word)
return dict.values()
solution = Solution()
solution.groupAnagrams(["eat","tea","tan","ate","nat","bat"]) | true |
917d2c675d163fb6f085f0e6c69c58d39bb3d426 | dcarlin/Advent-of-Code-Challenge | /Advent of Code/Day 2/Day2Part1.py | 1,541 | 4.15625 | 4 | '''
--- Day 2: Corruption Checksum ---
As you walk through the door, a glowing humanoid shape yells in your direction. "You there! Your state appears to be idle. Come help us repair the corruption in this spreadsheet - if we take another millisecond, we'll have to display an hourglass cursor!"
The spreadsheet consists of rows of apparently-random numbers. To make sure the recovery process is on the right track, they need you to calculate the spreadsheet's checksum. For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences.
For example, given the following spreadsheet:
5 1 9 5
7 5 3
2 4 6 8
The first row's largest and smallest values are 9 and 1, and their difference is 8.
The second row's largest and smallest values are 7 and 3, and their difference is 4.
The third row's difference is 6.
In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18.
What is the checksum for the spreadsheet in your puzzle input?
Your puzzle answer was 46402.
'''
#CODE STARTS HERE.
#PART 1
file = open('DayTwoInput.txt', 'r')
rows = list(file)
checksum = 0
output = 0
large = 0
small = 0
for x in range(0, len(rows)):
values = rows[x].split('\t')
for value in values:
value = int(value)
if large < value:
large = value
if small == 0 or small > value:
small = value
checksum += (large - small)
small = 0
large = 0
print(checksum)
| true |
004b042ab39c96ab2f9d950059494977446fa917 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-3/exercicio3-6.py | 759 | 4.28125 | 4 | # Exercício 3.6 - Escreva uma expressão que será utilizada para decidir se um aluno foi
# ou não aprovado. Para ser aprovado, todas as médias do aluno devem ser maiores
# que 7. Considere que o aluno cursa apenas três matérias, e que a nota de cada uma
# está armazenada nas seguintes variáveis: matéria1, matéria2 e matéria3
print('\n')
materia1 = float(input('Informe a média da matéria 1: '))
materia2 = float(input('Informe a média da matéria 2: '))
materia3 = float(input('Informe a média da matéria 3: '))
print('\n')
if(materia1 >= 7 and materia2 >= 7 and materia3 >= 7):
print('Parabéns! O aluno foi aprovado em todas as matérias.')
else:
print('Ops! O aluno não foi aprovado em todas as matérias.')
print('\n')
| false |
8caf1d3569c3b978107e2792de81ec03db4e2108 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-5/exercicio5-27.py | 489 | 4.15625 | 4 | # Exercício 5.27 - Escreva um programa que verifique se um número é palíndromo.
# Um número é palíndromo se continua o mesmo caso seus dígitos sejam invertidos.
# Exemplos: 454, 10501.
numero = input('\nVerifique se um número é palíndromo: ')
numeros = list(numero)
palindromo = list(numero)
palindromo.reverse()
if numeros == palindromo:
print('\nO número %d é um palíndromo.\n' % int(numero))
else:
print('\nO número %d não é um palíndromo.\n' % int(numero)) | false |
e2dcd6d9dba252af11a9e2264ed43f9f90c6e420 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-5/exercicio5-26.py | 529 | 4.15625 | 4 | # Exercício 5.26 - Escreva um programa que calcule o resto da divisão inteira entre dois
# números. Utilize apenas as operações de soma e subtração para calcular o resultado.
n1 = int(input('\nInforme um número inteiro: '))
n2 = int(input('Informe outro número inteiro: '))
if n2 == 0:
print('\nERRO! Não se pode dividir um número por zero.\n')
else:
while n1 > 0:
n1 -= n2
if n1 <= 0:
resto = 0 - n1
print('\nResto da divisão igual a %d\n' % resto) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.