blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
86db1638b89afc2fd09b5e88c132277b52fc5e89 | kingfuzhu/Python-Foundation | /Python基础/迭代器.py | 1,319 | 4.1875 | 4 | #iterator: an object that can remember the position of traverse.
iter() #create an iterator
next() #return the next event of iterator
list = [1,2,3,4]
it = iter(list)
for i in range(10):
x = next(it,'No default value')
print(x)
#builder: builder is a function of returning iterators.
import sys
def fib(n):
a,b,con = 0,1,0
while True:
if (con > n ):
return
yield a,b
a,b = b,b+a
con += 1
f = fib(10)
while True:
try:
print(next(f))
except StopAsyncIteration:
sys.exit()
#recursion: in the process of invoking function, directly or indirectly invoke the function itself.
def fun():
return fun()
def facto(n):
if n == 1:
return 1
return n * facto(n - 1)
facto(5)
#5*fact(4)-->5*4*fact(3)-->5*4*3*fact(2)-->5*4*3*2*fact(1)-->5*4*3*2*1
print(facto(5));
def func(y):
print (y) #10 5 2.5 1.25
if y/2 > 1:
rep = func(y/2) #
print('last recurring value:',y)
return y
func(10)
def num(i):
print(i)
if i/2 > 1:
print(i/2)
if i/4 > 1:
print(i/4)
if i/8 > 1:
print(i/8)
print('last recursion:',i/8)
print('last recursion:',i/4)
print('last recursion:',i/2)
print('last recursion:',i)
num(10) | true |
4f0ba89f43cbded3e11b5d5b15a786e918bfedee | 5afs/CSE | /notes/Delaney Kelly - Challenges.py | 2,167 | 4.1875 | 4 | def challenge1(first_name, last_name): # Write name backwards
print(last_name, first_name)
challenge1("Delaney", "Kelly")
def challenge2(digit): # Tell if number is even or odd
if digit % 2 ==0:
print("%d is even." % digit)
else:
print("%d is odd." % digit)
challenge2(7)
def challenge3(base, height): # Calculate area of triangle
area = (base * height) / 2
print("If the base of a triangle is %d and the height is %d, then the area is approximately %d"
% (base, height, area))
challenge3(3, 7)
def challenge4(number1): # Tell if number is positive, negative, or 0
if number1 > 0:
print("%d is positive." % number1)
elif number1 < 0:
print("%d is not positive." % number1)
else:
print("%d is zero." % number1)
challenge4(1.78)
def challenge5(radius): # Find area of circle w/ radius
area = 3.14*radius**2
print("If the radius is %d, the area is %d." % (radius, area))
challenge5(4)
def challenge6(radius): # volume of a sphere
volume = (4/3) * 3.14 * radius**3
print("If the radius of a sphere is %d, then the volume is approximately %d" % (radius, volume))
challenge6(7)
def challenge7(n): # Accepts an integer (n) and computes the value of n+nn+nnn
n = n + n**2 + n**3
print(n)
challenge7(2)
def challenge8(number): # Tell if a number is w/in 150 of 2000 or 3000
if 1850 <= number <= 2150:
print("The number is within 150 of 2000. ")
elif 2850 <= number <= 3150:
print("The number is within 150 of 3000. ")
else:
print("The number is not within 150 of 2000 or 3000. ")
challenge8(2130)
def challenge9(letter): # Tell if a letter is a vowel
vowels = ["a", "e", "i", "o", "u", "y"]
if letter == vowels:
print("%s is a vowel." % letter)
else:
print("%s is not a vowel." % letter)
challenge9("t")
def challenge10(string): # Tell if a string is numeric
if string == str(string):
print("%s is not a number." % string)
elif string == int(string):
print("%s is a number." % string)
challenge10("Cat")
| true |
e85081bfcae08145a2a393931ca04aa64b9395d6 | Yogesh-3/Mind-refreshers | /Calculator.py | 669 | 4.125 | 4 | def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
def mod(num1, num2):
return num1 % num2
num1 = int(input("Enter first number: "))
operation = input("specify operation(+, -, *, /, %):")
num2 = int(input("Enter second number: "))
result = 0
if operation == '+':
result = add(num1,num2)
elif operation == '-':
result = sub(num1,num2)
elif operation == '*':
result = mul(num1,num2)
elif operation == '/':
result = div(num1,num2)
elif operation == '%':
result = mod(num1,num2)
else:
print("Please enter: +, -, *, / or %")
print(result)
| false |
9f4636c987c12debaea5785423842726030291b0 | johncmk/Python | /Divide_and_Conquer/shortest.py | 1,900 | 4.15625 | 4 | '''
Shortest Path
@author: John
'''
'''Tree class'''
class Tree:
__slots__ = "root, left, right".split()
def __init__(self, root, left = None, right = None):
self.root = root
self.left = left
self.right = right
'''If Tree has no child return T else F'''
def empty(self):
return True if self.left is None and self.right is None else False
'''Get root value of the tree'''
def getRoot(self):
return self.root
'''Print tree in Pre-order'''
def printTree(t, tab = 0):
if t is None:
return
print tab*'\t', t.getRoot()
printTree(t.left,tab+1)
printTree(t.right,tab+1)
'''Solution a: using 2 recursions to find the two nodes, and compare their paths to root'''
'''Find the LCA(Lowest Common Ancestor) of the BST'''
def findLCA(t,a,b,):
if t is None:
return t
elif t.root > a and t.root > b:
return findLCA(t.left,a,b)
elif t.root < a and t.root < b:
return findLCA(t.right,a,b)
return shortestPath(t,a,b)
'''ShortestPath using LCA send pointer to left and right side'''
def shortestPath(t,left,right):
if left > right:
left,right = right,left
l,r = 0,0
if t.root == left and t.root == right:
return 0
elif t.root == left:
return l + findTarget(t.right,right)
elif t.root == right:
return findTarget(t.left,left) + r
return findTarget(t.left,left) + findTarget(t.right,right)
'''locate the node in BST'''
def findTarget(t,target,length = 1):
if t.root == target:
return length
length+=1
if t.root > target:
return findTarget(t.left,target,length)
return findTarget(t.right,target,length)
'''Solution b: using one recursion'''
t = Tree(5,Tree(3,Tree(2)),Tree(7,Tree(6),Tree(8)))
printTree(t)
print "Shortest Path value from 5 to 3 is ",findLCA(t,5,3)
| true |
e90680468d88e87222e3f35444f7757a56a52393 | myielin/assembly-study | /recursion.py | 215 | 4.1875 | 4 | # this code recursively adds up every integer that comes before a given value
def rec(i, n):
if n == 0:
return i
else:
return i + rec(i + 1, n-1)
x = int(input("value: "))
print(rec(0, x))
| true |
47dcadf8fd2d178982299616bfbde68672bf96fa | VishwakarmaKomal/My-Python-programs | /Reverse_Vowel.py | 389 | 4.1875 | 4 | def reverse_vowel(str1):
vowels=""
for char in str1:
if char in "aeiouAEIOU":
vowels += char
result_string=""
for char in str1:
if char in "aeiouAEIOU":
result_string += vowels[-1]
vowels=vowels[:-1]
else:
result_string += char
return result_string
print(reverse_vowel("Komal"))
| false |
1bac2b0c74af14891e26942c99f7d207f436fa4a | Alogenesis/Basic-Python-Udemy | /05Ex01KilometersToMiles.py | 520 | 4.25 | 4 | '''Kilometers to Miles converter'''
mile = 1.609344
km = input("Please enter a number of Kilometers")
print(km, "Kilometers are eqaul", ((float(km))/mile), "Miles")
'''Tips'''
'''1. Force input'''
km = float(input("Please enter a number of Kilometers"))
result = km / mile
print(km, "Kilometers are eqaul", result , "Miles")
'''2. Force decimal with round function'''
km = float(input("Please enter a number of Kilometers"))
result = km / mile
print(km, "Kilometers are eqaul", round(result,4) , "Miles") | true |
2b45611ec9e3f985b1e8773da53bfbce81f632ce | nancy3457/selfteaching-python-camp | /exercises/1901090043/1001S02E03_calculator.py | 821 | 4.125 | 4 | def calculator():
num1 = input("输入一个数:")
num1 = num1.strip()
num1 = float(num1)
yunsuanfu = input("输入运算符:")
yunsuanfu = yunsuanfu.strip()
num2 = input("输入另外一个数:")
num2 = num2.strip()
num2 = float(num2)
if yunsuanfu == '+':
num3 = num1 + num2
print("结果是:",num3)
elif yunsuanfu == "-":
num3 = num1 - num2
print("结果是:",num3)
elif yunsuanfu == "*":
num3 = num1 * num2
print("结果是:",num3)
elif yunsuanfu == "/":
num3 = num1 / num2
print("结果是:",num3)
else:
print("输入有误!")
calculator()
| false |
464caed9ab45d970dee02e1e2312632ca94864ee | jackie-may/tech_academy_python_projects | /nice_or_mean_video.py | 902 | 4.125 | 4 | #template:
#PYTHON: 3.9.1
#
#AUTHOR: Jackie May
#
#PURPOSE: The Tech Academy - Python Course, Creating our first program
# together.Demonstrating how to pass variables from function
# to function while producing a functional game.
#
# Remember, function_name(variable) _means that we pass in
# the variable. Return variable _means that we are returning
# the variable back to the calling function.
def start(): # start() contains the variables
f_name = "Sarah" # use names that describe what the variable is
l_name = "Connor"
age = 28
gender = "Female"
get_info(f_name,l_name,age,gender)
def get_info(f_name,l_name,age,gender):
print("My name is {0} {1}. I am a {2} year old {3}.".format(f_name,l_name,age,gender))
if __name__ == "__main__":
start()
| true |
a0a15bcb1fe0f944b79f327a53d198a353eef78b | ValentinaArokiya/python-basics | /while_loop.py | 491 | 4.59375 | 5 | # number of times to iterate is not known
# continues to execute a block of code while some condition remains true.
# while some_boolean_condition:
# do something
# a for loop will pick every element in the list automatically and continues the next iteration. No need to increment.
# a while loop needs to be incremented inorder to continue with the next iteration.
x=0
while x < 5:
print(f"The current value of x is {x}")
x = x+1
else:
print("X is not less than 5")
| true |
1db16778f12701557b2c28a559a7c84c35509a49 | ValentinaArokiya/python-basics | /scope_1.py | 824 | 4.59375 | 5 | # #Example-1:
#
# x = 50
#
# def func(x):
# print(f'X is {x}')
#
# func(x)
#
# #Example-2:
#
# x = 50
#
# def func(x):
# print(f'X is {x}')
#
# x = 200
# print(f'I just locally changed X to {x}')
#
# func(x)
#
# print(x)
#Example-3: the value of x which is defined outside the function can be changed, using the global keyword
x = 50
def func():
global x # grab the value of the global x, and do whatever changes you want to x.
print(f'X is {x}') # just print the value of x.
x = 200 # assign a new value to the variable x. Local reassignment on a global variable
print(f'I just locally changed X to {x}')
print(x) # this will print the original value of x, since the value isnt changed yet.
func()
print(x) # this will print the new value of x, that got changed by the function.
| true |
3b12a5d2f6b78f7edc0df6ac558c6284ec774c09 | ValentinaArokiya/python-basics | /range.py | 467 | 4.375 | 4 | # range - is a generator. It generates some sort of information, instead of saving all the information to memory. More efficient system.
# range - does not include the end number
print("Range")
for num in range(10):
print(num)
print("Start-Stop")
for num in range(3,10):
print(num)
print("Start-Stop-Step")
for num in range(3,10,2):
print(num)
print("To print the elements of a range, it has to be casted to a list.")
print(list(range(0,11,2)))
| true |
95995efe1fd13b04637bdef3642370b837f5776f | ValentinaArokiya/python-basics | /object_oriented_3.py | 516 | 4.25 | 4 |
class Circle:
#Class Object Attribute
pi = 3.14
def __init__(self, radius=1):
self.radius = radius
# Method:
def area(self):
print(self.pi * (self.radius**2))
def get_circumference(self):
return self.pi * self.radius * 2
# self.pi can also be referenced as Circle.pi - since it is a Class Attribute.
my_circle = Circle(4)
print(my_circle.radius)
print(my_circle.pi)
(my_circle.area())
print(my_circle.get_circumference())
print(Circle.pi)
print(my_circle)
| true |
d334e72cf9763a4bf4088a89723b35fc00feb514 | ValentinaArokiya/python-basics | /dict_1.py | 743 | 4.3125 | 4 | # unordered and cannot be sorted
# has key-value pairs
# list - are retrieved by location. So can use index and slicing.
prices_lookup = {'apple' : 2.99, 'grapes' : 4.99, 'orange' : 3.05}
print(prices_lookup['grapes']) # instead of passing the index position, we pass in the key itself.
print(prices_lookup)
d = {'k1': 123, 'k2': 456, 'k3': {'key1': 100}, 'k4': 'c'}
print(d['k2'])
print(d['k3'])
print(d['k3']['key1'])
# (d['k4'][0]).upper()
# print(d)
e = {'k1': 100, 'k2': 200, 'k3' : 300}
print(e)
e['k7'] = 700 # adding key value pair to existing dictionary
print(e)
e['k1'] = 1000 # modifying the existing value of a key
print(e)
print(e.keys())
print(e.values())
print(e.items()) # result will be in the form of tuples
| true |
2bdbfe271b22e580a49d8b9b3bce1d7ae6721466 | kisyular/speedDistance | /proj01.py | 2,965 | 4.3125 | 4 | #
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 23:34:06 2015
@author: kisyular
"""
###########################################################################
#Algorithm
# Prompt the user for values of speed and distance
# display results of entered inputs by the user
# display results of calculations for hare and tortoise
# show the results of the final calculations
###########################################################################
import math
# Prompt the user for values of speed and distance
total_distance=input ("the distance to finish line(in miles)")
speed_of_tortoise=input ("the speed of the tortoise (in inches per minute)")
speed_of_hare=input ("the speed of the hare (in miles per hour)")
time_hare_rest=input ("the time that the hare rests after running (in minutes)")
time_the_hare_runs=input ("the time that the hare runs before resting (in minutes)")
# display results of entered
print( )
print( "The distance is", total_distance, )
print( "the speed of tortoise is", speed_of_tortoise, )
print( "the speed of hare is", speed_of_hare, )
print( "the time the hare rests is", time_hare_rest, )
print( "the time the hare runs before resting is", time_the_hare_runs, )
# display results of calculations for hare and tortoise
total_distance_float = float( total_distance )
speed_of_tortoise_float = float( speed_of_tortoise )
speed_of_hare_float = float( speed_of_hare )
time_hare_rest_float = float( time_hare_rest )
time_the_hare_runs_float = float( time_the_hare_runs )
print( "The ceiling of", total_distance_float, "is", math.ceil( total_distance_float) )
print( "The floor of", total_distance_float, "is", math.floor( total_distance_float ) )
speed_of_tortoise_in_miles = (speed_of_tortoise_float * 0.00094696969)
print( "the speed of tortoise", speed_of_tortoise_in_miles, )
# show the results of the final calculations
speed_of_tortoise_in_miles_float = float(speed_of_tortoise_in_miles)
print( "the total time the tortoise takes in hours is", total_distance_float/speed_of_tortoise_in_miles_float)
time_hare_takes_no_rest = (total_distance_float / speed_of_hare_float)
remaining_distance = (total_distance_float % speed_of_hare_float)
print("the combined time hare takes without resting is",total_distance_float / speed_of_hare_float)
print("the remaining distance is",total_distance_float % speed_of_hare_float)
time_hare_takes_no_rest_float = float( time_hare_takes_no_rest )
time_hare_takes_no_rest_float= (total_distance_float / speed_of_hare_float)
number_of_time_hare_runs = (math.ceil((time_hare_takes_no_rest_float)/(time_the_hare_runs_float/60))-1)
number_of_time_hare_runs_float = float(number_of_time_hare_runs)
time_hare_takes_to_finish =(time_hare_takes_no_rest_float)+(number_of_time_hare_runs_float*(time_hare_rest_float/60))
time_hare_takes_to_finish_float = float(time_hare_takes_to_finish)
print("the total time the hare takes in hours is", time_hare_takes_to_finish_float) | true |
dce2c9e983a92725e8e773680abc897ee26dd6d1 | vijayakumarr345/pattern | /Alphabets/Capital Alphabets/U.py | 690 | 4.25 | 4 | # Capital Alphabet U using Function
def for_U():
""" *'s printed in the Shape of Capital U """
for row in range(9):
for col in range(7):
if row !=8 and col %6 ==0 or row ==8 and col %6 !=0:
print('*',end=' ')
else:
print(' ',end=' ')
print()
def while_U():
""" *'s printed in the Shape of Capital U """
row =0
while row <9:
col =0
while col <7:
if row !=8 and col %6 ==0 or row ==8 and col %6 !=0:
print('*',end=' ')
else:
print(' ',end=' ')
col+=1
print()
row +=1
| false |
c9643ed2221f70bc5ef89e7020f68b4a82eef5f0 | vijayakumarr345/pattern | /Numbers/six.py | 764 | 4.34375 | 4 | # Shape of number 6 using functions
def for_6():
""" *'s printed in the shape of number 6 """
for row in range(9):
for col in range(5):
if col ==0 and row%8 !=0 or row%4 ==0 and col%4 !=0 or col ==4 and row not in (0,2,3,4,8):
print('*',end=' ')
else:
print(' ',end=' ')
print()
def while_6():
""" *'s printed in the shape of number 6 """
row =0
while row<9:
col =0
while col <5:
if col ==0 and row%8 !=0 or row%4 ==0 and col%4 !=0 or col ==4 and row not in (0,2,3,4,8):
print('*',end=' ')
else:
print(' ',end=' ')
col+=1
print()
row += 1
| false |
6e88cb7001b40fec4807eac019de80c2a699a6f5 | vijayakumarr345/pattern | /Alphabets/Small Alphabets/j.py | 742 | 4.1875 | 4 | # Small alphabet j using function
def for_j():
""" *'s printed in the Shape of small j """
for row in range(9):
for col in range(4):
if col == 2 and row not in (1,8) or col ==1 and row in (2,8) or col ==0 and row ==7:
print('*',end=' ')
else:
print(' ',end=' ')
print()
def while_j():
""" *'s printed in the Shape of Small j """
row =0
while row <9:
col =0
while col <4:
if col == 2 and row not in (1,8) or col ==1 and row in (2,8) or col ==0 and row ==7:
print('*',end=' ')
else:
print(' ',end=' ')
col+=1
print()
row +=1
| false |
1b4bffb72bdaec04f50ef609b82f854f99f43401 | SuxPorT/python-exercises | /Mundo 3 - Estruturas Compostas/Desafio #075.py | 935 | 4.28125 | 4 | # Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
# A) Quantas vezes apareceram o valor 9.
# B) Em que posição foi digitado o primeiro valor 3.
# C) Quais foram os números pares.
print("===" * 10)
numeros = (int(input('Digite o 1° valor: ')),
int(input('Digite o 2° valor: ')),
int(input('Digite o 3° valor: ')),
int(input('Digite o 4° valor: ')))
print("===" * 10)
print(f"Você digitou os valores {numeros}.")
print("===" * 10)
if 9 in numeros:
print(f"N° de vezes que apareceu o 9: {numeros.count(9)}.")
else:
print("O número 9 não foi digitado.")
if 3 in numeros:
print(f"Posição do primeiro 3: {numeros.index(3) + 1}.")
else:
print("O valor 3 não foi digitado.")
print("Valores pares: ", end="")
for valor in numeros:
if valor % 2 == 0:
print(f"{valor}", end=" ")
print("")
print("===" * 10)
| false |
24e505d86413f79d87494de7417c816b850f007f | SuxPorT/python-exercises | /Mundo 1 - Fundamentos/Desafio #004.py | 638 | 4.21875 | 4 | # Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis
# sobre ele.
texto = input("Escreva algo: ")
print("Qual é o tipo primitivo?\033[1;33m", type(texto))
print("\033[mÉ um número?\033[1;33m", texto.isnumeric())
print("\033[mÉ um texo?\033[1;33m", texto.isalpha())
print("\033[mPossui letra(s) ou número(s)?\033[1;33m", texto.isalnum())
print("\033[mTodas as letras estão em maiúsculo?\033[1;33m", texto.isupper())
print("\033[mTodas as letras estão em minúsculo?\033[1;33m", texto.islower())
print("\033[mPossui apenas espaços?\033[1;33m", texto.isspace())
| false |
a17b3d7236323c594c7447bac2b9376214dc24fa | SuxPorT/python-exercises | /Mundo 2 - Estruturas de Controle/Desafio #058.py | 1,079 | 4.15625 | 4 | # Melhore o jogo do Desafio #028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai
# tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.
from random import randint
from time import sleep
computador = randint(0, 10)
total = 0
acerto = False
print("Estou pensando em um número de 0 a 10. Tente adivinhar... ")
sleep(1.5)
print("===" * 20)
escolha = int(input("Terminei! Qual número eu escolhi? "))
print("===" * 20)
print("{:^60}".format("PROCESSANDO..."))
print("===" * 20)
sleep(2)
while not acerto:
if escolha == computador:
print("Você acertou! Foram necessários {} palpites".format(total + 1))
acerto = True
else:
total += 1
if escolha > computador:
escolha = int(input("Você errou! Tente um número menor: "))
print('===' * 20)
sleep(1)
if escolha < computador:
escolha = int(input("Você errou! Tente um número maior: "))
print("===" * 20)
sleep(1)
| false |
83d83e6b9f08a2ef9451f35792805acb973dfb29 | SuxPorT/python-exercises | /Mundo 2 - Estruturas de Controle/Desafio #059.py | 2,044 | 4.25 | 4 | # Crie um programa que leia dois valores e mostre um menu como o ao lado:
# [1] Somar [4] Novos números
# [2] Multiplicar [5] Sair do programa
# [3] Maior
# Seu programa deverá realizar a operação solicitada em cada caso.
numero1 = float(input("\033[1;30mPrimeiro valor: "))
numero2 = float(input("Seundo valor: "))
escolha = 0
while escolha != 7:
print("\033[1;30m===" * 12)
print("\033[1;33m[1] \033[1;34mSomar"
"\n\033[1;33m[2] \033[1;34mSubtrair"
"\n\033[1;33m[3] \033[1;34mMultiplicar"
"\n\033[1;33m[4] \033[1;34mDividir"
"\n\033[1;33m[5] \033[1;34mMaior"
"\n\033[1;33m[6] \033[1;34mNovos números"
"\n\033[1;33m[7] \033[1;34mSair do programa")
print("\033[1;30m===" * 12)
escolha = int(input("OPÇÃO: "))
print("===" * 12)
if escolha == 1:
print("A soma entre {} e {} é {}.".format(numero1, numero2, numero1 + numero2))
elif escolha == 2:
print("A diferença entre {} e {} é {}.".format(numero1, numero2, numero1 - numero2))
elif escolha == 3:
print("O resultado de {} x {} é {}.".format(numero1, numero2, numero1 * numero2))
elif escolha == 4:
print("A divisão entre {} {} é {}.".format(numero1, numero2, numero1 / numero2))
elif escolha == 5:
if numero1 > numero2:
print("Entre {} e {} o maior valor é {}.".format(numero1, numero2, numero1))
elif numero2 > numero1:
print("Entre {} e {} o maior valor é {}.".format(numero1, numero2, numero2))
else:
print("{} e {} são valores iguais.".format(numero1, numero2))
elif escolha == 6:
print("Informe os números novamente.")
print("===" * 12)
numero1 = float(input("Primeiro valor: "))
numero2 = float(input("Seundo valor: "))
elif escolha == 7:
print("\033[1;31m {:^35}".format("SAINDO DO PROGRAMA"))
print("\033[1;30m===" * 12)
else:
print("\033[1;31mOPÇÃO INVÁLIDA, TENTE NOVAMENTE\033[m")
| false |
6cc716bc17191d7472a79adc2b4151a5014de4f8 | SuxPorT/python-exercises | /Mundo 2 - Estruturas de Controle/Desafio #049.py | 298 | 4.28125 | 4 | # Refaça o Desafio #009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.
numero = int(input("Digite um número: "))
print("=" * 8, "TABUADA", "=" * 8)
for valor in range(1, 11):
print("{} x {} = {}".format(numero, valor, (numero * valor)))
| false |
6f4c6413b62361a0c6c10a8c2d08891510b7b146 | SuxPorT/python-exercises | /Mundo 1 - Fundamentos/Desafio #014.py | 267 | 4.375 | 4 | # Escreva um programa que converta uma teperatura digitada em °C e converta para °F
celsius = float(input("Informe a temperatura em °C: "))
fahrenheit = 1.8 * celsius + 32
print("A temperatura de {:.1f}°C corresponde a {:.1f}°F.".format(celsius, fahrenheit))
| false |
dd506ce2cc8ff07ac67bf6c04a7d61262835a4e7 | SuxPorT/python-exercises | /Mundo 2 - Estruturas de Controle/Desafio #063.py | 481 | 4.21875 | 4 | # Escreva um programa que leia um númreo numero inteiro qualquer e mostre na tela os numero primeiros termos de uma
# Sequência de Fibonacci.
# Ex.: 0 → 1 → 1 → 2 → 3 → 5 → 8
termo = int(input("Número de termos: "))
contador = 3
termo1 = 0
termo2 = 1
print("{} → {}".format(termo1, termo2), end=" ")
while contador <= termo:
termo3 = termo1 + termo2
termo1 = termo2
termo2 = termo3
print(" → {}".format(termo2), end=" ")
contador += 1
| false |
3886d91aacdc37a662d46649a2a8e887c2f28c67 | addriango/curso-python | /POO/09.reto.py | 926 | 4.4375 | 4 | #crear un programa que pida introducir una direccion email por teclado
#el programa debe imprimir por consola si la direccion de email es correcta
# o no en funcion de si esta tiene el simbolo "@". Si tiene un arroba la direccion
#sera correcta.Si tiene mas de una o ninguna "@" sera erronea
# sila "@" esta al comienzo de la direccion email tambien sera erronea
email=input("Introduce tu Email: ")
ultimocaracter=len(email)-1
veces=email.count("@")
posicion_arroba=email.find("@")
if veces==0 or veces>1 or posicion_arroba==0 or posicion_arroba==ultimocaracter:
print("El email es incorrecto")
else:
print("El email es correcto")
#solucion con metodos string
# mailUsuario=input("Introduce tu Email: ")
# arroba=mailUsuario.count("@")
# if arroba!=1 or mailUsuario.rfind("@")==(len(mailUsuario)-1) or mailUsuario.find("@")==0:
# print("Email incorrecto")
# else:
# print("Email Correcto")
| false |
6e2d5f0e45d8b10f89a4eb001d647c9e299448a9 | addriango/curso-python | /sintaxis-basica/07.tuplas.py | 685 | 4.25 | 4 | ## las tuplas son listas que no modemos modificar
## ni añadir ni eleminar ni editar items
## si permiten ver si un elemento esta en una tupla
miTupla = ("fredy","leon","mariana")
#convertir una tupla en lista
milista = list(miTupla)
#convertir una tupla en lista
milista = tuple(milista)
print("fredy" in miTupla) #devuelve True si el elemento esta en la tupla
print(miTupla.count("leon")9 #el metodo coun sirve pra saber cuantas veces esta un elemtno en una tupla
len(miTupla) # cuantos elementos tiene una tupla 0 lista
print(len(milista))
nuevatupla = ("frank",12,3,1995)
nombre, dia, mes, anio = nuevatupla #asigna cada valor de la tupla a cada variable respectivamente
| false |
434e18ba0837ae2a295f063fd1eff259ceba48f3 | irandijunior1903/SI---Monitoria | /EstruturaDeDecisão/ed9.py | 752 | 4.21875 | 4 | um = int(input("Digite um número: "))
dois = int(input("Digite outro número: "))
tres = int(input("Digite mais um número: "))
if um > dois and dois > tres:
print("A ordem descrescente é {}, {}, {}". format(um, dois, tres))
elif tres > dois and dois > um:
print("A ordem descrescente é {}, {}, {}". format(tres, dois, um))
elif um > tres and tres > dois:
print("A ordem descrescente é {}, {}, {}". format(um, tres, dois))
elif dois > tres and tres > um:
print("A ordem descrescente é {}, {}, {}". format(dois, tres, um))
elif tres > um and um > dois:
print("A ordem descrescente é {}, {}, {}". format(tres, um, dois))
else:
print("A ordem descrescente é {}, {}, {}". format(dois, um, tres))
print("FIM")
| false |
88b866a217871ef050d65892f30fcf1be8fdf6c8 | jeff-the-ma/helloAir | /fibonacci.py | 366 | 4.15625 | 4 | #! usr/bin/env python
# Fibonacci.py - A quick introduction to using generators **WOW**
from random import randint as r_Int
def fib():
a,b = 0,1
while 1:
yield a
a,b = b, a + b
** BEGIN CODE **
try:
g = fib()
for it in range(15):
next(g)
except Exception as e:
raise Exception('Exception Occurred when {}'.format(e))
| true |
c61bd12126c07ac006dc13d6d3c9491eb5b6945d | YousefbnK/python-foundations | /hr_pro.py | 1,948 | 4.1875 | 4 | from datetime import date
employees = []
managers = []
class Employee():
def __init__(self, name, age, salary, employment_year):
self.name = name
self.age = age
self.salary = salary
self.employment_year = employment_year
def get_working_years(self):
return date.today().year - self.employment_year
def __str__(self):
return "name: {}, Age: {}, Salary: {}, Working Years: {}".format(self.name, self.age, self.salary, self.get_working_years())
class Manager(Employee):
def __init__(self, name, age, salary, employment_year, bonus):
super().__init__(name, age, salary, employment_year)
self.bonus = bonus
def get_bonus(self):
return self.salary * self.bonus
def __str__(self):
return "Name: {}, Age: {}, Salary: {}, Working Years: {}, Bonus: {}".format(self.name, self.age, self.salary, self.get_working_years(), self.get_bonus())
options = ["Show Employees", "Show Managers", "Add an Employee", "Add a Manager", "Exit"]
print("Welcome to HR Pro 2019")
stop = "no"
while stop == "no":
print("Options:")
for i in options:
# print (options.index(i) +1, i)
print(f"{options.index(i) +1}. {i}")
user_input = int(input("What would you like to do? "))
if user_input == 1:
for facts in employees:
print(facts)
elif user_input == 2:
for facts in managers:
print(facts)
elif user_input == 3:
name = input("Name: ")
age = int(input("Age: "))
salary = int(input("Salary: "))
employment_year = int(input("Employment year: "))
employees.append(Employee(name, age, salary, employment_year))
print("Employee added successfully")
elif user_input == 4:
name = input("Name: ")
age = int(input("Age: "))
salary = int(input("Salary: "))
employment_year = int(input("Employment year: "))
bonus = float(input("Bonus Percentge: "))
managers.append(Manager(name, age, salary, employment_year, bonus))
print("Manager added successfully")
elif user_input == 5:
stop = "yes"
| false |
045abbef867c41f95596aa1215555b1b27505bd2 | CSA-ZMZ/Chapter12 | /longest_word.py | 1,234 | 4.59375 | 5 | #Zachary Zawaideh
#Computer Programming
#3/6/18
def longest_word():#Even though the task is complex the program is small enough for one function.
lists=[]#We need to have empty brackets in order to create a list if we need to.
long=""#We create an empty set of "" in order to have a len to use in an if statement later.
file=open("alice (3).txt","r")#The first step of action is to open the file.
read=file.readlines()#It is necessary to read the file lines.
for this in read:#We need to use a for loop to split the file script.
this=this.split()
for pencil in this:#This for loop is used to put the text into brackets and make it a list.
lists.append(pencil)#Puts the text into a list in the for loop.
for this in lists:#Runs through the script again, but this time it is using an if statment in the for loop.
if len(this)>len(long):#Uses length and a greater than statment to to find the longest word.
long=this#Sets long equal to this.
print("Longest word: "+long+"")#Prints the longest word in Alice and Wonderland.
print("Amount of characters: "+str(len(long))+" ")#Prints how many characters it has.
longest_word()#Starts the program
| true |
10909b06fae3738601f9921c5d17b3ee8fe53a2b | Santosh2205/python-scripts | /Files/Range.py | 564 | 4.34375 | 4 | ##syntax:range (start,stop,stop)
print(list(range(1,10)))
print(tuple(range(3,9)))
print(list(range(2,10,2)))
print(list(range(1,100,2)))
##write a program to capture any name from keyboard and perform the below oepations.
# if length of the string is less than 10.... string is too small
#is lenght of the string is greter than 30.. string is too big
name=input("enter any name :")
print(name)
print(name.__len__())
B=name.__len__()
print(B)
if B<10:
print("string is too small")
elif B>30:
print("String is too big")
'''_______________________'''
| true |
d025b1245f5ea31adab7a3bfcbf80b022bca1c6e | y43560681/y43560681-270201054 | /lab5/example2.py | 236 | 4.125 | 4 | x = int(input("How many numbers will you enter? "))
even = 0
odd = 0
for i in range(1, x+1):
a = int(input("Enter a number ="))
if a % 2 == 0:
even += 1
elif a % 2 == 1:
odd += 1
print((even / (even + odd)) * 100) | false |
285dc9f873d4b104a1cf81791b4ebc772070f25f | ttnguyen2203/code-problems-python | /string_permutation.py | 352 | 4.15625 | 4 | '''
Print all permutations of a string.
Difficulty: Easy
Solution notes:
O(n*n!) time
O(1) space
'''
def permutation(string, prefix = ''):
if len(string) == 0:
print prefix
else:
for s in string:
permutation(string[:string.index(s)]+string[string.index(s)+1:], prefix + s)
if __name__ == '__main__':
print string_permutation("abc", '') | true |
c131d5c6fdeda5197270075080d4ce555634f408 | ttnguyen2203/code-problems-python | /phone_number.py | 812 | 4.28125 | 4 | '''
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
(https://leetcode.com/problems/letter-combinations-of-a-phone-number/#_=_)
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Difficulty: Medium
'''
def phone_number(str):
if not str:
return []
res = [""]
mapping = {"1":[""], "2":['a', 'b', 'c'], "3":['d', 'e', 'f'], "4":['g', 'h', 'i'], "5":['j', 'k', 'l'], "6":['m', 'n', 'o'], "7":['p', 'q', 'r', 's'], "8":['t', 'u', 'v'], "9":['w', 'x', 'y', 'z']}
for s in str:
temp = []
for r in res:
for char in mapping[s]:
temp.append (r + char)
res = temp
return res
if __name__ == '__main__':
print phone_number("23")
| true |
a6145c948d5dceb8de012794709def9b1f715637 | ttnguyen2203/code-problems-python | /fb_interview_2017.py | 1,385 | 4.15625 | 4 | '''
Welcome to Facebook!
This is just a simple shared plaintext pad, with no execution capabilities.
When you know what language you'd like to use for your interview,
simply choose it from the dropdown in the top bar.
Enjoy your interview!
--------------------------------------------------------
Write a function that takes an input string and an alphabet, and returns the shortest substring of the input which contains every letter of the alphabet at least once.
Example:
Input: "aaccbc"
Alphabet: "abc"
Output: "accb"
--------------------------------------------------------
'''
output_arr = []
def pangram_solver(input_str, alphabet):
pangram_helper(input_str, alphabet)
print output_arr
sorted_arr = sorted(output_arr, key=len)
return sorted_arr[0]
def pangram_helper(input_str, alphabet):
if not input_str:
return None
alpha_dict = {}
for i in range(0, len(input_str)):
a = input_str[i]
if a in alphabet:
if a in alpha_dict.keys():
alpha_dict[a] += 1
else:
alpha_dict[a] = 1
if len(alpha_dict.keys()) == len(alphabet) and input_str not in output_arr:
output_arr.append(input_str)
pangram_helper(input_str[1:], alphabet)
pangram_helper(input_str[:-1], alphabet)
if __name__ == '__main__':
print pangram_solver("aaccbc", "abc")
| true |
01b9a1fa282bfd44b44504b5e044f1a6fa7bcc85 | ttnguyen2203/code-problems-python | /oddeven_linked_list.py | 792 | 4.28125 | 4 | '''
Given a singly linked list, group all odd nodes together followed by the even nodes.
Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
Difficult: Medium
'''
def odd_even(head):
if not head:
return None
if not head.next:
return head
odd = odd_start = head
even = even_start = head.next
while odd and even:
if even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
else:
even = even.next
odd.next = even_start
return odd
| true |
2c7508a65467e3ae55f240f985dc54bde284824f | ttnguyen2203/code-problems-python | /is_anagram.py | 795 | 4.15625 | 4 | '''
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Difficult: Easy
Solution Notes:
O(n) time
O(1) space
'''
def is_anagram(s,t):
letter_dict = {}
for letter in s:
if letter in letter_dict:
letter_dict[letter] = letter_dict[letter] + 1
else:
letter_dict[letter] = 1
for letter in t:
letter_dict[letter] = letter_dict[letter] - 1
for val in letter_dict.values():
if val != 0:
return False
return True
if __name__ == '__main__':
print is_anagram("anagram", "nagaram") | true |
9d7b2b3c8a43d760aedfd16310886042ee4b1192 | ttnguyen2203/code-problems-python | /capitalize.py | 354 | 4.28125 | 4 | '''
You are given a string . Your task is to capitalize each word of .
Input Format:
A single line of input containing the string, .
Constraints:
The string consists of alphanumeric characters and spaces.
Sample Input: hello world
Sample Output: Hello World
'''
def capitalize(string):
return ' '.join([word.capitalize() for word in string.split()]) | true |
11dadb80c367c4d7da358b845c1c4b75d29987b7 | rahulmourya336/Python3-for-dummies | /Practicals/12_largest_among_three_numbers.py | 332 | 4.15625 | 4 | #Practical 12: Largest among three numbers
value = [-1, 0, 1]
value[0] = input("Enter three numbers: ")
value[1] = input()
value[2] = input()
value[0] = int(value[0])
value[1] = int(value[1])
value[2] = int(value[2])
max = 0
for i in range(0, 3):
if(int(max) < value[i]):
max = value[i]
print("Max value is: ", max)
| true |
88b7d3e31b5a5fb57e64e1058bbec63ccfec6f11 | yousufAzadAyon/100-Days-of-Code | /04-Day-Four/rock-scissor-paper-001.py | 1,004 | 4.125 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
game_images = [rock, paper, scissors]
choice = int(input('what do you chose?\npress 0 for Rock, 1 for Paper, and 2 for Scissors\n:'))
random_choice = random.randint(0,2)
print(f'Your choice {game_images[choice]}\ncomputer choice{game_images[random_choice]}')
if choice == random_choice:
print('Its a tie!')
if choice >= 3 or choice < 0:
print("You typed an invalid number, you lose!")
elif choice == 0 and random_choice == 2:
print("You win!")
elif random_choice == 0 and choice == 2:
print("You lose")
elif random_choice > choice:
print("You lose")
elif choice > random_choice:
print("You win!")
elif random_choice == choice:
print("It's a draw") | false |
fb45276f129fcaff2b448da900c0835634d8101f | bpuderer/python-snippets | /general/slicing.py | 1,074 | 4.125 | 4 | # [start:stop:step]
s = "Monty Python's Flying Circus"
print("entire sequence:", s[:])
print("last element:", s[-1])
print("reversed:", s[::-1])
print("third to end:", s[2:])
print("last three:", s[-3:])
print("first three:", s[:3])
print("beginning until last three:", s[:-3])
print("ever other element:", s[::2])
print("third through fifth:", s[2:5])
# start and stop relative to direction
print("third through fifth reversed:", s[4:1:-1])
# naming slices
last_three_reversed = slice(None, -4, -1)
print("last three reversed:", s[last_three_reversed])
# slice assignment to insert
lst = ['and', 'completely', 'different']
lst[1:1] = ['now', 'for', 'something']
print(lst)
# remove adjacent items from list
lst = ['and', 'now', 'for', 'something',
'this', 'is', 'an', 'ex-parrot',
'completely', 'different']
del lst[4:8]
print(lst)
# replace adjacent items in list
lst = ['and', 'now', 'for', 'everything', 'somewhat', 'different']
lst[3:5] = ['something', 'completely']
print(lst)
# why end is excluded
print('Python'[:2], 'Python'[2:], sep='')
| false |
8f07f37c3ffc6bb950d0ce3c4638b60e1b682924 | tsrezende/Unis_2018.4_linguagemProgramacao | /exercTresCicloDois.py | 800 | 4.15625 | 4 | #-*-conding:latin1 -*-
#ler 3 numeros e mostre o menos deles
num1 = input ('Insira o primeiro numero: ')
num2 = input ('Insira o segundo numero: ')
num3 = input ('Insira o terceiro numero:')
if (num1>=num2 and num2>num3):
print 'O menor numero e :',num3
else:
if (num1>num2 and num3>=num2):
print 'O menor numero e: ',num2
else:
if(num2>num1 and num1>num3):
print 'O menor numero e:',num3
else:
if(num3>num1 and num1>num2):
print 'O menor numero e:',num2
else:
if(num3>num2 and num2>num1):
print 'O menor numero e:',num1
else:
if(num2>num3 and num3>num1):
print'O menor numero e:',num1
| false |
7fd2256b58710ab4321f11f7cdb3a27c3326dd4d | meghanamurthysn/D06 | /HW06_ch09_ex06.py | 1,050 | 4.4375 | 4 | #!/usr/bin/env python3
# HW06_ch09_ex05.py
# (1)
# Write a function called is_abecedarian that returns True if the letters in a
# word appear in alphabetical order (double letters are ok).
# - write is_abecedarian
# (2)
# How many abecedarian words are there?
# - write additional function(s) to assist you
# - number of abecedarian words: 0
##############################################################################
# Imports
# Body
def is_abecedarian(word):
count = 0
for ltr in word:
count += 1
if(count == 1):
index_alph = ord(ltr)
elif(index_alph > ord(ltr)):
return False
else:
index_alph = ord(ltr)
return True
def num_abecedarian():
fin = open('words.txt','r')
num_abecedarian_words = 0
for word in fin:
if is_abecedarian(word):
num_abecedarian_words += 1
print("The number of abecedarian words in the file are: {}".format(num_abecedarian_words))
##############################################################################
def main():
num_abecedarian()
if __name__ == '__main__':
main()
| true |
d32b2dc7a6b3758e1f7f32119c33a6ad2f836067 | IntriguedCuriosity/SpecializationInPython | /returning_values_of_a_class_using_str_method.py | 470 | 4.125 | 4 | class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initializeX, initializeY):
""" Create a new point at the origin """
self.x = initializeX
self.y = initializeY
def getX(self):
return self.x
def getY(self):
return self.y
def __str__(self):
return "x= {} , y= {}".format(self.x, self.y)
p=Point(5,10)
print(str(p)) | true |
0ed32b34c43ef96fb42bb2409673b5787d546b7a | kellischeuble/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 780 | 4.28125 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
# check to see if we are at the end of the word..
# can't possibly contain "th" if we have less than
# two characters
if len(word) < 2:
return 0
# if the first two letters are "th" return 1 to up
# the count AND the rest of the word without
if word[:2] == "th":
return 1 + count_th(word[2:])
# if the first two letters are not "th", then we need
# to just move over once and return the rest of the word
else:
return count_th(word[1:])
| true |
fa6b89ef3e34c957163364b033570156a8a1ddf2 | BiteSizeWhale/Python-2 | /ex50/Python/ex3.py | 1,148 | 4.4375 | 4 | #Prints out the line I will now count my chickens"
print "I will now count my chickens:"
#Prints out Hens then devides 30 by 6 and then adds 25 and 5
print "Hens", 25 + 30 / 6
#Prints out Roosters then Takes 20 out of the equation?
print "Roosters", float(10 - 9 * 3 % 4)
#Prints out what all the numbers will equal to after PENDAS
print float( 3 + 2 + 1 - 5 + 4 % 2 -1 /4 + 6)
#Prints out is it true that 3 + 2 < 2 - 7?
print "is it true that 3 + 2 < 5 - 7?"
#Tell you if the function is either true or false if it was ture the less than sign would be a grater than sign
print 3+ 2 < 5 - 7
#Prints out 3+2 and then gives you the number 5
print "What is 3 + 2?", 3+2
#Prints out What is 5 - 7 then gives you the number -2
print "What is 5 - 7?", 5 - 7
#Prints out Oh, that's why it's False.
print "Oh, that's why it's False."
#Prints out how about some more
print "How about some more."
#Prints out Is it greater? Then returns True
print "Is it greater?", 5 > -2
#Prints out is ti greater or equal, then reuturns True
print "is it greater or equal", 5 >= -2
#Prints out is it less or equal? then returns False
print "Is it less or equal?", 5 <= -2
| true |
70194d421a2c2accb8ef415e4bd3fd4d228ac2d6 | devChuk/snippets | /LeetCode/algorithms/728_selfdividingnumbers.py | 758 | 4.28125 | 4 | """
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
"""
def selfDividingNumbers(self, left, right):
result = []
for number in range(left, right + 1):
is_valid = True
for digit in str(number):
digit = int(digit)
if digit == 0 or number % digit != 0:
is_valid = False
break
if is_valid:
result.append(number)
return result
| true |
fe0e9f710d03349fe927b99cd648d2cb316d667c | sschuller13/Python-Code | /Session5Notes.py | 1,301 | 4.125 | 4 | #Week 5 2/14/19
x= range(3,6)
sum=0.0
for i in x:
sum+=i
avg=sum/len(x)
print "Average is: ", avg
a=[9,41,12,3,77,19]
print a
a[1:3]=[]
print a
a=list()
print a
a.append('book')
print a
a.append('30')
print a
a.append([3,'james'])
print a #3 elements now, makes the whole list ONE element
b=['book',30]
print b+[3,'james'] #notice difference between + and append
a=[3,1,10]
sorted(a) #this just creates a new list
print a
a.sort() #this sorts but doesn't save it like this, if you did a[1] you'd still get 3
print a
numList=list()
while True:
inp=raw_input('Enter a number:')
if inp=='done':
break
value=float(inp)
numList.append(value)
print numList
tuple1=['a','b',1]
print tuple1
#immutable, elements unchangable
#tuple=('a',) allows it to be a tuple, if you dont put the comma it'll just be a string
a,b,=(1,7)
a
b
a,b=b,a
eng2sp = {}
eng2sp['one'] = 'uno'
eng2sp['two'] = 'dos'
print eng2sp
{'one':'uno','two':'dos'}
counts=dict()
names=['csev','cwen','csev','zquian','cwen']
for name in names:
counts[name]=counts.get(name,0)+1
#name is the iteration, names is the name of the list, and this counts the number of times each names appears in the given dictionary
print counts
| true |
29c88c5f325441851da410b87de66729df0b6dc7 | edpender/Python-Exercises | /Python_Exercises_Reverse_a_String.py | 339 | 4.5625 | 5 | #Write a python function to reverse a string, then ask the users for a string to test it.
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Greek Yoghurt"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using loops) is : ",end="")
print (reverse(s))
| true |
10f906c4c1b6f48dd85885a19cb23a2ff0824e95 | huyjohnson/200605_007_Guttag_Ch2.4_FingerExercise_WhileLoop | /WhileLoop.py | 373 | 4.40625 | 4 | # - Finger exercise - Guttag chapter 2.4 - while loop
# Replace the comment in the following code with a while loop
numXs = int(input('How many times should I print the letter X? '))
toPrint = ''
# Below addition of while loop
while toPrint == '': # While toPrint is still an empty str
toPrint = 'X' * numXs
# Above addition of while loop
print(toPrint)
| true |
ef4b59a05be7ff495ef80793e2e16016f86dc5c2 | aalejoz25/Modelos-II | /Ejercicios Python/Ejercicios con ciclos/Ejercicio 31.py | 241 | 4.125 | 4 | """Escribir un programa que genere las tablas de multiplicar
de un número introducido por el teclado."""
x = int(input("Digite un numero entero: "))
print("Tabla de multiplicar de ",x,": ")
for i in [0,1,2,3,4,5,6,7,8,9]:
print(x*i)
| false |
9cae4e130a734d009d0441d15791e2e8eac5cd40 | piotrpatrzylas/Repl.it | /POP1 Part-time/Session 2 Problem 14: Number of zeros.py | 469 | 4.15625 | 4 | """
Given N numbers: the first number in the input is N, after that N integers are given. Count the number of zeros among the given integers and print it. You need to count the number of numbers that are equal to zero, not the number of zero digits.
Recommendation. Use for loops.
For example, on input
4
1
0
3
0
output must be
2
"""
counter = int(input())
final = 0
for i in range(0, counter):
num = int(input())
if num == 0:
final += 1
print(final)
| true |
08a619ca1a7984cb6e85493e3e807af9556fbda1 | piotrpatrzylas/Repl.it | /POP1 Part-time/Session 1 Problem 11: Sign of a Number.py | 236 | 4.15625 | 4 | """
For the given integer X print 1 if it's positive, -1 if it's negative, or 0 if it's equal to zero.
For example, on input
-13
output should be
-1
"""
n = int(input())
if n > 0:
print(1)
elif n == 0:
print(0)
else:
print(-1)
| true |
99e33baa748081826eba694fb00b92b44957c4df | piotrpatrzylas/Repl.it | /POP1 Part-time/Session 4 Problem 2: Swap Columns Function.py | 572 | 4.28125 | 4 | """
Implement the non-fruitful function swap_columns(M, m, n, i, j) that modifies the given matrix M, with m rows and n colums, by swapping the (whole) colums i and j.
For example, result of
M = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34]]
swap_columns(M, 3, 4, 0, 1)
print(M)
must be
[[12, 11, 13, 14], [22, 21, 23, 24], [32, 31, 33, 34]]
"""
def swap_columns(M, m, n, i, j):
if i != j:
for row in range(m):
for col in range(n):
if col == i:
tmp = M[row][col]
M[row][col] = M[row][j]
M[row][j] = tmp
| false |
2c865c8c33cd277e44dee07e792e8b3c5fee7c2d | piotrpatrzylas/Repl.it | /POP1 Part-time/Session 1 Problem 01 Sum of 3 numbers.py | 281 | 4.21875 | 4 | """
Instructions from your teacher:
Write a program that takes three numbers and prints their sum. Every number is given on a separate line.
For example, on input
5
6
7
output should be
18
"""
num1 = int(input())
num2 = int(input())
num3 = int(input())
print(num1+num2+num3) | true |
58f7331d0f8d9a5f41143c3cfbfbface8c74bcab | piotrpatrzylas/Repl.it | /POP1 Part-time/Session 11 Problem 1: Linked Lists and Stacks.py | 1,200 | 4.21875 | 4 | """
Implement a stack using a link list to store the sequence of its elements (see the lecture notes and slides for definitions and details).
Use the pattern on the left.
Your implementation must support the following examples/test cases
s = Stack()
#Test1 checks s.is_empty()==True
s.push(1)
s.push(2)
#Test2 checks s.peek()==2
s.pop()
#Test3 checks s.peek()==1
#Test4 checks s.is_empty()==False
s.pop()
#Test5 checks s.is_empty()==True
"""
class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
class Stack:
def __init__(self):
self.top = None #top stores a Node
def push(self, x):
#implement this: adds a new Node, makes top point to it,
#old top is "saved in" the new Node's next
NewNode = Node(x)
NewNode.next = self.top
self.top = NewNode
def pop(self):
#implement this: makes top point to the next of the Node pointed to by top
self.top = self.top.next
def peek(self):
#implement this: returns the data of the Node pointed to by top
return self.top.data
def is_empty(self):
#implement this: returns True if there are no Nodes in
#Stack, otherwise False
return (self.top == None)
| true |
ab10d6fb0e4bbf49e7ca4e10d055cd4aa0c5e03d | piotrpatrzylas/Repl.it | /POPI challenging problems (optional)/Session 1 Digital Clock.py | 416 | 4.21875 | 4 | """
Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock?
The program should print two numbers: the number of hours (between 0 and 23) and the number of minutes (between 0 and 59).
For example, on input
150
output must be
2 30
"""
clock = int(input())
hours = clock // 60
minutes = clock % 60
print(hours, " ", minutes) | true |
1fa7100cb5c73221aff4c9574f4b8cfc0651994d | piotrpatrzylas/Repl.it | /POP1 Part-time/Session 1 Problem 19: Chocolate bar.py | 564 | 4.21875 | 4 | """
Chocolate bar has the form of a rectangle divided into n×m portions. Chocolate bar can be split into two rectangular parts by breaking it along a selected straight line on its pattern.
Determine whether it is possible to split it so that one of the parts will have exactly k squares.
The program reads three integers: n, m, and k. It should print YES or NO.
For example, on input
2
10
7
output must be
NO
"""
n = int(input())
m = int(input())
k = int(input())
area = n * m
if (k % n == 0 or k % m == 0) and area >= k:
print("YES")
else:
print("NO")
| true |
c134286161547e0eae93ea01720d125c18503a5c | sdonk/data-structures | /algodata/algorithms/base_conversion.py | 1,732 | 4.125 | 4 | import string
from algodata.datastructures.basics import Stack
LETTERS_LOOKUP = {i + 10: string.ascii_lowercase[i] for i in range(26)}
def iterative_base_conversion(number, base):
"""
Converts a number (base 10) into a string of any base using string
"""
result = ""
while number != 0:
reminder = number % base
number = number // base
if 36 > reminder > 9:
result += LETTERS_LOOKUP[reminder]
else:
result += str(reminder)
# reverse the string
return result[::-1]
def stack_iterative_base_conversion(number, base):
"""
Converts a number (base 10) into a string of any base using a stack
"""
stack = Stack()
while number != 0:
reminder = number % base
number = number // base
if 36 > reminder > 9:
stack.push(LETTERS_LOOKUP[reminder])
else:
stack.push(reminder)
# pop the elements out of the stack and return the result
result = ""
# the following code can be rewritten more elegantly using join and implementing __iter__ in the Stack
# it's done in this way to demonstrate the underlying logic
# see next function for a more Pythonic way
while not stack.is_empty:
result += str(stack.pop())
return result
def list_iterative_base_conversion(number, base):
"""
Converts a number (base 10) into a string of any base using a list
"""
elements = []
while number != 0:
reminder = number % base
number = number // base
if 36 > reminder > 9:
elements.append(LETTERS_LOOKUP[reminder])
else:
elements.append(str(reminder))
return ''.join(reversed(elements))
| true |
218fa219f1416fb2b980ad8555cbb4d461874310 | iandavidson/SSUCS115 | /Lab06/Lab06a.py | 656 | 4.21875 | 4 | '''
Program: CS 115 Lab 6a
Author: Ian Davidson
Description: This program will ask the user for a value
and tell the user whether the value is even or odd.
'''
def main():
N = int(input('Enter a number: '))
while (N != 1):
if N % 2 == 1:
# Compute the next term in the Collatz sequence for odd N, and set N to that value.
N = 3*N + 1
print("The next term is " + str(N) + ".")
else:
# Compute the next term in the Collatz sequence for even N, and set N to that value.
N = N//2
print("The next term is " + str(N) + ".")
# Print the new value of N.
main() | true |
053b3e4a977ba3a3f9009e3fe42cad86c067a4e3 | f-fathurrahman/ffr-MetodeNumerik | /chapra_7th/ch15/chapra_example_15_7.py | 735 | 4.125 | 4 | from scipy.optimize import minimize
def obj_func(x):
x1 = x[0]
x2 = x[1]
# we use the same notation as in the book
return 2 + x1 - x2 + 2*x1**2 + 2*x1*x2 + x2**2
x0 = [-0.5, 0.5] # initial search point
# The following are some methods that do not require gradient information
# result = minimize(obj_func, x0, method="Nelder-Mead")
# result = minimize(obj_func, x0, method="BFGS")
result = minimize(obj_func, x0, method="L-BFGS-B")
# NOTE
# We search for the minimum value.
# The book mistakenly asks us to find the maximum instead.
# Full output (might differ for each methods)
print("result = ")
print(result)
# The result
print("result.x (arg) = ", result.x)
print("result.fun (minimum value) = ", result.fun)
| true |
97051c950e72d25c09eaeb81953b185eaafe6fbc | skgtrx/Python-OOP | /Pillar-4(Polymorphism)/15-AbstractBaseClass.py | 1,344 | 4.5625 | 5 | ''' Abstract Base Class '''
# Abstract base class doesn't have defination on its own but
# forces the implimentation of abstract methods in its derived classs.
# Abstract class doesn't have an instance.
### Situation ###
# We have 2 classes square and rectangle.
# Both of them area method.
# We hae to make sure that both the classes must contain area class.
# Here, for this situation an abstract class can help us.
# For creating an abstract we have to import ABCMeta and abstractmethod from abc module.
from abc import ABCMeta, abstractmethod
# Abstract class
class Shape(metaclass = ABCMeta): # We have to pass ABCMeta to metaclass
@abstractmethod # Decorator for making abstract method.
def area(self):
return 0
class Square(Shape):
side = 4
def area(self):
print("Area of square: ",self.side*self.side)
class Rectangle(Shape):
length = 10
width = 5
def area(self):
print("Area of rectangle: ",self.length*self.width)
sq = Square()
rec = Rectangle()
sq.area()
rec.area()
# We can check either abstract class is working or not by commenting area method in either of Square or Rectangle.
# Let's try creating object of abstract class
#s = Shape()
#TypeError: Can't instantiate abstract class Shape with abstract methods area
| true |
65a0f4cc3ae8ae1714ffdf549a53d254ec6b1b81 | skgtrx/Python-OOP | /Pillar-3(Inheritance)/11-AccessSpecifier.py | 1,433 | 4.28125 | 4 | ''' In this section we'll get to know about Access Specifier Public, Private and Protected Members of the class '''
# Public Means access to anyone.
# Proctected means access to itself and serived class
# Private means only access to itself.
# In python by default these access specifier are not included into the syntex.
# Rather a naming convention has been given to them to make their use easy.
# For Public -> it's normal the way we do.
# For Protected -> Start your member name with _
# For Private -> Start your member name wit __
class Car:
numberOfWheels = 4 # Public
_color = "Black" # Protected
__yearOfManufacture = 2017 # Private
class Bmw(Car):
def __init__(self):
print("Protected attribute color: ",self._color)
car = Car()
print("Public attribute number of Wheels : ",car.numberOfWheels)
# The same we accessed the public member we can also access the protected as well.
# But due too the naming convention it's not recommended to do so.
bmw = Bmw()
# Now, let's print private
print("Private attribute by class year of manufacture : ",Car._Car__yearOfManufacture) # This is known as name mangling in private member.
print("Private attribute by instance year of manufacture : ",car._Car__yearOfManufacture)
# Private attribute can be access by either class or the instance of that class only.
# But it's recommended to not do it until and unless not necessary.
| true |
9b7e3a132294e1d668a57ecc4357b30bca0010f7 | canattofilipe/python3 | /basico/dicionarios/dicionarios_pt1.py | 888 | 4.375 | 4 | """
Exemplos de dicionários em Python3.
"""
# criando um dicionario.
pessoa = {'nome': 'Prof(a). Ana', 'idade': 38, 'cursos': [
'Inglês', 'Português']}
# verifica o tipo.
print(type(pessoa)) # <class 'dict'>
# mostra as operações disponiveis para um dicionario.
print(dir(dict))
"""
mostra a quantidade de pares (chave e valor) contidas
no dicionario.
"""
print(len(pessoa))
# acessando valor pela chave.
print(pessoa['nome'])
print(pessoa.get('idade'))
"""
acessa o valor pela chave e
devolve um valor customizado quando nao encontra a chave.
"""
print(pessoa.get('valor invalido'), ['lista vazia'])
# acessando um valor do tipo lista
print(pessoa['cursos'][1])
# mostra todas as chaves de um dicionario.
print(pessoa.keys())
# mostra todos os valores de um dicionario.
print(pessoa.values())
# mostra todos os items (chave e valor) de um dicionario.
print(pessoa.items())
| false |
fa0a7199452f61e4d9d2f1933b01ea53d474cef0 | canattofilipe/python3 | /estrutura_controle/for_2.py | 697 | 4.21875 | 4 | #!/usr/bin/python3
# iterando sobre uma string.
palavra = 'paralelepipado'
for letra in palavra:
print(letra, end=',')
print('Fim')
# iterando sobre uma lista.
aprovados = ['Rafaela', 'Pedro', 'Renato', 'Maria']
for nome in aprovados:
print(nome)
for posicao, nome in enumerate(aprovados):
print(posicao+1, nome)
# iterando sobre uma tupla.
dias_semana = ('Domingo', 'Segunda', 'Terça',
'Quarta', 'Quinta', 'Sexta', 'Sabado')
for dia in dias_semana:
print(f'Hoje é dia {dia}')
# iterando sobre um conjunto de string.
for letra in set('Muito Legal'):
print(letra)
# iterando sobre um conjunto de numeros.
for numero in {1, 2, 3, 4, 5}:
print(numero)
| false |
aab55e281d060fafd9434275dec5a88f85eb78c1 | canattofilipe/python3 | /basico/conjuntos/conjuntos.py | 792 | 4.3125 | 4 | """
Exemplos de conjuntos em Python3.
"""
# criando um conjunto.
a = {1, 2, 3, 3}
print(type(a)) # <class 'set'>
print(a)
# criando um conjunto usando a funcao set().
a = set('cod3r')
print(a)
# usando operadores de membro em conjuntos.
print('c' in a, 't' not in a)
# verica se um conjunto pertence ao outro.
{1, 2, 3} == {3, 2, 1, 3} # True
# Operações.
c1 = {1, 2}
c2 = {2, 3}
print(c1.union(c2)) # {1, 2, 3}
print(c1.intersection(c2)) # {2}
# incorpora os elementos de "c2" em "c1".
c1.update(c2)
print(c1) # {1, 2, 3}
# verifica se "c2" é um subconjunto de "c1".
print(c2 <= c1) # True
# verifica se "c1" é um superconjunto de "c2".
print(c1 >= c2)
# mostra a diferença entre os conjuntos (isso é o contrario da interseção)
print({1, 2, 3} - {2})
print(c1 - c2)
| false |
154387ed446a7f1cb428998749969612342e7277 | jeyjey626/AISDI-projects | /sorting-algorithms/src/bubble_sort.py | 742 | 4.21875 | 4 | # Bubble sorting algorithm
import sys
def sort(array):
list_to_sort = array.copy()
swap_occurred = True # algorithm should finish when no swap was made
while swap_occurred:
swap_occurred = False # new iteration, reset swap flag
for i in range(len(list_to_sort) - 1): # 1 less than elements because we are always checking a i, i+1 pair
if list_to_sort[i] > list_to_sort[i + 1]:
# Swap elements and flag swap
list_to_sort[i], list_to_sort[i + 1] = list_to_sort[i + 1], list_to_sort[i]
swap_occurred = True
return list_to_sort
if __name__ == '__main__':
sort_array = [ch for ch in open(sys.argv[1]).read()]
sort_array = sort(sort_array)
| true |
67aa67c8bd1d099c22f6c4b397f9be4125390d58 | annu100/AI5002-Probability-and-Random-variables | /Assignment_5/python codes/sum_of_2_no_ondices.py | 1,126 | 4.28125 | 4 | from matplotlib import pyplot as plt
sides=6; # 2 dices with 6 sides
def all_rolls(sides):
"""Return sum of all combinations of two dice with given number of sides."""
result = []
temp_list = list(range(2, 2*sides+1))
while temp_list:
result.extend(temp_list)
temp_list = temp_list[1:-1]
return sorted(result)
y=all_rolls(6) # returns all combinations of sum of numbers on 2 dices
possible_outcomes=36 # total number of outcomes
print(y)
occurance=[x for x in range(11)]
prob=[x for x in range(11)]
def find_prob(y):
x=[2,3,4,5,6,7,8,9,10,11,12]
for i in range(11):
occurance[i]=y.count(x[i]) # counting each outcome
prob[i]=occurance[i]/possible_outcomes; #desired probability matrix
return prob
print("probability for getting sum on 2 dices are given by:",find_prob(y))
x=[2,3,4,5,6,7,8,9,10,11,12]
plt.plot(x,find_prob(y),marker='o')
plt.xlabel("possible sums of 2 numbers appearing on two dices")
plt.ylabel("probability of sum of 2 numbers appearing on two dices")
plt.title("graph of probability versus sum of two numbers")
plt.show()
| true |
7e5bcdcdbb0db54ca4637eb38476facd7029e03d | avison9/Hackerrank30dayscode | /day5.py | 1,680 | 4.28125 | 4 |
# Write a Person class with an instance variable,age, and a constructor that takes an integer, initalAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print Age is not valid, setting age to 0.. In addition, you must write the following instance methods:
# yearPasses() should increase the instance variable by .
# amIOld() should perform the following conditional actions:
# If , print You are young..
# If and , print You are a teenager..
# Otherwise, print You are old..
# To help you learn by example and complete this challenge, much of the code is provided for you, but you'll be writing everything in the future. The code that creates each instance of your Person class is in the main method. Don't worry if you don't understand it all quite yet!
# Note: Do not remove or alter the stub code in the editor
class Person:
def __init__(self,initialAge):
if initialAge < 0:
print("Age is not valid, setting age to 0.")
self._age = 0
else:
self._age = initialAge
def amIOld(self):
if self._age < 13:
print("You are young.")
elif self._age >= 13 and self._age < 18:
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
self._age += 1
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("") | true |
75ee0a340b8d3abf3264cf648cddc96387085cae | rustnnes/HackerRank | /python/p21.py | 374 | 4.125 | 4 | #!/bin/python3
"""
Basic code for learning Python
Problem 21 - Text Wrap
(https://www.hackerrank.com/challenges/text-wrap/)
"""
import textwrap
def wrap(string, max_width):
return textwrap.fill( textwrap.dedent(string) , width=max_width)
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
| true |
de7bfe16725c42dad1f5f9b0f5a5ac285e8d4d3c | Vaibhav-rawat/Show-me-the-next-Pelindrome | /main.py | 617 | 4.125 | 4 | '''To check whether a number is pelindrome or not and if not it prints the next pelindrome which comes after that number
Author - Vaibhav Rawat
Purpose - Python Problem Solving'''
n=int(input('How many number you want to enter?\n'))
l=[]
for i in range(n):
i=int(input('Enter the number\n'))
l.append(i)
for i in l:
if str(i)==str(i)[::-1]:
print('This number is a Pelindrome\n')
else:
print(f'Opps {i} is not a pelindrome but next pelindrome is')
while True:
if str(i)==str(i)[::-1]:
print(i)
break
else:
i+=1
| false |
efd9987c79038c848bb2d66452ffc11fa05ca078 | zadraleks/Stepik.Python_3.First_steps | /Lesson 1-4/1-4-3.py | 240 | 4.25 | 4 | #Напишите программу, вычисляющую квадратный корень введённого целого числа. Задаваемое число больше или равно 0.
a = int(input())
print(a ** 0.5) | false |
10e7edacab01199d3b21598ace2785281921b887 | zadraleks/Stepik.Python_3.First_steps | /Lesson 1-5/1-5-3.py | 256 | 4.1875 | 4 | #Напишите программу, которая считает произведение двух вещественных чисел. Данные находятся на разных строках.
a = float(input())
b = float(input())
print(a * b) | false |
4053b718547e2a027fbd84f1e181334abf4e4ca4 | lobdol/softserve_course | /Multiples of 3 or 5.py | 532 | 4.21875 | 4 | #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
# Note: If the number is a multiple of both 3 and 5, only count it once.
#Pushynskyy Kostya
def solution(number):
sum=0
while number>0:
number=number-1
if number%5==0:
sum=sum+number
elif number%3==0:
sum=sum+number
return sum | true |
ce161cfface27d08b2572104aeca973f941f4cc3 | OleksandrTsegelnyk/Tsegelnyk_Lv-450.1.PythonCore | /HW4T3.py | 695 | 4.3125 | 4 | # Create a function which answers the question "Are you playing banjo?".
# If your name starts with the letter "R" or lower case "r", you are playing banjo!
# The function takes a name as its only argument, and returns one of the following strings:
# name + " plays banjo"
# name + " does not play banjo"
# user_name = input("Input your name and I will say playing you banjo or not ")
############################################
# 1 way
def music_answer(user_name):
if user_name[0]=='R' or user_name[0]=='r':
print(user_name, " plays banjo" )
else:
print(user_name, " does not play banjo")
music_answer('doma')
#################################################
| true |
54a38d9d0e5ba16f4b06e666984c8000bfbf7775 | Jacklu0831/Interview-Prep | /small-problems/Square_root.py | 708 | 4.28125 | 4 | def sqrt(n):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
left = 0
right = n
while left <= right:
middle = (left + right) // 2
floor_pred = middle ** 2
ceiling_pred = (middle + 1) ** 2
if floor_pred <= n < ceiling_pred:
return int(middle)
elif n >= ceiling_pred:
left = middle + 1
else:
right = middle - 1
return None
print ("Pass" if (3 == sqrt(9)) else "Fail")
print ("Pass" if (0 == sqrt(0)) else "Fail")
print ("Pass" if (4 == sqrt(16)) else "Fail")
print ("Pass" if (1 == sqrt(1)) else "Fail") | true |
86df2aaaf76a6b1556031f3e3dc38aa2dd69885f | EthanTaft/PythonLearning | /Calendar.py | 2,629 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 21 11:46:31 2017
@author: Ethan
"""
"""Build a caldendar that the user will be able to interact with from the
command line. The user should be able to view the calendar, add events,
pdate events, and delete events.
"""
"""The program should behave in the following way: Print a welcome message to
the user. Prompt the user to view, add, update, or delete and event on the
calendar. Depending on what the user specifies they want to do, the program
should do exactly what the user wants it to do. The program should never
terminate unless the user decides to exit.
"""
"""Build a calendar, man!
"""
from time import sleep, strftime
user_name = "Darrill"
calendar = {}
def welcome():
print(user_name + " welcome to your personal calendar.")
print("Your calendar is opening...")
sleep(1)
print("Date: "+ strftime("%A %B %d, %Y"))
print("Time: " + strftime("%I:%M:%S"))
sleep(1)
print("What would you like to do?")
def start_calendar():
welcome()
start = True
while start == True:
user_choice = input("Choose A to add, U to Update, V to View D to Delete, "
"X to Exit: ")
user_choice.upper()
if user_choice in ["v", "V"]:
if len(calendar.keys()) == 0:
print("The calendar is empty")
else:
print(calendar)
elif user_choice in ["u", "U"]:
date = input("What date?: ")
update = input("Enter the update: ")
calendar[date] = update
print("Your calendar was updated")
print(calendar)
elif user_choice in ["a", "A"]:
event = input("Enter event: ")
date = input("Enter date MM/DD/YYYY: ")
if len(date) > 10 or int(date[6:10]) < int(strftime("%Y")):
print("Entered date is invalid")
try_again = input("Try Again? Y for Yes, N for N: ")
if try_again == "Y":
continue
else:
start = False
else:
calendar[date] = event
print("Event Added!")
print(calendar)
elif user_choice in ["d", "D"]:
if len(calendar.keys()) == 0:
print("The calendar is already empty.")
else:
event = input("What event?: ")
for i in list(calendar.keys()):
if calendar[i] == event:
del(calendar[i])
print("The event was successfully deleted.")
print(calendar)
else:
print("That event does not yet exist in the calendar.")
elif user_choice in ["x", "X"]:
start = False
else:
print("Your choice is not a valid choice for this program.")
start = False
| true |
544b2f7daaf0235e1f18d823e4e29ab74923b882 | EthanTaft/PythonLearning | /SquaredListSort.py | 721 | 4.5 | 4 | """Here is a function that takes a list as a parameter. It squares each
element in the list and then appends that value to a new list that is originally
empty before the initialization of the for loop. This shows two ways to do it.
One sequentially in scripting fashion and then one functionally.
"""
start_list = [5, 3, 1, 2, 4]
square_list = []
for element in start_list:
square_list.append(element**2)
square_list.sort()
print square_list
"""Or Make a function to do the same thing for future lists that need to be
squared and sorted
"""
def list_square_sort(ls):
empty_ls = []
for element in ls:
empty_ls.append(element**2)
empty_ls.sort()
return(empty_ls)
list_square_sort(start_list)
| true |
21680ca3bf8648fe5f7c78d8ba79cf7a8b88cc94 | mikemklee/CSC108 | /Week 1/ch1-3.py | 2,740 | 4.40625 | 4 | # defining function
def convert_to_celsius(farenheit):
return (farenheit - 32) * 5 / 9
# using local variables for temporary storage
def quadratic(a, b, c, x):
first = a * x ** 2
second = b * x
third = c
return first + second + third
# call quadratic()
print(quadratic(2, 3, 4, 0.5))
# Example function with docstring
def days_difference(day1, day2):
""" (int, int) -> int
Return the number of days between day1 and day2, which are
both in the range 1-365 (thus indicating the day of the year).
>>> days_difference(200, 224)
24
>>> days_difference(50, 50)
0
>>> days_difference(100, 99)
-1
"""
return day2 - day1
# the first line : function header
# the second line: describe types of values to be passed and returned
# after that: decription of what the function will do when called;
# mention parameters and describe what the function returns
# after that: example calls and return values as expected
# after that: body of function
def get_weekday(current_weekday, days_ahead):
""" (int, int) -> int
Return which day of the week it will be days_ahead days
from current_weekday.
current_weekday is the current day of the week and is in the range
1-7, indicating whether today is Sunday (1), Monday (2), ..., Saturday (7).
days_ahead is the number of days after today.
>>> get_weekday(3, 1)
4
>>> get_weekday(6, 1)
7
>>> get_weekday(7, 1)
1
>>> get_weekday(1, 0)
1
>>> get_weekday(4, 7)
4
>>> get_weekday(7, 72)
2
"""
return (current_weekday + days_ahead - 1) % 7 + 1
def get_birthday_weekday(current_weekday, current_day, birthday_day):
""" (int, int, int) -> int
Return the day of the week it will be on birthday_day, given that the
day of the week is current_weekday and the day of the year is
current_day.
current_weekday is the current day of the week and is in the range 1-7,
indicating whether today is Sunday (1), Monday (2), ..., Saturday (7).
current_day and birthday_day are both in the range 1-365.
>>> get_birthday_weekday(5, 3, 4)
6
>>> get_birthday_weekday(5, 3, 116)
6
>>> get_birthday_weekday(6, 116, 3)
5
"""
days_diff = days_difference(current_day, birthday_day)
return get_weekday(current_weekday, days_diff)
def pie_percent(n):
""" (int) -> int
Precondition: n > 0
Assuming there are n people who want to eat a pie, return the percentage
of the pie that each person gets to eat.
>>> pie_percent(5)
20
>>> pie_percent(2)
50
>>> pie_percent(1)
100
"""
return int(100/n)
| true |
16f4b3e2a327e043e86d2fc3a3ecae7036f03bfe | Adnan-Mohammad/Python-Homework | /HM 3 Part B.py | 1,006 | 4.3125 | 4 | ##String In that we need to search
s = 'this should happen'
stringfortest = 'this happen'
## List to store the that the string is persent or not in the provided string
##for that let's take an blank list
listToStoreBoolValues = []
##Spliting the testing string to store all the values of the provided string
listToStoreAllElementsOfStringforTest = stringfortest.split(' ')
##Now we will loop over the above list
for i in listToStoreAllElementsOfStringforTest:
##Using membership opertor to check the values persent in the string or not
if i in s:
print('Yes element or word %s is persent in the string'%(i))
listToStoreBoolValues.append(True)
else:
listToStoreBoolValues.append(False)
print('List:- ',listToStoreBoolValues)
## Now if any of the element present in the string then we will print the string that is used for the testing
if 1 in listToStoreBoolValues:
print("Here is your string : - %s"%(s))
else:
print('No string is present') | true |
5fc4517d44f79d71ebba6506a6400d72da04940c | TeaPanda/Python-Temp-Converter | /Main.py | 911 | 4.15625 | 4 | import sys
import os
while True:
print("What is the temperature? Please only use numbers")
x = int(input(""))
if -99999 < x < 99999:
break
else:
print("Your number is too big or too small, are you even on earth?")
while True:
print("Type C if it is in Celsius or F if it is in Fahrenheit")
unit = input("")
if unit.capitalize() == "C":
f = x * (9/5) + 32
print( x ,"ºC is", f , "ºF")
break
elif unit.capitalize() == "F":
c = (x - 32) * (5/9)
print( x ,"ºF is", c , "ºC")
break
else:
print("Please insert either C or F")
print("")
if unit.capitalize() == "C":
k = x + 273.15
print("Btw, your temperature in Kelvins is" , k)
else:
k = c + 273.15
print("Btw, your temperature in Kelvins is" , k)
print("")
input("Press any key to exit")
| true |
a1e3fa53959b119362450f7bb8ecb3251a817b27 | ozericyer/class2-functions-week04 | /4th week 2.exact_divisor.py | 854 | 4.375 | 4 | """Write a function that finds the exact divisors of a given number.
For example:
function call : exact_divisor(12)
output : 1,2,3,4,6,12"""
def exact_divisor(number): #we define exact_divisor function
divisors=[] #we define empty divisors and alldivisors for using for loop
al_divisors= []
if (number== 0): #0 is not a divisor,Firstly we set this condition
return "Zero has no exact divisor"
else: #if it is a number except 0
for h in range(1,number+1): #We set a for loop for scanning divisors from 1 to this number.
if (number % h==0): #If any number h is divisor of this number,we add to list divisors
divisors.append(h)
al_divisors=divisors
return al_divisors #Then we print all divisor
print(*(exact_divisor(20))) | true |
69ceb7ccc8bede5dfc9b94240f93bab67c87754d | ozericyer/class2-functions-week04 | /4th week 10.unique_list.py | 854 | 4.28125 | 4 | """Write a function that filters unique(unrepeated) all elements of a given list.
For example :
function call: unique_list([1,2,3,3,3,3,4,5,5])
output : [1, 2, 3, 4, 5]"""
t=[1, 3, 5, 6, 3, 5, 6, 1,5,6,3,3,8] # We have a list and we will filter this list
print ("The original list is:"+str(t)) # We print original list for seeing differences
unique=[] #And we define list unique for using for loop
def unique_list(t): #We define function unique_list
for i in t: #We set for loop for scanning list
if i not in unique: #If it is not in list,We will add the number to unique list
unique.append(i)
return "The list after removing repeated numbers:"+str(unique) #And finally we print our new list
print(unique_list(t)) | true |
f12ab28df6fe8f21ae80014d4ab1f640da6d791c | terbos/PythonForEverybody | /strings.py | 876 | 4.125 | 4 | surname = "Papastergiou"
print("String: ",surname)
print("Length: ", len(surname))
print("Taking a part or a letter from a string")
print("First part of String: ",surname[:6])
print("Second part of String: ",surname[6:])
print("Find a count of a letter")
def findLetter(letterToFind):
count = 0
for letter in surname:
if letter == letterToFind:
count += 1
print("Letter:",letterToFind,"has appeared", count, "times")
findLetter("a")
print("In Capitals:",surname.upper())
def findIndexOfTheLetter(letter,string):
index = string.find(letter)
print("Index of letter",letter,"in string:",string,"is:",index)
findIndexOfTheLetter("g",surname)
findIndexOfTheLetter("ster",surname) #can work with substrings as well
print("Does surnname start with P?",surname.startswith("P"))
print("Does surnname start with p?",surname.startswith("p"))
| true |
4629106df2f91a3da9eaf5ff4d740c66bb8b5cfd | terbos/PythonForEverybody | /assignment_4_6.py | 1,086 | 4.34375 | 4 | #4.6 Write a program to prompt the user for
# hours and rate per hour using input to compute gross pay.
# Award time-and-a-half for the hourly rate
# for all hours worked above 40 hours.
# Put the logic to do the computation of time-and-a-half
# in a function called computepay()
# and use the function to do the computation.
# The function should return a value.
# Use 45 hours and a rate of 10.50 per hour to test the program
# (the pay should be 498.75).
# You should use input to read a string and float()
# to convert the string to a number.
# Do not worry about error checking the user input
# unless you want to - you can assume the user types numbers properly.
# Do not name your variable sum or use the sum() function.
input_hours = input("Enter the hours: ")
input_rate = input("Enter the rate: ")
hours = float(input_hours)
rate = float(input_rate)
def computepay():
if hours > 40:
payment = (hours - 40) * (rate * 1.5)
final_payment = payment + (40 * rate)
else:
final_payment = hours * rate
return final_payment
print(computepay())
| true |
5cb1ce752acc0b96c0cdf111e6371a24519c170e | gregg45/LPTHW | /ex15.py | 674 | 4.53125 | 5 | #first we import argv to take arguement variables from the command line
from sys import argv
# next we unpack argv to the two variables specified
script, filename = argv
# we then assign the txt variable to a file which we open called filename, taken from the command line
txt = open(filename)
# We print a sentence with character formatting and with the filename
print "Here's your file %r" % filename
# we read the file text and print it
print txt.read()
# we ask for the file from the raw input
print "Type the filename again:"
file_again = raw_input("> ")
# we do the same thing, assigning it the variable text again
txt_again = open(file_again)
print txt_again.read() | true |
35046c269f1e893fc0f6684e09dc63d9ce76224b | Tomasz-Kluczkowski/Education-Beginner-Level | /THINK LIKE A COMPUTER SCIENTIST FOR PYTHON 3/CHAPTER 26 QUEUES/Linked Queue.py | 1,337 | 4.3125 | 4 | class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
if self.cargo == None:
return ""
return str(self.cargo)
def print_backward(self):
first_node = self
if self.next is not None: #if not last item which does not have next defined
tail = self.next #move to the next item, print nothing
tail.print_backward() #call to print tail recursively until we reach
print(self.cargo, end=" ") #print item with no next defined
if self is not first_node:
print(",", end=" ")
class Queue:
def __init__(self):
self.length = 0
self.head = None
def is_empty(self):
return self.length == 0
def insert(self, cargo):
node = Node(cargo)
if self.head is None:
#if list is empty the new node goes first
self.head = node
else:
# find the last node in the list
last = self.head
while last.next:
last = last.next
# append the new node
last.next = node
self.length += 1
def remove(self):
cargo = self.head.cargo
self.head = self.head.next
self.length -= 1
return cargo | true |
f13b4a457ded589ce45e5bc0214fc98312023893 | Tomasz-Kluczkowski/Education-Beginner-Level | /THINK LIKE A COMPUTER SCIENTIST FOR PYTHON 3/CHAPTER 18 RECURSION/litter.py | 1,895 | 4.6875 | 5 | """
11.Write a program named litter.py that creates an empty file named trash.txt in each subdirectory of a directory tree given the root of the tree as an argument (or the current directory as a default). Now write a program named cleanup.py that removes all these files.
Hint #1: Use the program from the example in the last section of this chapter as a basis for these two recursive programs. Because you’re going to destroy files on your disks, you better get this right, or you risk losing files you care about. So excellent advice is that initially you should fake the deletion of the files — just print the full path names of each file that you intend to delete. Once you’re happy that your logic is correct, and you can see that you’re not deleting the wrong things, you can replace the print statement with the real thing.
Hint #2: Look in the os module for a function that removes files.
myfile = open("test.txt", "w")
myfile.write("My first file written from Python\n")
myfile.write("---------------------------------\n")
myfile.write("Hello, World!\n")
myfile.close()
"""
import os
def get_dirlist(path):
""" Return a sorted list of all entries in path.
This returns just the names, not the full path to the names.
"""
dirlist = os.listdir(path)
dirlist.sort()
return dirlist
def add_litter(path):
""" Print recursive listing of contents of path """
dirlist = get_dirlist(path)
for file in dirlist:
fullname = os.path.join(path, file) # turn name into full pathname
if os.path.isfile(fullname):
continue # skip file creation for path which leads to a file
elif os.path.isdir(fullname):
file_handle = open(fullname +"\\litter.txt", "w")
file_handle.write("")
file_handle.close()
add_litter(fullname)
add_litter("C:\\Temp\\") | true |
a89da65c0269395111113aad55839a91e01d7374 | Tomasz-Kluczkowski/Education-Beginner-Level | /THINK LIKE A COMPUTER SCIENTIST FOR PYTHON 3/CHAPTERS 1 - 7/conditionals ex11-12 find if right angled.py | 2,248 | 4.71875 | 5 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Kilthar
#
# Created: 25-01-2017
# Copyright: (c) Kilthar 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
"""Write a function is_rightangled which, given the length of three sides of a
triangle, will determine whether the triangle is right-angled.
Assume that the third argument to the function is always the longest side.
It will return True if the triangle is right-angled, or False otherwise.
Hint: Floating point arithmetic is not always exactly accurate,
so it is not safe to test floating point numbers for equality.
If a good programmer wants to know whether x is equal or close enough to y,
they would probably code it up as:
if abs(x-y) < 0.000001: # If x is approximately equal to y
...
Extend the above program so that the sides can be given to
the function in any order."""
def is_rightangled(side1,side2,side3):
"checks if the triangle is right angled using pythagorean theorem c^2 = a^2 + b^2"
c_side = max(side1,side2,side3)
"""we have to decide which of the variables is the maximum one, since we have not learned about
obtaining index of a value in a list we have to do it the hard way and check for the variables value and determine which one it is"""
if c_side == side1: # checks if side1 is the longest side
a_side = side2
b_side = side3
return abs(c_side**2-(a_side**2+b_side**2)) < 0.000001
elif c_side == side2: # checks if side2 is the longest side
a_side = side1
b_side = side3
return abs(c_side**2-(a_side**2+b_side**2)) < 0.000001
else: # checks if side3 is the longest side
a_side = side1
b_side = side2
return abs(c_side**2-(a_side**2+b_side**2)) < 0.000001
side1 = float(input("Please enter length of side1:"))
side2 = float(input("Please enter length of side2:"))
side3 = float(input("Please enter length of side3:"))
if is_rightangled(side1,side2,side3):
print("The triangle is right angled")
else:
print("The triangle is not right angled")
| true |
85e8f9c1183999f50972af3f1040b4d91167a87a | Tomasz-Kluczkowski/Education-Beginner-Level | /THINK LIKE A COMPUTER SCIENTIST FOR PYTHON 3/CHAPTERS 1 - 7/filling bars.py | 882 | 4.21875 | 4 | import turtle
def draw_bar(t,height):
''' get turtle t to draw one bar of height'''
t.begin_fill() #fill bar with color set as a second parameter of turtle
t.left(90)
t.forward(height)
t.write(" "+ str(height)) # will write bar's value on top of it
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill() #stop filling a bar
t.penup() # separate the bars from each other
t.forward(10) # small gap for before the next bar
t.pendown()
wn = turtle.Screen()
wn.bgcolor("lightblue")
wn.title("display bar chart")
tom = turtle.Turtle()
tom.pensize(1)
tom.speed(1)
tom.color("blue", "red") # will change pen color to blue and fill color to red for #this turtle
data = [48, 117, 200, 240, 160, 260, 220] # data values for the bar chart
for a in data:
draw_bar(tom,a)
# wn.mainloop() this is commented for iphone use only
| true |
09fc8d5d0e1c3460cd96b9c47a76483c4c6b0ea7 | Tomasz-Kluczkowski/Education-Beginner-Level | /THINK LIKE A COMPUTER SCIENTIST FOR PYTHON 3/CHAPTER 8 STRINGS EXERCISES/Ex11 count substrings.py | 711 | 4.28125 | 4 |
def count_substring(text,substring):
"""count how many times substring occurs in string text"""
ix = 0
count = 0
while ix < (len(text)-1):
if text.find(substring,ix) != -1:
ix = text.find(substring,ix)+1 #+len(substring) version with +len(substring) omits repeated occurences within the substring itself i.e.: 'aaa' in 'aaaaaa' and counts only 2 for this example not 4
count += 1
elif text.find(substring,ix) == -1:
break
return count
print(count_substring('Mississippi','is'))
print(count_substring('lala land','la'))
print(count_substring('tututututututu','tu'))
print(count_substring('aaaaaa','aaa'))
| true |
a637908bfda4b0f42989e63417a595154303754a | Tomasz-Kluczkowski/Education-Beginner-Level | /THINK LIKE A COMPUTER SCIENTIST FOR PYTHON 3/CHAPTER 21 MORE OOP/Class MyTime.py | 2,153 | 4.125 | 4 | from unit_testing import test
class MyTime:
def __init__(self, hrs=0, mins=0, secs=0):
"""Create a MyTime object initialized to hrs, mins, secs.
The vlue of mins and secs can be outside the range 0-59,
but the resulting MyTime object will be normalized"""
totalsecs = hrs*3600 + mins*60 + secs
self.hours = totalsecs // 3600
leftoversecs = totalsecs % 3600
self.minutes = leftoversecs // 60
self.seconds = leftoversecs % 60
def to_seconds(self) -> int:
"""Return the number of seconds represented by this instance"""
return self.hours * 3600 + self.minutes * 60 + self.seconds
def __str__(self):
return "{0:02d}:{1:02d}:{2:02d}".format(self.hours, self.minutes, self.seconds)
def increment(self, seconds):
time = MyTime(0, 0, self.to_seconds() + seconds)
self.hours = time.hours
self.minutes = time.minutes
self.seconds = time.seconds
def add_time(self, t2):
secs = self.to_seconds() + t2.to_seconds()
return MyTime(0, 0, secs)
def after(self, time2):
"""Return True if I am strictly greater than time2
:type time2: MyTime
"""
return self.to_seconds() > time2.to_seconds()
def __add__(self, other):
return MyTime(0, 0, self.to_seconds() + other.to_seconds())
def __sub__(self, other):
return MyTime(0, 0, self.to_seconds() - other.to_seconds())
def between(self, t1, t2):
"""Returns true if invoking object is between times t1 and t2
:type t1: MyTime
:type t2: MyTime
"""
return t1.to_seconds() <= self.to_seconds() < t2.to_seconds()
def __gt__(self, other):
"""Allows to compare two MyTime objects"""
return self.to_seconds() > other.to_seconds()
t1 = MyTime(10,50,30)
t2 = MyTime(14,55,23)
t3 = MyTime(11,12,12)
print(t3.between(t1, t2))
print(t2 > t1)
t1.increment(10)
print(t1)
t1.increment(-20)
print(t1.seconds == 20)
print(t1)
t1.increment(-30)
print(t1)
print(str(t1) == "10:49:50")
t1.increment(3600)
print(t1)
print(str(t1) == "11:49:50")
| true |
deeae0a00e50fc1a9c01290b8c6c2a72a71d94b5 | ajaysurya8888/TCS-DCA-Solutions | /NinjaToDigital_14.py | 1,465 | 4.25 | 4 | def getMinimumOperations(first, second):
# to keep track of the minimum number of operations required
count = 0
# `i` and `j` keep track of the current characters' index in the
# first and second strings, respectively
# start from the end of the first and second string
i = len(first) - 1
j = i
while i >= 0:
# if the current character of both strings doesn't match,
# search for `second[j]` in substring `first[0,i-1]` and
# increment the count for every move
while i >= 0 and first[i] != second[j]:
i = i - 1
count = count + 1
i = i - 1
j = j - 1
# return the minimum operations required
return count
# Function to determine if the first string can be transformed into
# the second string
def isTransformable(first, second):
# if the length of both strings differs
if len(first) != len(second):
return False
first.sort()
second.sort()
# return true if both strings have the same set of characters
return first == second
if __name__ == '__main__':
first = "MORNING"
second = "BRING"
if isTransformable(list(first), list(second)):
print("The minimum operations required to convert the String", first,
"to string", second, "are", getMinimumOperations(first, second))
else:
print("The string cannot be transformed") | true |
a5fc6ecca491828a5596ea51b470c9f0b66ed9a8 | qamarilyas/Demo | /bubbleSort.py | 365 | 4.125 | 4 |
def bubbleSort(lst):
for i in range(len(lst)-1): # outer loop run from index 0 to len(lst)
for j in range((len(lst)-i)-1): # inner loop run from index 0 to omitting i values
if(lst[j]>lst[j+1]):
lst[j],lst[j+1]=lst[j+1],lst[j] # swap each time if second value is greater
print(lst)
lst=[5,7,3,11,9,2]
bubbleSort(lst) | false |
b59e2b9181d503af377c936c7a3764a4b7bc7b70 | robertpullin/utilities | /point_generation/random_coordinates.py | 2,902 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 20 10:04:24 2021
@author: RP
"""
import random
def generate_random_coordinate(min_lat=-90,max_lat=90,min_lon=-180,max_lon=180,precision=6,seed=None):
"""Generate a random coordinate of defined precision within bounds.
Parameters
----------
min_lat : float (optional)
minimum latitude in decimal degrees
max_lat : float (optional)
maximum latitude in decimal degrees
min_lon : float (optional)
minimum longitude in decimal degrees
max_lat : float (optional)
maximum longitude in decimal degrees
precision : int (optional)
number of digits to round to after decimal
seed : int (optional)
if set to int, sets random.seed(seed)
Returns
-------
coord : tuple
tuple of form (latitude,longitude)
"""
if(isinstance(seed,int)):
random.seed(seed)
latitude = round(random.uniform(min_lat,max_lat),precision)
longitude = round(random.uniform(min_lon,max_lon),precision)
coord = (latitude,longitude)
return coord
def generate_random_coordinates(n,min_lat=-90,max_lat=90,min_lon=-180,max_lon=180,precision=6,seed=None):
"""Generate a list of n random coordinates of defined precision within bounds.
Parameters
----------
n : int
number of coordinates to generate
min_lat : float (optional)
minimum latitude in decimal degrees
max_lat : float (optional)
maximum latitude in decimal degrees
min_lon : float (optional)
minimum longitude in decimal degrees
max_lat : float (optional)
maximum longitude in decimal degrees
precision : int (optional)
number of digits to round to after decimal
seed : int (optional)
if set to int, sets random.seed(seed)
Returns
-------
coords : list
list of tuple of form (latitude,longitude)
"""
if(isinstance(seed,int)):
random.seed(seed)
coords = [generate_random_coordinate(min_lat=min_lat,
max_lat=max_lat,
min_lon=min_lon,
max_lon=max_lon,
precision=precision) for c in range(0,n)]
return coords
def coords_to_lat_lon_lists(coords):
"""Converts a list of coordinates in tuple form (latitude,longitude) to a list of latitudes and a list of longitudes.
Parameters
----------
coords : list(tuple)
a list of coordinates in tuple form (latitude,longitude)
Returns
-------
lats : list
list of latitudes in input order
lons : list
list of longitudes in input order
"""
lats = [c[0] for c in coords]
lons = [c[1] for c in coords]
return lats,lons | true |
d98fc309ba7e0b05832d6f8284128d83ef9a9b33 | mertzjl91/PythonProjects | /rockpaperscissors.py | 1,393 | 4.15625 | 4 | import random
n = random.randint(1,3)
turn = input("Rock, paper, scissors, shoot! \nMake your move!:")
while True:
if ((turn == "rock" or turn == "Rock") and int(n) == 1) or ((turn == "paper" or turn == "Paper") and int(n) == 2) or ((turn == "scissors" or turn == "Scissors") and int(n) == 3):
print("It is a tie! Try again!")
n = random.randint(1,3)
turn = input("Make your move:")
elif (turn == "rock" or turn == "Rock") and int(n) == 2:
print("Sorry, you lose, I've got paper!")
break
elif (turn == "rock" or turn == "Rock") and int(n) == 3:
print("Congratulations! You won! I had scissors!")
break
elif (turn == "paper" or turn == "Paper") and int(n) == 1:
print("Congratulations! You won! I had rock!")
break
elif (turn == "paper" or turn == "Paper") and int(n) == 3:
print("Sorry, you lose, I've got scissors!")
break
elif (turn == "scissors" or turn == "Scissors") and int(n) == 1:
print("Sorry, you lose, I've got rock!")
break
elif (turn == "scissors" or turn == "Scissors") and int(n) == 2:
print("Congratulations! You won! I had paper")
break
else:
print("Whoops! It looks like you spelled something wrong!")
turn = input("Make sure you enter rock, paper, or scissors:")
| true |
d09d3306845ed3dbe513affe30279af12565edd7 | starrycherry/CMUProject | /Mypython/src/lesson6/practice.py | 2,765 | 4.125 | 4 | '''
Created on Nov 27, 2012
@author: Cherrie
'''
class Overload:
def __init__(self,name):
pass
# def __init__(self,first,second):
pass
a=Overload("a")
#b=Overload("b","c")
#class BankAccount:
# def __init__(self, initial_balance=0):
# """Creates an account with the given balance."""
# self.account=initial_balance
# self.fee=0
#
# def deposit(self, amount):
# """Deposits the amount into the account."""
# self.account+=amount
#
# def withdraw(self, amount):
# """Withdraws the amount from the account. Each withdrawal resulting in a negative balance also deducts a fee of 5 dollars from the balance."""
# self.fee+=5
# self.account=self.account-amount-5
#
# def get_balance(self):
# """Returns the current balance in the account."""
# return self.account
#
# def get_fees(self):
# """Returns the total fees ever accrued in the account."""
# return self.fee
#
#my_account = BankAccount(10)
#my_account.withdraw(5)
#my_account.deposit(10)
#my_account.withdraw(5)
#my_account.withdraw(15)
#my_account.deposit(20)
#my_account.withdraw(5)
#my_account.deposit(10)
#my_account.deposit(20)
#my_account.withdraw(15)
#my_account.deposit(30)
#my_account.withdraw(10)
#my_account.withdraw(15)
#my_account.deposit(10)
#my_account.withdraw(50)
#my_account.deposit(30)
#my_account.withdraw(15)
#my_account.deposit(10)
#my_account.withdraw(5)
#my_account.deposit(20)
#my_account.withdraw(15)
#my_account.deposit(10)
#my_account.deposit(30)
#my_account.withdraw(25)
#my_account.withdraw(5)
#my_account.deposit(10)
#my_account.withdraw(15)
#my_account.deposit(10)
#my_account.withdraw(10)
#my_account.withdraw(15)
#my_account.deposit(10)
#my_account.deposit(30)
#my_account.withdraw(25)
#my_account.withdraw(10)
#my_account.deposit(20)
#my_account.deposit(10)
#my_account.withdraw(5)
#my_account.withdraw(15)
#my_account.deposit(10)
#my_account.withdraw(5)
#my_account.withdraw(15)
#my_account.deposit(10)
#my_account.withdraw(5)
#print my_account.get_balance(), my_account.get_fees()
print [1,2]+[3]
def test(a):
n=a
numbers=[i for i in range(2,n)]
results=[]
while len(numbers)>0:
results.append(numbers[0])
j=1
while j<len(numbers):
if numbers[j]%numbers[0]==0 and j!=i:
numbers.pop(j)
j+=1
numbers.pop(0)
return len(results)
print test(5000)
def question8():
slow=1000
fast=1
year=0
while slow>=fast:
slow=slow*2
fast=fast*2
slow=slow*(1-0.4)
fast=fast*(1-0.3)
year+=1
return year
print question8()
| true |
bd401546a352d628c5b76490250f9195176431f0 | codebubb/python_course | /Semester 1/Project submissions/Lewis Clarke/Lewis_Clarke_Python_Coding-2016-04-18/Python Coding/Week 7/file_reader.py | 2,211 | 4.3125 | 4 | from collections import Counter
f = """So far we've encountered two ways of writing values
expression statements and the print statement. (A third way
is using thewri te() method of file objects; the standard output
file can be referenced as sys.stdout. See the Library Reference for
more information on this.)Often you'll want more control over the
formatting of your output than simply printing space-separated values.
There are two ways to format your output; the first way is to do all
the string handling yourself; using string slicing and concatenation
operations you can create any layout you can imagine. The string types
have some methods that perform useful operations for padding strings to
a given column width; these will be discussed shortly. The second way is
to use the str.format() method.The string module contains a Template
class which offers yet another way to substitute values into strings.One
question remains, of course: how do you convert values to strings? Luckily,
Python has ways to convert any value to a string: pass it to the repr()
or str() functions.The str() function is meant to return representations
of values which are fairly human-readable, while repr() is meant to generate
representations which can be read by the interpreter (or will force a
SyntaxError if there is no equivalent syntax).For objects which don't have
a particular representation for human consumption, str() will return the same
value as repr(). M any values, such as numbers or structures like lists
and dictionaries, have the same representation using either function. Strings
and floating point numbers, in particular, have two distinct representations"""
print ('The number of words in this file are'), len(f.split())
numbers = sum(c.isdigit() for c in f)
chars = sum(c.isalpha() for c in f)
print ('In this document there are'), numbers, ('numbers')
print ('In this document there are'), chars, ('Characters')
count = {}
unique = []
for w in f.split():
if w in count:
count[w] += 1
else:
count[w] = 1
for word, times in count.items():
if times == 1:
unique.append(word)
print ('In this document there is'), len(unique),('Unique Words')
| true |
71c628e8a5bc5f4866ab231e64020571e1f3a78c | codebubb/python_course | /Semester 1/Project submissions/Andreas Georgiou/Semester 1 - Introduction to Programming/Semester 1 - Introduction to Programming/Week 7/Practice/time moduled practise.py | 361 | 4.125 | 4 | # Unix epoch is a set date in time; Thursday, 1 January 1970 (the current date)
# Unix time is the number of seconds that has passed since this date
import time
print time.time() # prints unix time
print time.strftime("%H:%M:%S") # prints formated time
print time.strftime("%d/%m/%y") # prints formated date
print time.strftime("%d/%m/%y , %H:%M:%S")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.