blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
0423a1f2927e6d4ea4a16578801e4f237d0cda6d
|
20040116/Learning-experience-of-python
|
/Day02(2021.07.07)_Class.py
| 2,588
| 4.40625
| 4
|
###类的基础学习
###书上的例子
###属性:类中的形参和实参 方法:类中的具体函数
###将一个类作为另一个类的属性
class Wheel():
def __init__(self, maker, size):
self.maker = maker
self.size = size
def wheel_description(self):
print("This wheel is " + str(self.size) + " maked by " + self.maker)
class Car():
'''模拟汽车的简单尝试'''
def __init__(self, make, model, year, maker, size):
self.make = make
self.model = model
self.year = year
self.maker = maker
self.size = size
self.odometer_reading = 0
self.gas_tank = 50
self.wheel = Wheel(self.maker, self.size) ###将Wheel类作为Car类的一个属性
def get_descriptive(self):
long_name = self.make + ' ' + self.model + ' ' + str(self.year)
return long_name.title()
'''修改属性的值'''
def update_odometer(self, mileage):
self.odometer_reading = mileage
print('当前里程数为' + str(self.odometer_reading))
def increment_odometer(self, miles):
self.odometer_reading += miles ###mileage和miles为外部形参
print('当前里程数为' + str(self.odometer_reading))
def fill_gas_tank(self):
print("This car's gas tank is " + str(self.gas_tank))
###类的继承
###子类继承父类的所有属性和方法,同时可以定义自己的属性和方法
###父类必须包含在当前文件中,且位于子类的前面
class ElectricCar(Car):
'''对Car类的继承'''
def __init__(self, make, model, year, maker, size): ###初始化父类的属性
super().__init__(make, model, year, maker, size) ###super()是一个特殊函数,帮助父类和子类关联起来
self.battery_size = 100
'''给子类定义属性和方法'''
def describe_battery(self):
print('Battery size is ' + str(self.battery_size))
'''重写父类的方法'''
def fill_gas_tank(self):
print("This car has no gas tank") ###改写父类中的函数,调用时忽略父类的同名函数
my_car = Car('audi', 'a4', 2021, "maker1", 20)
print(my_car.get_descriptive())
my_car.update_odometer(1000)
my_car.increment_odometer(100)
my_car.fill_gas_tank()
my_car.wheel.wheel_description()
my_byd_car = ElectricCar('BYD', "秦", 2021, "maker2", 30)
print(my_byd_car.get_descriptive())
my_byd_car.describe_battery()
my_byd_car.fill_gas_tank()
my_byd_car.wheel.wheel_description()
| false
|
f0fb1d24bbeffbc40fbfed97db945a69ffd9a6a1
|
AlexSR2590/curso-python
|
/07-ejercicios/ejercicio1.py
| 433
| 4.3125
| 4
|
"""
Ejercicio 1
-Crear dos variables "pais" y "continente"
-Mostrar el valor por pantalla (imprimir)
-imprimir el tipo de dato de las dos variables
"""
pais = input("Introduce un país: ")
continente = input("Introduce un continente: ")
print("Pais: ", pais)
print("Tipo de dato de la variable pais: ")
print(type(pais))
print("Continente: ",continente)
print("Tipo de dato de la variable continente: ")
print(type(continente))
| false
|
1a9900260ede8d1f9fa50622b31f2244ff70d858
|
AlexSR2590/curso-python
|
/11-ejercicios/ejercicio1.py
| 1,774
| 4.28125
| 4
|
"""
Hcaer un programa que tenga una lista de 8 numeros enteros
y hacer lo siguiente:
- Recorrer la lista y mostrarla
- Ordenar la lista y mostrarla
- Mostrar su longitud
- Bucar algun elemento que el usuario pida por teclado
"""
numeros = [1, 9, 4, 2, 30, 7, 28, 18]
#Recorrer la lista y mostrarla (función)
print("Recorrer la lista y mostrarla")
def recorrerLista(lista):
resultado = ""
for numero in lista:
resultado += "\n" + str(numero)
return resultado
print(recorrerLista(numeros))
print("------------------------\n")
#Ordernar la lista y mostrarla (función)
print("Ordenar lista")
def ordernarLista(lista):
lista.sort()
return lista
print(ordernarLista(numeros))
print("------------------------\n")
#Mostrar longitud de la lista
print("Mostar longitud de la lita")
print(len(numeros))
print("------------------------\n")
#Buscar algún elemento que pida el usuario
print("Buscar elemento en la lista\n")
encontrado = False
def buscarElemento(lista, encontrar):
if encontrar in lista:
return True
else:
return False
while encontrado == False:
encontrar = int(input("¿Qué número quieres buscar?: "))
encontrado = buscarElemento(numeros, encontrar)
if encontrado == False:
print("Número no encontrado en la lista\n")
else:
print("Número encontrado en la lista en el índice: ")
print(numeros.index(encontrar))
"""
print("Buscar elemento en la lista")
busqueda = int(input("Introduce un número: "))
comprobar = isinstance(busqueda, int)
while not comprobar or busqueda <= 0:
busqueda = int(input("introduce un númro: "))
else:
print(f"Has introducido el {busqueda}")
print(f"#### Buscar en la lista el número {busqueda} #####")
search = numeros.index(busqueda)
print(f"El número buscado existe en el indice: {search}")
"""
| false
|
08af65139899c28b6e118af7f9c15ecfda947611
|
AlexSR2590/curso-python
|
/03-operadores/aritmeticos.py
| 446
| 4.125
| 4
|
#Operadores aritmeticos
numero1 =77
numero2 = 44 #Operador asignación =
resta = numero1 - numero2
multiplicacion = numero1 * numero2
division = numero1 / numero2
resto = numero1 % numero2
print("***********Calculadora*************")
print(f"La resta es: {resta}" )
print(f"La suma es: {numero1 + numero2} ")
print("La multiplicacion es: ", multiplicacion)
print("La divison es: ", division)
print("El resto de numero1 / numero2 es: ", resto)
| false
|
01f42ded2480038227e1d492193c9a1dbb3395bf
|
Chih-YunW/Leap-Year
|
/leapYear_y.py
| 410
| 4.1875
| 4
|
while True:
try:
year = int(input("Enter a year: "))
except ValueError:
print("Input is invalid. Please enter an integer input(year)")
continue
break
if (year%4) != 0:
print(str(year) + " is not a leap year.")
else:
if(year%100) != 0:
print(str(year) + " is a leap year.")
else:
if(year%400) == 0:
print(str(year) + " is a leap year.")
else:
print(str(year) + " is not a leap year.")
| true
|
999579d8777c53f7ab91ebdcc13b5c76689f7411
|
ayushmohanty24/python
|
/asign7.2.py
| 682
| 4.1875
| 4
|
"""
Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values
"""
fname = input("Enter file name: ")
try:
fh = open(fname)
except:
print("File doesn't exist")
quit()
total=0
count=0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
count=count+1
finding=line.find(':')
number=line[finding+1:].strip()
num=float(number)
total=total+num
average=total/count
print("Average spam confidence:",average)
| true
|
adfa2df9495c4631f0d660714a2d130bfedd9072
|
jni/interactive-prog-python
|
/guess-the-number.py
| 2,010
| 4.15625
| 4
|
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
def initialize_game():
global secret_number, rangemax, guesses_remaining, guesses_label
rangemax = 100
guesses_remaining = 7
new_game()
# helper function to start and restart the game
def new_game():
global secret_number, rangemax, guesses_remaining, guesses_label
secret_number = random.randrange(rangemax)
if rangemax == 100:
guesses_remaining = 7
else:
guesses_remaining = 10
# define event handlers for control panel
def range100():
global rangemax
rangemax = 100
new_game()
print 'The secret number is now in [0, 100).'
def range1000():
global rangemax
rangemax = 1000
new_game()
print 'The secret number is now in [0, 1000).'
def input_guess(guess):
global secret_number, guesses_remaining, guesses_label
guess = int(guess)
print 'Your guess was %i' % guess
guesses_remaining -= 1
guesses_label.set_text('Guesses remaining: %i' % guesses_remaining)
if guess < secret_number:
print '... and it was too low.'
elif guess > secret_number:
print '... and it was too high.'
else:
print '... and BOOM. You got it.'
new_game()
if guesses_remaining == 0:
print 'You ran out of guesses! Starting a new game.'
print '(The secret number was %i.)' % secret_number
new_game()
# create frame
initialize_game()
frame = simplegui.create_frame('Guess the number', 200, 200)
# register event handlers for control elements and start frame
frame.add_input('Enter guess:', input_guess, 50)
frame.add_button('New game in [0, 100)', range100, 100)
frame.add_button('New game in [0, 1000)', range1000, 100)
guesses_label = frame.add_label('Guesses remaining: %i' %
guesses_remaining)
# call new_game
new_game()
frame.start()
| true
|
5fd5b964582057ac930249378e9b944ac1b31bc0
|
raghav1674/graph-Algos-In-Python
|
/Recursion/05/StairCaseTraversal.py
| 393
| 4.15625
| 4
|
def max_ways_to_reach_staircase_end(staircase_height, max_step, current_step=1):
if staircase_height == 0 or current_step == 0:
return 1
elif staircase_height >= current_step:
return max_ways_to_reach_staircase_end(
staircase_height-current_step, max_step, current_step-1) + staircase_height//current_step
print(max_ways_to_reach_staircase_end(10, 2))
| true
|
a4a7c7db2d8fbfb5649f831e832190e719c499c6
|
phos-tou-kosmou/python_portfolio
|
/euler_project/multiples_of_three_and_five.py
| 1,459
| 4.34375
| 4
|
def what_are_n():
storage = []
container = 0
while container != -1:
container = int(input("Enter a number in which you would like to find multiples of: "))
if container == -1: break
if type(container) is int and container not in storage:
storage.append(container)
elif container in storage:
print("You have already entered this number, please enter all positive unique integer values")
else:
print("You must enter a valid integer that is postive")
return storage
def __main__():
# what_are_n() will return an array of integers
main_storage = what_are_n()
# next we will take a user input for what number they would
# like to find the summation of all multiples from storage
n = int(input("What number would you like to find the multiples of? : "))
final_arr = []
'''This will loop through n and enter a second for loop that will check
the mod of each element in final_arr. We are able to break once finding
an element because duplicates would skew the outcome. Once one number mods
n, then any other mod that equals 0 is arbitrary to that i'''
for i in range(0,n):
for j, fac in enumerate(main_storage):
if i % fac == 0:
final_arr.append(i)
break
final = sum(final_arr)
print(final)
if __name__ == "__main__":
pass
__main__()
| true
|
eec09d1b8c6506de84400410771fcdeb6fe73f73
|
StephenTanksley/hackerrank-grind-list
|
/problem-solving/extra_long_factorials.py
| 950
| 4.5625
| 5
|
"""
The factorial of the integer n, written n!, is defined as:
n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1
Calculate and print the factorial of a given integer.
Complete the extraLongFactorials function in the editor below. It should print the result and return.
extraLongFactorials has the following parameter(s):
n: an integer
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the extraLongFactorials function below.
# Memoization here isn't strictly necessary, but I wanted to practice writing out a memoization feature.
def memo(f):
table = {}
def helper(x):
if x not in table:
table[x] = f(x)
return table[x]
return helper
@memo
def extraLongFactorials(n):
product = 1
for i in range(1, n+1):
product *= i
print(product)
if __name__ == '__main__':
n = int(input())
extraLongFactorials(n)
| true
|
706fe7a6d67d4df85a66c25d952ef7cc2d6ba6d3
|
jamiepg1/GameDevelopment
|
/examples/python/basics/fibonacci.py
| 277
| 4.1875
| 4
|
def fibonacci (n):
""" Returns the Fibonacci number for given integer n """
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-2) + fibonacci(n-1)
n = 25
for i in range(n):
result = fibonacci(i)
print "The fibonacci number for ", i, " is ", result
| false
|
34c6867e4dc393cdcf455a09701e906b48cf5f5e
|
solitary-s/python-learn
|
/list/tuple.py
| 329
| 4.15625
| 4
|
# 元组 不可以修改 类似字符串
tuple1 = tuple(range(1, 10))
print(tuple1)
# ,逗号才是元组的标识
temp1 = (1)
print(type(temp1)) # <class 'int'>
temp2 = (1,)
print(type(temp2)) # <class 'tuple'>
# 元组的更新和删除,通过切片拼接
temp = (1, 2, 4)
temp = temp[:2] + (3,) + temp[2:]
print(temp)
| false
|
cf8e0b2ce24068f60f4c4cb056e2baa57cae3f8f
|
solitary-s/python-learn
|
/dict/dict.py
| 479
| 4.125
| 4
|
# 字典
dict1 = {'1': 'a', '2': 'b', '3': 'c'}
print(dict1)
print(dict1['2'])
# 空字典
empty = {}
print(type(empty))
# 创建
dict((('F', 70), ('i', 105)))
dict(one=1, two=2, three=3)
# 内置方法
# 用来创建并返回一个新的字典
dict2 = {}
dict2 = dict2.fromkeys((1, 2, 3), ('one', 'two', 'three'))
print(dict2)
# keys(), values() 和 items()
dict3 = {}
dict3 = dict3.fromkeys(range(10), 'good')
print(dict3.keys())
print(dict3.values())
print(dict3.items())
| false
|
cfa8ff6a920cfbf24b950c8f47e8e109b52d2fde
|
Arpita-Mahapatra/Python_class
|
/List_task.py
| 1,074
| 4.15625
| 4
|
'''a=[2,5,4,8,9,3] #reversing list
a.reverse()
print(a)''' #[3, 9, 8, 4, 5, 2]
'''a=[1,3,5,7,9] #deleting element from list
del a[1]
print(a)''' #[1, 5, 7, 9]
'''a=[6,0,4,1] #clearing all elements from list
a.clear()
print(a)''' #o/p : []
'''n = [1, 2, 3, 4, 5] #mean
l = len(n)
nsum = sum(n)
mean = nsum / l
print("mean is",mean)''' #o/p: mean is 3.0
'''n=[6,9,4,3,1] #median
n.sort()
l=int(len(n)/2)
median=n[l]
print(median)''' #O/P : 4
'''n=[2,6,4,9,3] #avg of first, middle,last elements
l=int(len(n)/2)
avg= (n[0]+n[l]+n[-1])/3
print(avg)''' #O/P : 3.0
'''a=[[1,2,3],4,5,6,[8,9],[[44,55,66],[66,77],["Hello","Python","Welcome"]]]
print(a[5][2][2][3:])''' #print "come"
'''a=[[1,2,3],4,5,6,[8,9],[[44,55,66],[66,77],["Hello","Python","Welcome"]]]
print(a[5][2][2])''' #o/p: Welcome
'''a=[[1,2,3],4,5,6,[8,9],[[44,55,66],[66,77],["Hello","Python","Welcome"]]]
print(a[5][2][1][1:4])''' #o/p:yth
a=[[1,2,3],4,5,6,[8,9],[[44,55,66],[66,77],["Hello","Python","Welcome"]]]
print(a[5][2][1:]) #o/p:['Python', 'Welcome']
| false
|
aad85067c090c60b6095d335c6b9a0863dd76311
|
dpolevodin/Euler-s-project
|
/task#4.py
| 820
| 4.15625
| 4
|
#A palindromic number reads the same both ways.
#The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
num_list = []
result = []
# Create a list with elements multiplied by each other
for i in range(100,1000):
for j in range(100,1000):
num_list.append(i * j)
word_list_str = map(str, num_list)
# Find palindrom in list and add it in new list
for element in word_list_str:
element_reverse = ''.join(reversed(element))
if element == element_reverse:
result.append(element_reverse)
# Sort list to find max value in palindromic numbers
fin_result = list(map(int, result))
fin_result.sort()
# Print max palindromic number
print('Max palindrom is: ', fin_result[-1])
| true
|
41b6ee22ddfb9f6ad0d6dc18d0ec4e5bf1e0bb43
|
anagharumade/Back-to-Basics
|
/BinarySearch.py
| 827
| 4.125
| 4
|
def BinarySearch(arr, search):
high = len(arr)
low = 0
index = ((high - low)//2)
for i in range(len(arr)):
if search > arr[index]:
low = index
index = index + ((high - low)//2)
if i == (len(arr)-1):
print("Number is not present in the input array.")
else:
pass
elif search < arr[index]:
high = index
index = (high - low)//2
if i == (len(arr)-1):
print("Number is not present in the input array.")
else:
pass
else:
if arr[index] == search:
print("Number found at position: ", index)
break
if __name__ == "__main__":
arr = [1,2,3,4,5,6,7,8,9,12]
BinarySearch(arr, 7)
| true
|
3967fad907d30a59282306b168bfd3fa032bfaa9
|
mootfowl/dp_pdxcodeguild
|
/python assignments/lab10_unit_converter_v3.py
| 1,466
| 4.34375
| 4
|
'''
v3 Allow the user to also enter the units.
Then depending on the units, convert the distance into meters.
The units we'll allow are inches, feet, yards, miles, meters, and kilometers.
'''
def number_crunch():
selected_unit = input("Pick a unit of measurement: inches, feet, yards, miles, meters, or kilometers. > ")
selected_number = float(input("And now pick a number. > "))
if selected_unit == 'inches':
conversion = selected_number * 0.0254
print(f"{selected_number} {selected_unit} is equal to {conversion} meters.")
number_crunch()
elif selected_unit == 'feet':
conversion = selected_number * 0.3048
print(f"{selected_number} {selected_unit} is equal to {conversion} meters.")
number_crunch()
elif selected_unit == 'yards':
conversion = selected_number * 0.9144
number_crunch()
elif selected_unit == 'miles':
conversion = selected_number * 1609.34
print(f"{selected_number} {selected_unit} is equal to {conversion} meters.")
number_crunch()
elif selected_unit == 'meters':
conversion = selected_number
print(f"{selected_number} {selected_unit} is equal to {conversion} meters. DUH.")
number_crunch()
elif selected_unit == 'kilometers':
conversion = selected_number / 1000
print(f"{selected_number} {selected_unit} is equal to {conversion} meters.")
number_crunch()
number_crunch()
| true
|
d900cef1d0915808b0b213a6339636bf2dd3dcd2
|
mootfowl/dp_pdxcodeguild
|
/python assignments/lab15_ROT_cipher_v1.py
| 971
| 4.15625
| 4
|
'''
LAB15: Write a program that decrypts a message encoded with ROT13 on each character starting with 'a',
and displays it to the user in the terminal.
'''
# DP note to self: if a = 1, ROT13 a = n (ie, 13 letters after a)
# First, let's create a function that encrypts a word with ROT13...
alphabet = 'abcdefghijklmnopqrstuvwxyz '
key = 'nopqrstuvwxyzabcdefghijklm '
def encrypt(word):
encrypted = ''
for letter in word:
index = alphabet.find(letter) # returns the alphabet index of the corresponding letter
encrypted += (key[index]) # prints the rot13 letter that correlates to the alphabet index
return encrypted
def decrypt(encrypted_word):
decrypted = ''
for letter in encrypted_word:
index = key.find(letter)
decrypted += (alphabet[index])
return decrypted
secret_sauce = input("Type in a word > ")
print(encrypt(secret_sauce))
not_so_secret_sauce = input("Type in an encrypted word > ")
print(decrypt(not_so_secret_sauce))
| true
|
858422c01e9d9390216773f08065f38a124cb579
|
monicaneill/PythonNumberGuessingGame
|
/guessinggame.py
| 1,724
| 4.46875
| 4
|
#Greetings
print("Hi there! Welcome to Monica's first coding project, 'The Python Number Guessing Game'!")
print("Let's see if you can guess the number in fewer steps than the computer openent. Let's begin!")
#Computer Function
def computerGuess(lowval, highval, randnum, count=0):
if highval >= lowval:
guess = lowval + (highval - lowval) // 2
# If guess is in the middle, it is found
if guess == randnum:
return count
#If 'guess' is greater than the number it must be
#found in the lower half of the set of numbers
#between the lower value and the guess.
elif guess > randnum:
count = count + 1
return computerGuess(lowval, guess-1, randnum, count)
#The number must be in the upper set of numbers
#between the guess and the upper value
else:
count + 1
return computerGuess(guess + 1, highval, randnum, count)
else:
#Number not found
return -1
#End of function
#Generate a random number between 1 and 100
import random
randnum = random.randint(1,101)
count = 0
guess = -99
while (guess != randnum):
#Get the user's guess
guess = (int) (input("Enter your guess between 1 and 100:"))
if guess < randnum:
print("You need to guess higher")
elif guess > randnum:
print("Not quite! Try guessing lower")
else:
print("Congratulations! You guessed right!")
break
count = count + 1
#End of while loop
print("You took " + str(count) + " steps to guess the number")
print("The computer guessed it in " + str(computerGuess(0,100, randnum)) + " steps")
| true
|
0a517656681efc1b179ca047ed54e2e210567824
|
tnaswin/PythonPractice
|
/Aug18/recursive.py
| 406
| 4.21875
| 4
|
def factorial(n):
if n <= 1:
return 1
else:
return n * (factorial(n - 1))
def fibonacci(n):
if n <= 1:
return n
else:
return (fibonacci(n - 1) + (fibonacci(n - 2)))
n = int(raw_input("Enter a number: "))
if n <= 0:
print("Plese enter a positive integer")
else:
print "Factorial: ", factorial(n)
print "Fibonacci: ",
for i in range(n):
print(fibonacci(i)),
| false
|
0e5c69430dcddf93721e19e55a54d131394ca452
|
montoyamoraga/nyu-itp
|
/reading-and-writing-electronic-text/classes/class_02/cat.py
| 2,211
| 4.125
| 4
|
# import sys library
import sys
# this is a foor loop
#stdin refers to the lines that are input to the program
#typical python styling is indenting with four spaces
for line in sys.stdin:
#strip() removes whitespace at the end of the line
#strip() is a method of a line object
line = line.strip()
if "you" in line:
#print prints to the console
print line
# python follows the pemdas order of precedence
## stands for parenthesis, exponents, multiplication, addition, substraction
#this is a string variable
tofu = "delicious"
#this is for printing it to the screen
#notice that this it doesn't include quotes
print tofu
#to check the length of the string, use len()
print len("ok thx bye")
#operator in has two arguments, one to the left and one to the right
#it returns True if the string on the left can be found on the one to the right
#and False otherwise
print "foo" in "buffoon"
print "foo" in "reginald"
#strings have the method startswith that returns True or False
#if the string on the argument is found on the original string
#it is case-sensitive
print "tofu".startswith("to")
print "tofu".startswith("soy")
#ther is an analog method called endswith, to check for endings
print "tofu".endswith("fu")
print "tofu".endswith("soy")
#the find() method looks for a string inside of another string
#it returns the position in the string where it found the first match
#return -1 if nothing is found
print "tofu".find("u")
print "tofu".find("x")
#the lower() method evaluates to lowercase and upper() to uppercase
#they don't change the original value, they return the evaluated value
#most python functionalities don't affect the original one
#there is also titlecase, with method title()
print "tofu is awesome".lower()
print "tofu is awesome".upper()
print "tofu is awesome".title()
# the strip() method removes at beginning and end
print " t o f u yeah ".strip()
#the replace method replaces the first argument for the second argument
#in the original string,
print "what up, this is weird weird oh no".replace("i", "o");
#string indexing
#you can access subsets of the strings with [i:j]
#where i and j stand from ith to (j-1)th character
| true
|
47c9f72baa7577f726046a80f338e40fd199bb61
|
montoyamoraga/nyu-itp
|
/reading-and-writing-electronic-text/assignments/assignment_04/this.py
| 2,031
| 4.1875
| 4
|
#assignment 04
#for class reading and writing electronic text
#at nyu itp taught by allison parrish
#by aaron montoya-moraga
#february 2017
#the digital cut-up, part 2. write a program that reads in and creatively re-arranges the content of several source texts. what is the unit of your cut-up technique? (the word, the line, the character? something else?) how does your procedure relate (if at all) to your choice of source text? feel free to build on your assignment from last week. your program must make use of at least one set or dictionary. choose one text that you created with your program to read in class.
#my program takes two texts, lyrics for two different songs (javiera plana's invisible and flaming lips' bad days) and remixes them taking different random words from each of them, producing
#import sys, random and string module
from os import system
import random
import string
# read files
text01 = open("./text_original_01.txt").read()
text02 = open("./text_original_02.txt").read()
#split the texts in lists with all of the words
list01 = text01.split()
list02 = text02.split()
#construct a set of every word in the texts
set01 = set()
set02 = set()
for word in list01:
set01.add(word)
for word in list02:
set02.add(word)
#construct a dictionary with words as keys and number of times in values
dict01 = dict()
dict02 = dict()
for word in list01:
if word in dict01:
dict01[word] += 1
else:
dict01[word] = 1
for word in list02:
if word in dict02:
dict02[word] += 1
else:
dict02[word] = 1
for i in range(10):
#empty string for the current line
currentLine = ""
#make a random decision
decision = random.randint(1,2)
if decision == 1:
word = random.choice(dict01.keys())
for i in range(dict01[word]):
currentLine = currentLine + word + " "
elif decision == 2:
word = random.choice(dict02.keys())
for i in range(dict02[word]):
currentLine = currentLine + word + " "
print currentLine
| true
|
e7f50e19dbf531b0af4ae651759d714278aac06b
|
ribeiroale/rita
|
/rita/example.py
| 498
| 4.21875
| 4
|
def add(x: float, y: float) -> float:
"""Returns the sum of two numbers."""
return x + y
def subtract(x: float, y: float) -> float:
"""Returns the subtraction of two numbers."""
return x - y
def multiply(x: float, y: float) -> float:
"""Returns the multiplication of two numbers."""
return x * y
def divide(x: float, y: float) -> float:
"""Returns the division of two numbers."""
if y == 0:
raise ValueError("Can not divide by zero!")
return x / y
| true
|
299cc5fc729fef69fea8e96cd5e72344a1aa3e12
|
voyeg3r/dotfaster
|
/algorithm/python/getage.py
| 1,075
| 4.375
| 4
|
#!/usr/bin/env python3
# # -*- coding: UTF-8 -*-"
# ------------------------------------------------
# Creation Date: 01-03-2017
# Last Change: 2018 jun 01 20:00
# this script aim: Programming in Python pg 37
# author: sergio luiz araujo silva
# site: http://vivaotux.blogspot.com
# twitter: @voyeg3r
# ------------------------------------------------
"""
One frequent need when writing interactive console applications is to obtain
an integer from the user. Here is a function that does just that:
This function takes one argument, msg . Inside the while loop the user is prompt-
ed to enter an integer. If they enter something invalid a ValueError exception
will be raised, the error message will be printed, and the loop will repeat. Once
a valid integer is entered, it is returned to the caller. Here is how we would
call it:
"""
def get_int(msg):
while True:
try:
i = int(input(msg))
return i
except ValueError as err:
print(err)
age = get_int("Enter your age ")
print("Your age is", age)
| true
|
d9eddfd175dd379bd8453f908a0d8c5abeef7a29
|
bbullek/ProgrammingPractice
|
/bfs.py
| 1,536
| 4.1875
| 4
|
''' Breadth first traversal for binary tree '''
# First, create a Queue class which will hold nodes to be visited
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
return self.queue.pop(0)
def isEmpty(self):
return len(self.queue) == 0
# Define a Node class that holds references to L/R children, value, and 'visited' boolean
class Node:
def __init__(self, value = None):
self.value = value
self.left = None
self.right = None
self.visited = False
# Define a Binary Tree class full of nodes
class BinTree:
def __init__(self):
self.root = None
# Now the BFS algorithm
def BFS(root):
if root is None: # Edge case where we're passed a null ref
return
queue = Queue() # Initialize queue
root.visited = True
queue.enqueue(root)
while queue.isEmpty() == False:
v = queue.dequeue() # Some node containing a value
print(v.value)
# for all vertices adjacent to v...
if v.left is not None and v.left.visited == False:
v.left.visited = True
queue.enqueue(v.left)
if v.right is not None and v.right.visited == False:
v.right.visited = True
queue.enqueue(v.right)
# The main function where everything comes together
def main():
tree = BinTree()
# Populate the tree with nodes
tree.root = Node(50)
tree.root.left = Node(20)
tree.root.right = Node(30)
tree.root.left.left = Node(10)
tree.root.left.right = Node(5)
tree.root.right.left = Node(3)
# Perform BFS to visit the nodes of this tree
BFS(tree.root)
main()
| true
|
17f30d9b41e3bac84534424877c3fc81791ef755
|
jibachhydv/bloomED
|
/level1.py
| 498
| 4.15625
| 4
|
# Get the Number whose index is to be returned
while True:
try:
num = int(input("Get Integer: "))
break
except ValueError:
print("Your Input is not integer")
# List of Number
numbers = [3,6,5,8]
# Function that return index of input number
def returnIndex(listNum, num):
for i in range(len(listNum)):
if listNum[i] == num:
return i
return -1
# Run the Function
print(f"Index of {num} in {numbers} is {returnIndex(numbers, num)}")
| true
|
e4a48078d125102f2a154d5c7cf387b0f087b7a8
|
ScroogeZhang/Python
|
/day03字符串/04-字符串相关方法.py
| 1,185
| 4.21875
| 4
|
# 字符串相关方法的通用格式:字符串.函数()
# 1.capitalize:将字符串的首字母转换成大写字母,并且创建一个新的字符返回
str1 = 'abc'
new_str = str1.capitalize()
print(new_str)
# 2.center(width,fillerchar):将原字符串变成指定长度并且内容居中,剩下的部分使用指定的(字符:长度为1的字符串)填充
new_str = str1.center(7,'!')
print(str1,new_str)
# 3.rjust(width,fillerchar)
new_str = str1.rjust(7,'*')
print(new_str)
number = 19 # py1805009
#str(数据):将其他任何的数据转换成字符串
num_str = str(number)
print(num_str, type(num_str))
# 让字符串变成宽度为3,内容右对齐,剩下部分使用'0'填充
new_str = num_str.rjust(3, '0')
print(new_str)
new_str = 'py1805' + new_str
print(new_str)
# 4.ljust(width,fillerchar):左对齐
str1 = 'py1805'
new_str = str1.ljust(10, '0')
print(new_str)
new_str = new_str + num_str
print(new_str)
# 5.字符串1.join(字符串2): 在字符串2中的每个字符间插入一个字符串1
new_str = '123'.join('bbb')
print(new_str)
print('---------------')
# 6.maketrans()
new_str = str.maketrans('abc', '123')
print(new_str)
| false
|
61cc074563240c4e6f6835b1bf6be450b76956a9
|
ScroogeZhang/Python
|
/day04 循环和分支/04-while循环.py
| 951
| 4.1875
| 4
|
# while循环
'''
while 条件语句:
循环体
其他语句
while:关键字
条件语句: 结果是True,或者False
循环体:重复执行的代码段
执行过程:判断条件语句是否为True,如果为True就执行循环体。
执行完循环体,再判断条件语句是否为True,如果为True就在执行循环体....
直到条件语句的值为False,循环结束,直接执行while循环后面的语句
注意:如果条件语句一直都是True,就会造成死循环。所以在循环体要有让循环可以结束的操作
python 中没有do-while 循环
'''
# 死循环
# while True:
# print('aaa')
flag = True
while flag:
print('aaa')
flag = False
#使用while 循环计算1到100的和:
sum1 = 0
count = 1
while count <= 100:
sum1 += count
count += 1
print(sum1)
#练习: 计算100以内偶数的和
sum1 = 0
count = 0
while count <= 100:
sum1 += count
count += 2
print(sum1)
#
| false
|
79c4584eb2cae10c882162f315f213dcaa734949
|
ScroogeZhang/Python
|
/day03字符串/05-if语句.py
| 1,131
| 4.5
| 4
|
# if语句
# 结构:
# 1.
# if 条件语句:
# 条件语句为True执行的代码块
#
# 执行过程:先判断条件语句是否为True,
# 如果为True就执行if语句后:后面对应的一个缩进的所有代码块
# 如果为False,就不执行冒号后面的一个缩进中的代码块,直接执行后续的其他语句
#
# 条件语句:可以使任何有值的表达式,但是一般是布尔值
#
#
# if : 关键字
if True:
print('代码1')
print('代码2')
print('代码3')
print('代码4')
# 练习:用一个变量保存时间(50米短跑),如果时间小于8秒,打印及格
time = 7
if time < 8:
print('及格') # 只有条件成立的时候才会执行
print(time) #不管if语句的条件是否,这个语句都会执行
'''
if 条件语句:
语句块1
else:
语句块2
执行过程:先判断条件语句是否为True,如果为True就执行语句块1,否则就执行语句块2
练习:用一个变量保存成绩,如果成绩大于等于60,打印及格,否则打印不及格
'''
score = 70
if score >= 60:
print('及格')
else:
print('不及格')
| false
|
fca406d84960938a40a1d2216983f2c07efa374e
|
Suraj-S-Patil/Python_Programs
|
/Simple_Intrst.py
| 246
| 4.125
| 4
|
#Program to calculate Simple Interest
print("Enter the principal amount, rate and time period: ")
princ=int(input())
rate=float(input())
time=float(input())
si=(princ*rate*time)/100
print(f"The simple interest for given data is: {si}.")
| true
|
d552de01cad51b019587300e6cf5b7cbc5d3122f
|
Cherol08/finance-calculator
|
/finance_calculators.py
| 2,713
| 4.40625
| 4
|
import math
#program will ask user if they want to calculate total investment or loan amount
option = """ Choose either 'investment' or 'bond' from the menu below to proceed:\n
Investment - to calculate the amount of interest you'll earn on interest
Bond - to calculate the amount you'll have to pay on a home loan\n """
print(option)
choice = input("Enter option:\t").lower() # lower method used to convert input to lowercase characters
# while loop used if user doesn't enter either of the 2 options specified, program will keep asking
# user to enter correct option. if user does enter either option
#break statement will discontinue the loop and continue with the next statement
while (choice != "investment") and (choice != "bond"):
print("Invalid option.\n")
choice = input("Enter option:\t").lower()
if (choice == "investment") or (choice == "bond"):
break
# if user chooses investment, program will ask user to enter the following values:
# P- principal investment amount, r - interest rate, t - time planned to invest in years
# and the type of interest they'd like to use. The conditional statement executed if user chooses investment,
# will calculate user's investment depending on the type of interest user chooses.
# A- total investment amount with interest. Each outcome is rounded off to 2 decimal places
if choice == "investment":
P = float(input("Enter amount to deposit:\t"))
r = float(input("Enter the percentage of interest rate:\t"))
t = int(input("Enter number of years planned to invest:\t"))
interest = input("Simple or compound interest:\t").lower()
if interest == "simple":
A = round(P*(1+r*t), 2) #simple interest formula
print(f"\nThe total amount of your investment with simple interest is R{A}")
elif interest == "compound":
A = round(P*math.pow((1+r), t), 2) #compund interest formula
print(f"\nThe total amount of your investment with compound interest is R{A}")
# if user chooses bond, program will ask user for the following values:
# p-present value amount, i-interest rate, n -number of months to repay bond
# x - the total bond repayment per month
#the final answer is rounded of to two decimal places and displayed
elif choice == "bond":
bond = True
p = float(input("Enter present value of the house:\t"))
i = float(input("Enter the percentage of interest rate:\t"))
if i:
i = i/12 #interest in the bond formula is divided by 12
n = int(input("Enter period planned to repay the bond(in months):\t"))
x = round((i*p)/(1 - math.pow((1+i), -n)), 2) #bond formula
print(f"\nThe total bond repayment is R{x} per month")
| true
|
462321abc830736f71325221f81c4f5075dd46fb
|
amithjkamath/codesamples
|
/python/lpthw/ex21.py
| 847
| 4.15625
| 4
|
# This exercise introduces 'return' from functions, and hence daisy-chaining them.
# Amith, 01/11
def add(a, b):
print "Adding %d + %d" % (a,b)
return a + b
def subtract(a, b):
print "Subtracting %d - %d" % (a,b)
return a - b
def multiply(a,b):
print "Multiplying %d * %d" % (a,b)
return a*b
def divide(a,b):
print "Dividing %d / %d" % (a,b)
return a/b
print "Let's do some math with just functions!"
age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
# Example of how "string %x" % variable is combined with "string", variable, "string again" ...
print "Age: %d, Height: %d, Weight:" % (age, height), weight, ", IQ: %d" % iq
print "Here's a puzzle"
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, " Can you do it by hand?"
| true
|
923177e67d9afe32c3bcc738a8726234c5d08ad2
|
CTRL-pour-over/Learn-Python-The-Hard-Way
|
/ex6.py
| 758
| 4.5
| 4
|
# Strings and Text
# This script demonstrates the function of %s, %r operators.
x = "There are %d types of people." % 10
binary = "binary" # saves the string as a variable
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not) # inserting variables ()
# here's where we print out our variables ^^^
print x
print y
print "I said: %r." % x # prints
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
# % hilarious becomes the missing variable for joke_evaluation
print joke_evaluation % hilarious
# more assigning strings to variables. will be used later
w = "This is the left side of..."
e = "a string with a right side"
# below is where we print the obove variables (w, e)
print w + e
| true
|
568c69be02b59df5d2c531bb707be680fc5efa77
|
CTRL-pour-over/Learn-Python-The-Hard-Way
|
/ex29.py
| 1,080
| 4.65625
| 5
|
# What If
# The if statements, used in conjunction with the > , < operators will print
# the following text if True.
# In other words, ( if x is True: print "a short story" )
# Indentation is needed for syntax purpouses. if you do not indent you will get
# "IndentationError: expected an indented block".
# If you do not create a colon after the new block of code is declared,
# you will get a SyntaxError: invalid syntax.
people = 20
cats = 30
dogs = 15
if people < cats and 1 == 1: # Prints first
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs and "test" != "testing": # Prints second
print "The world is dry!"
dogs += 5 # "increment by" operator. This is the same as 15 + 5 = 20
if people >= dogs: # Prints third
print "People are greater than or equal to dogs."
if people <= dogs: # Prints fourth
print "People are less than or equal to dogs."
if (not people != dogs): # Prints fifth
print "People are dogs."
| true
|
46554c75d2000a673d11d628b5921831bec87b74
|
CTRL-pour-over/Learn-Python-The-Hard-Way
|
/ex15.py
| 944
| 4.25
| 4
|
# Reading Files
# this file is designed to open and read a given file as plain text
# provide ex15.py with an argument (file) and it will read it to you
# then it will as for the filename again, you can also give it a different file.
from sys import argv
# here is how we can give an additional argument when trying to run the script (insert read file)
script, filename = argv
# line 8 doesnt actually open the file to the user. this is under the hood.
txt = open(filename)
# line 11 is how we actually read the file to the user. but first you must open it.
print "Here's your file %r:" % filename
print txt.read()
# here is where we ask for the filename again and assign it to a variable (file_again)
print "Type the filename again:"
file_again = raw_input("> ")
# here is how we open the new file in the directory
txt_again = open(file_again)
# here is how we actually print or read() the second file txt_again.read()
print txt_again.read()
| true
|
2ca7c4e31ad857f80567942a0934d9399a6da033
|
zoeyangyy/algo
|
/exponent.py
| 600
| 4.28125
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Time : 2018/8/16 下午10:27
# @Author : Zoe
# @File : exponent.py
# @Description :
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
result = base
if exponent == 0:
return 1
elif exponent > 0:
for i in range(exponent-1):
result *= base
return result
else:
for i in range(-exponent-1):
result *= base
return 1/result
c = Solution()
print(c.Power(2,-3))
| true
|
36d281d594ec06a38a84980ca15a5087ccb2436a
|
connor-giles/Blackjack
|
/hand.py
| 847
| 4.125
| 4
|
"""This script holds the definition of the Hand class"""
import deck
class Hand:
def __init__(self):
self.cards = [] # A list of the current cards in the user's hand
self.hand_value = 0 # The actual value of the user's hand
self.num_aces = 0 # Keeps track of the number of aces that the user has
def __len__(self):
return len(self.cards)
def add_card(self, new_card):
self.cards.append(new_card)
self.hand_value += deck.values[new_card.rank]
if new_card.rank == 'Ace':
self.num_aces += 1
def adjust_for_ace(self):
# If the users hand value is greater than 21 but the user still has an ace, you need to re-adjust the hand value
while self.hand_value > 21 and self.num_aces:
self.hand_value -= 10
self.num_aces -= 1
| true
|
6b16f67a76c4951b641d252d40a1931552381975
|
by46/geek
|
/codewars/4kyu/52e864d1ffb6ac25db00017f.py
| 2,083
| 4.1875
| 4
|
"""Infix to Postfix Converter
https://www.codewars.com/kata/infix-to-postfix-converter/train/python
https://www.codewars.com/kata/52e864d1ffb6ac25db00017f
Construct a function that, when given a string containing an expression in infix notation,
will return an identical expression in postfix notation.
The operators used will be +, -, *, /, and ^ with standard precedence rules and
left-associativity of all operators but ^.
The operands will be single-digit integers between 0 and 9, inclusive.
Parentheses may be included in the input, and are guaranteed to be in correct pairs.
to_postfix("2+7*5") # Should return "275*+"
to_postfix("3*3/(7+1)") # Should return "33*71+/"
to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+"
c++ to_postfix("2+7*5") # Should return "275*+" to_postfix("3*3/(7+1)")
# Should return "33*71+/" to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+"
You may read more about postfix notation, also called Reverse Polish notation,
here: http://en.wikipedia.org/wiki/Reverse_Polish_notation
"""
ORDERS = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3,
'(': 0,
')': 4
}
def to_postfix(infix):
"""Convert infix to postfix
>>> to_postfix("2+7*5")
'275*+'
>>> to_postfix("3*3/(7+1)")
'33*71+/'
>>> to_postfix("5+(6-2)*9+3^(7-1)")
'562-9*+371-^+'
>>> to_postfix("(5-4-1)+9/5/2-7/1/7")
'54-1-95/2/+71/7/-'
"""
stack = []
result = []
for c in infix:
if c.isdigit():
result.append(c)
elif c == '(':
stack.append(c)
elif c == ')':
while stack[-1] != '(':
result.append(stack.pop())
stack.pop()
else:
while stack and ORDERS[stack[-1]] >= ORDERS[c]:
result.append(stack.pop())
stack.append(c)
if stack:
result.extend(reversed(stack))
return ''.join(result)
if __name__ == '__main__':
import doctest
doctest.testmod()
| true
|
81cfaff6e7ed2ac0be013d2439592c4fb8868e63
|
apugithub/Python_Self
|
/negetive_num_check.py
| 355
| 4.15625
| 4
|
# Negetive number check
def check(num):
return True if (num<0) else False
print(check(-2))
### The function does check and return the negatives from a list
lst = [4,-5,4, -3, 23, -254]
def neg(lst):
return [num for num in lst if num <0]
# or the above statement can be written as= return sum([num < 0 for num in nums])
print(neg(lst))
| true
|
8f27badfdef2487c0eb87e659fac64210faa1646
|
gaylonalfano/Python-3-Bootcamp
|
/card.py
| 767
| 4.125
| 4
|
# Card class from deck of cards exercise. Using for unit testing section
# Tests: __init__ and __repr__ functions
from random import shuffle
class Card:
available_suits = ("Hearts", "Diamonds", "Clubs", "Spades")
available_values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
def __init__(self, suit, value):
if suit not in Card.available_suits:
raise ValueError # (f"{suit} is not a valid suit.")
elif str(value) not in Card.available_values:
raise ValueError # (f"{value} is not a valid value.")
else:
self.suit = suit
self.value = value
def __repr__(self):
return "{} of {}".format(self.value, self.suit) # f"{self.value} of {self.suit}"
| true
|
6bcb51fae80c295f98d6004344c5ffec1028f602
|
gaylonalfano/Python-3-Bootcamp
|
/infinite_generators_get_multiples.py
| 649
| 4.21875
| 4
|
# def get_multiples(number=1, count=10):
# for i in range(1, count+1):
# yield number*i
#
# evens = get_multiples(2, 3)
# print(next(evens))
# print(next(evens))
# print(next(evens))
# print(next(evens))
# GET_UNLIMITED_MULTIPLES EXERCISE:
def get_unlimited_multiples(number=1):
next_num = number
while True:
yield next_num
next_num += number
# Student's example with *
# def get_unlimited_multiples(num=1):
# next_num = 1
# while True:
# yield num*next_num
# next_num += 1
fours = get_unlimited_multiples(4)
print(next(fours))
print(next(fours))
print(next(fours))
print(next(fours))
| true
|
c68446d2fa042a3c279654f3937c16d632bf2420
|
gaylonalfano/Python-3-Bootcamp
|
/decorators_logging_wraps_metadata.py
| 2,667
| 4.40625
| 4
|
"""
Typical syntax:
def my_decorator(fn):
def wrapper(*args, **kwargs):
# do stuff with fn(*args, **kwargs)
pass
return wrapper
Another tutorial example: https://www.youtube.com/watch?v=swU3c34d2NQ
from functools import wraps
import logging
logging.basicConfig(filename='example.log', level=logging.INFO)
def logger(func):
@wraps(func)
def log_func(*args):
logging.info(f"Running {func.__name__} with arguments {args}")
print(func(*args))
return log_func
@logger # With Decorator
def add(x, y):
return x+y
@logger # With Decorator
def sub(x, y):
return x-y
# WITH DECORATOR??? Not sure with add since it's built-in...
add(3, 3)
add(4, 5)
sub(10, 5)
sub(20, 10)
# WITHOUT DECORATOR:
add_logger = logger(add)
sub_logger = logger(sub)
add_logger(3, 3) # 6
add_logger(4, 5) # 9
sub_logger(10, 5) # 5
sub_logger(20, 10) # 10
# **NEXT** Open the file example.log to see log results
"""
# USING WRAPS TO PRESERVE METADATA - LOGGING FUNCTION DATA
# def log_function_data(fn):
# def wrapper(*args, **kwargs):
# """I'm a WRAPPER function""" # This is the doc string __doc__
# print(f"You are about to call {fn.__name__}")
# print(f"Here's the documentation: {fn.__doc__}")
# return fn(*args, **kwargs)
# return wrapper
#
# @log_function_data
# def add(x,y):
# """Adds two numbers together."""
# return x+y
#
# print(add(10, 30)) # PROBLEM WITH ADD FUNCTION!
# print(add.__doc__) # ALL referring to WRAPPER instead! NOT GOOD!
# print(add.__name__)
# help(add)
'''
SOLUTION - Module called functools with WRAPS FUNCTION!
wraps is simply a function we use to wrap around our wrapper function.
It ensures that the metadata of the functions that get decorated are
not lost by the decorator. So, for example, if you decorate @ add or len,
you won't lose the original metadata for those functions.
from functools import wraps
# wraps preserves a function's metadata
# when it is decorated!
def my_decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# do some stuff with fn(*args, **kwargs)
pass
return wrapper
'''
from functools import wraps
def log_function_data(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
"""I'm a WRAPPER function""" # This is the docstring __doc__
print(f"You are about to call {fn.__name__}")
print(f"Here's the documentation: {fn.__doc__}")
return fn(*args, **kwargs)
return wrapper
@log_function_data
def add(x,y):
"""Adds two numbers together."""
return x+y
print(add(10, 30))
print(add.__doc__)
print(add.__name__)
help(add)
| true
|
0fa247aef355f85a8a00d44357933f418038c91d
|
gaylonalfano/Python-3-Bootcamp
|
/debugging_pdb.py
| 1,790
| 4.1875
| 4
|
'''
Python Debugger (pdb) -- To set breakpoints in our code we can use pdb by inserting this line:
def function(params):
import pdb; pdb.set_trace() - Usually added/imported like this inside a function
*Rest of code*
Usually placed right before something starts breaking. Allows you to see a preview of what happens before/after.
Pdb Commands:
l (list)
n (next line)
a all values
p (print)
c (continue - finishes debugging by running the rest of the code)
NOTE - If you have parameters/variable names that are any of these above COMMANDS,
then you need to type: "p [variable name]" to print the value of that var. Ex. p c #
'''
# import pdb
#
#
# first = 'First'
# second = 'Second'
# pdb.set_trace()
# result = first + second
# third = 'Third'
# result += third
# print(result)
# def add_numbers(a, b, c, d):
# import pdb; pdb.set_trace()
#
# return a + b + c + d
#
# add_numbers(1, 2, 3, 4)
# DIVIDE() - two params num1, num2. If you don't pass the correct amount of args
# it should say "Please provided two integers or floats". If num2 == 0, should
# raise a ZeroDivisionError, so return string "Please do not divide by zero"
def divide(num1, num2):
try:
return num1/num2
except TypeError:
print("Please provide two integers or floats")
except ZeroDivisionError:
print("Please do not divide by zero")
# def divide2(num1):
# import pdb; pdb.set_trace()
# if type(num1) != int or type(num1) != float:
# raise TypeError("Please provide two integers or floats")
# # elif num2 == 0:
# # raise ZeroDivisionError("Please do not divide by zero")
# else:
# print(num1)
# divide(4, 2)
# divide([], "1")
# divide(1, 0)
# divide2('1', '2')
# divide2(4, '1')
# divide2([], 0)
divide2(5)
| true
|
9c309fa1bc6df7bf3d6e6b7ed047df45eb670316
|
gaylonalfano/Python-3-Bootcamp
|
/sorted.py
| 1,583
| 4.5625
| 5
|
'''
sorted - Returns a new sorted LIST from the items in iterable (tuple, list, dict, str, etc.)
You can also pass it a reverse=True argument.
Key difference between sorted and .sort() is that .sort() is a list-only method and returns the
sorted list in-place. sorted() accepts any type of iterable. Good for sorted on a key in dictionaries, etc.
'''
more_numbers = [6, 1, 8, 2]
sorted(more_numbers) # [1, 2, 6, 8]
print(more_numbers)
print(sorted(more_numbers, reverse=True))
sorted((2, 1, 45, 23, 99))
users = [
{'username': 'samuel', 'tweets': ['I love cake', 'I love pie']},
{'username': 'katie', 'tweets': ["I love my cat"], "color": "purple"},
{'username': 'jeff', 'tweets': []},
{'username': 'bob123', 'tweets': [], "num": 10, "color": "green"},
{'username': 'doggo_luvr', 'tweets': ["dogs are the best"]},
{'username': 'guitar_gal', 'tweets': []}
]
# sorted(users) # Error message. Need to specify on what you want to sort on
print(sorted(users, key=len)) # default is ascending
print(sorted(users, key=lambda user: user['username'])) # 'bob123', 'doggo_luvr', etc.
# Sort based off of who has the most tweets
print(sorted(users, key=lambda user: len(user['tweets']), reverse=True)) # Ascending default. 0 tweets > 2 tweets
# List of songs w/ playcount. How to sort based on playcount?
songs = [
{'title': 'happy birthday', 'playcount': 1},
{'title': 'Survive', 'playcount': 6},
{'title': 'YMCA', 'playcount': 99},
{'title': 'Toxic', 'playcount': 31}
]
print(sorted(songs, key=lambda song: song['playcount'], reverse=True))
| true
|
f6c7ea3bf3080757bd268ee0b701e6c29c0d584f
|
gaylonalfano/Python-3-Bootcamp
|
/interleaving_strings_zip_join.py
| 686
| 4.3125
| 4
|
'''
Write a function interleave() that accepts two strings. It should return a new string containing
the two strings interwoven or zipped together. For example:
interleave('hi', 'ha') # 'hhia'
interleave('aaa', 'zzz') # 'azazaz'
interleave('lzr', 'iad') # 'lizard'
'''
def interleave(str1, str2):
return ''.join(
map(
lambda i: i[0] + i[1],
zip(str1, str2)
)
)
def interleave(str1, str2):
return ''.join(map(lambda i: i[0]+i[1], zip(str1, str2)))
# Instructor's code:
def interleave2(str1, str2):
return ''.join(''.join(x) for x in (zip(str1, str2)))
print(interleave('aaa', 'zzz'))
print(interleave('lzr', 'iad'))
| false
|
a5668f587fe9b9b26b70afd0e7bf97bc317c35b3
|
gaylonalfano/Python-3-Bootcamp
|
/polymorphism_OOP.py
| 1,806
| 4.3125
| 4
|
'''
POLYMORPHISM - A key principle in OOP is the idea of polymorphism - an object can take
on many (poly) forms (morph). Here are two important practical applications:
1. Polymorphism & Inheritance - The same class method works in a similar way for different classes
Cat.speak() # meow
Dog.speak() # woof
Human.speak() # Yo
A common implementation of this is to have a method in a base (or parent) class that is
overridden by a subclass. This is called METHOD OVERRIDING. If other people on a team
want to write their own subclass methods, this is useful.
class Animal:
def speak(self):
raise NotImplementedError("Subclass needs to implement this method")
class Dog(Animal):
def speak(self):
return "woof"
class Cat(Animal):
def speak(self):
return "meow"
class Fish(Animal):
pass
d = Dog()
print(d.speak())
f = Fish()
print(f.speak()) # NotImplementedError: Subclass needs to implement this method - need a speak()
2. Special Methods (__dunder__ methods, etc) - The same operation works for different kinds of objects:
sample_list = [1, 2, 3]
sample_tuple = (1, 2, 3)
sample_string = "awesome"
len(sample_list)
len(sample_tuple)
len(sample_string)
8 + 2 = 10
"8" + "2" = "82"
Python classes have special (aka "magic") methods that are dunders. These methods with special
names that give instructions to Python for how to deal with objects.
'''
class Animal:
def speak(self):
raise NotImplementedError("Subclass needs to implement this method")
class Dog(Animal):
def speak(self):
return "woof"
class Cat(Animal):
def speak(self):
return "meow"
class Fish(Animal):
pass
d = Dog()
print(d.speak())
f = Fish()
print(f.speak()) # NotImplementedError: Subclass needs to implement this method - need a speak()
| true
|
79c42425fad9a2049934a8208d0b8cf9ca9b0a08
|
gaylonalfano/Python-3-Bootcamp
|
/custom_for_loop_iterator_iterable.py
| 1,648
| 4.4375
| 4
|
# Custom For Loop
'''
ITERATOR - An object that can be iterated upon. An object which returns data,
ONE element at a time when next() is called on it. Think of it as anything we can
run a for loop on, but behind the scenes there's a method called next() working.
ITERABLE - An object which will return an ITERATOR when iter() is called on it.
IMPORTANT: A list is also just an iterable. The list is actually never directly
looped over. What actually happens is the for loop calls iter("HELLO"), which
returns the iterator that is then the loop will call next() on that iterator
over and over again until it hits the end!
UNDERSTAND THE ITER() AND NEXT() METHODS
ITER() - Returns an iterator object.
NEXT() - When next() is called on an iterator, the iterator returns the next ITEM.
It keeps doing so until it raises a StopIteration error. It's actually using a
try/except block until it reaches the end and raises the StopIteration error.
'''
def my_for(iterable, func):
iterator = iter(iterable)
while True:
# Need to add in try/except block to stop error from displaying to user
try:
# Would be nice to add some functionality to it (sum, mul, etc.) other than just print
# print(next(iterator))
i = next(iterator)
func(i)
except StopIteration:
# print("End of loop")
break
# else: Another syntax is to do the func() call in the else statement
# func(i)
def square(x):
print(x**2) # If you only use RETURN, then it won't PRINT
#my_for("hello")
my_for([1, 2, 3, 4], square) # 1, 4, 9, 16
my_for('lol', print)
| true
|
2e9cde6ddaf45706eb646ec7404d22a851430e3f
|
gaylonalfano/Python-3-Bootcamp
|
/dundermethods_namemangling.py
| 1,096
| 4.5
| 4
|
# _name - Simply a convention. Supposed to be "private" and not used outside of the class
# __name - Name Mangling. Python will mangle/change the name of that attribute. Ex. p._Person__lol to find it
# Used for INHERITANCE. Python mangles the name and puts the class name in there for inheritance purposes.
# Think of hierarchy (Person > [Teacher, Cop, Coach, Student, etc.]). Teacher could also have self._Teacher__lol
# __name__ - Don't go around making your own __dunder__ methods
class Person:
def __init__(self):
self._secret = 'hi!'
self.name = 'Tony'
self.__msg = "I like turtles"
self.__lol = "hahahaha"
# In other programming languages to make private do:
# private self._secret = "hi!"
# def doorman(self, guess):
# if guess == self._secret:
# let them in
p = Person()
print(p.name)
print(p._secret)
# print(p.__msg) # AttributeError: 'Person' object has no attribute '__msg'
print(dir(p)) # list ['_Person__msg', '_Person_lol', '__class__', '__delattr__', ...]
print(p._Person__msg)
print(p._Person__lol)
| true
|
15dbca45f3fbb904d3f747d4f165e7dbca46c684
|
XavierKoen/cp1404_practicals
|
/prac_01/loops.py
| 924
| 4.5
| 4
|
"""
Programs to display different kinds of lists (numerical and other).
"""
#Basic list of odd numbers between 1 and 20 (inclusive).
for i in range(1, 21, 2):
print(i, end=' ')
print()
#Section a: List counting in 10s from 0 to 100.
for i in range(0, 101, 10):
print(i, end=' ')
print()
#Section b: List counting down from 20 to 1.
for i in range(1, 21):
j = 21 - i
print(j, end=' ')
print()
#Section c: Print number of stars (*) desired on one line.
number_of_stars = int(input("Number of stars: "))
for i in range(1, number_of_stars + 1):
print("*",end="")
print()
#Section d: Print desired number of lines of stars (*) with increasing number of stars in each line.
# Beginning with one and finishing with desired number.
number_of_stars = int(input("Number of stars: "))
for i in range(1, number_of_stars + 1):
for j in range(1, i + 1):
print("*",end="")
print()
print()
| true
|
e1e5bdeab07475e95a766701d6feb6e14fe83494
|
XavierKoen/cp1404_practicals
|
/prac_02/password_checker.py
| 2,067
| 4.53125
| 5
|
"""
CP1404/CP5632 - Practical
Password checker code
"""
MIN_LENGTH = 2
MAX_LENGTH = 6
SPECIAL_CHARS_REQUIRED = False
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\"
def main():
"""Program to get and check a user's password."""
print("Please enter a valid password")
print("Your password must be between {} and {} characters, and contain:".format(MIN_LENGTH, MAX_LENGTH,))
print("\t1 or more uppercase characters")
print("\t1 or more lowercase characters")
print("\t1 or more numbers")
if SPECIAL_CHARS_REQUIRED:
print("\tand 1 or more special characters: {}".format(SPECIAL_CHARACTERS))
password = input("> ")
while not is_valid_password(password):
print("Invalid password!")
password = input("> ")
print("Your {}-character password is valid: {}".format(len(password), password))
def is_valid_password(password):
"""Determine if the provided password is valid."""
# Establish counter variables.
count_lower = 0
count_upper = 0
count_digit = 0
count_special = 0
# If length is wrong, return False.
if MIN_LENGTH <= len(password) <= MAX_LENGTH:
# Count each character using str methods.
for char in password:
count_lower = count_lower + int(char.islower())
count_upper = count_upper + int(char.isupper())
count_digit = count_digit + int(char.isdigit())
# Return False if any are zero.
if count_lower == 0 or count_upper == 0 or count_digit == 0:
return False
else:
# Count special characters from SPECIAL_CHARACTERS string if required.
# Return False if count_special is zero.
if SPECIAL_CHARS_REQUIRED:
for char in password:
count_special = count_special + int(char in SPECIAL_CHARACTERS)
if count_special == 0:
return False
else:
return False
# If we get here (without returning False), then the password must be valid.
return True
main()
| true
|
72a5f79be816896fcdfbab8dd0a54f1588d25551
|
jeremyyew/tech-prep-jeremy.io
|
/code/topics/1-searching-and-sorting/M148-sorted-list.py
| 1,589
| 4.125
| 4
|
Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def sortList(self, head):
pass
# Iterative mergesort function to
# sort arr[0...n-1]
def mergeSort(self, head):
current_size = 1
left = head
while left:
left = head
while left:
mid = left + current_size - 1
right = len(a) - 1 if 2 * current_size + left - 1 > len(a)-1 else 2 * current_size + left - 1
mergeTwoLists(a, left, mid, right)
left = left.next
current_size = 2 * current_size
# Merge Function
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
node = ListNode(None)
head = node
while True: # better than a termination condition, because its tricky to refactor the code to pop the list for the next iteration to check, when you can't keep a reference to which list you want to pop at the end.
print(node.val)
if l1 is None and l2 is None:
return
# there is at least one non-None
if l1 is None or l2 is None:
if l1 is None:
some = l2
else:
some = l1
node.next = some
return head.next
# both are non-None
if l1.val < l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
return head.next
| true
|
5ccb88df6a21f7a105c7c08d2551412c4cc307bb
|
sachin1005singh/complete-python
|
/python_program/findvowel.py
| 218
| 4.28125
| 4
|
#vowels program use of for loop
vowel = "aeiouAEIOU"
while True:
v = input("enter a vowel :")
if v in vowel:
break
print("this in not a vowel ! try again !!")
print("thank you")
| true
|
74a079f8a0c40df56f5412dd4723cb2368b3759a
|
kartsridhar/Problem-Solving
|
/halindrome.py
| 1,382
| 4.25
| 4
|
"""
Given a string S. divide S into 2 equal parts S1 and S2. S is a halindrome if
AT LEAST one of the following conditions satisfy:
1. S is a palindrome and of length S >= 2
2. S1 is a halindrome
3. S2 is a halindrome
In case of an odd length string, S1 = [0, m-1] and S2 = [m+1, len(s)-1]
Example 1:
input: harshk
output: False
Explanation 1:
S does not form a palindrome
S1 = har which is not a halindrome
S2 = shk which is also not a halindrome.
None are true, so False.
Example 2:
input: hahshs
output: True
Explanation 2:
S is not a palindrome
S1 = hah which is a palindrome
S2 = shs which is also a palindrome
Example 3:
input: rsrabdatekoi
output: True
Explanation 3:
rsrabd, atekoi
Neither are palindromic so you take each word and split again
Break down rsrabd coz it's not palindromic,
rsr, abd.
rsr length is >=2 and is a palindrome hence it's true
"""
def splitString(s):
return [s[0:len(s)//2], s[len(s)//2:]] if len(s) >= 2 else []
def checkPalindrome(s):
return s == s[::-1] if len(s) >= 2 else False
def checkHalindrome(s):
print(s)
if checkPalindrome(s):
return True
else:
splits = splitString(s)
if len(splits) == 0:
return False
else:
for i in splits:
return checkHalindrome(i)
return False
inputs = 'rsrabdatekoi'
print(checkHalindrome(inputs))
| true
|
408d751896467c077d7dbc1ac9ffe6239fed474d
|
kartsridhar/Problem-Solving
|
/HackerRank/Problem-Solving/Basic-Certification/unexpectedDemand.py
| 1,630
| 4.40625
| 4
|
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'filledOrders' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY order
# 2. INTEGER k
#
"""
A widget manufacturer is facing unexpectedly high demand for its new product,. They would like to satisfy as many customers as possible. Given a number of widgets available and a list of customer orders, what is the maximum number of orders the manufacturer can fulfill in full?
Function Description
Complete the function filledOrders in the editor below. The function must return a single integer denoting the maximum possible number of fulfilled orders.
filledOrders has the following parameter(s):
order : an array of integers listing the orders
k : an integer denoting widgets available for shipment
Constraints
1 ≤ n ≤ 2 x 105
1 ≤ order[i] ≤ 109
1 ≤ k ≤ 109
Sample Input For Custom Testing
2
10
30
40
Sample Output
2
"""
def filledOrders(order, k):
# Write your code here
total = 0
for i, v in enumerate(sorted(order)):
if total + v <= k:
total += v
else:
return i
else:
return len(order)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
order_count = int(input().strip())
order = []
for _ in range(order_count):
order_item = int(input().strip())
order.append(order_item)
k = int(input().strip())
result = filledOrders(order, k)
fptr.write(str(result) + '\n')
fptr.close()
| true
|
914c7c8db0d3d316d22d899ba6756368ae4eb392
|
pythonmite/Daily-Coding-Problem
|
/problem_6_medium.py
| 514
| 4.1875
| 4
|
"""
Company Name : DropBox
Problem Statement : Find the second largest element in the list. For example: list :[2,3,5,6,6]
secondlargestelement >>> [5]
"""
def findSecondLargestNum(arr:list):
max = arr[0]
for num in arr:
if num > max:
max = num
secondlargest = 0
for num in arr:
if num > secondlargest and num < max:
secondlargest = num
return secondlargest
arr = [2,3,5,6,6]
answer = findSecondLargestNum(arr)
print(answer)
# >>> 5
| true
|
de1515c2150e80505cca6fbec738b38bc896487f
|
KarenRdzHdz/Juego-Parabolico
|
/parabolico.py
| 2,756
| 4.34375
| 4
|
"""Cannon, hitting targets with projectiles.
Exercises
1. Keep score by counting target hits.
2. Vary the effect of gravity.
3. Apply gravity to the targets.
4. Change the speed of the ball.
Integrantes:
Karen Lizette Rodríguez Hernández - A01197734
Jorge Eduardo Arias Arias - A01570549
Hernán Salinas Ibarra - A01570409
15/09/2021
Exercises marked by ***ejercicio realizado***
"""
"Libraries used"
from random import randrange
from turtle import *
from typing import Sized
from freegames import vector
"Global variables used in game"
ball = vector(-200, -200)
speed = vector(0, 0)
gravity = 25
s = 200
targets = []
count = 0
def changeGravity(value):
"Set gravity to global variable"
global gravity
gravity = value
def changeSpeed(sp): # ***Exercise 4: change speed***
"Set speed to global variable"
global s
s = sp
def tap(x, y):
"Respond to screen tap."
if not inside(ball):
ball.x = -199
ball.y = -199
speed.x = (x + 200) / gravity
speed.y = (y + 200) / gravity
def inside(xy):
"Return True if xy within screen."
return -200 < xy.x < 200 and -200 < xy.y < 200
def draw():
"Draw ball and targets."
clear()
for target in targets:
goto(target.x, target.y)
dot(20, 'blue')
if inside(ball):
goto(ball.x, ball.y)
dot(6, 'red')
update()
def move():
"Move ball and targets."
if randrange(40) == 0:
y = randrange(-150, 150)
target = vector(200, y)
targets.append(target)
for target in targets:
target.x -= 0.5
target.y -= 0.5 # ***Exercise 3: add gravity to targets***
if inside(ball):
speed.y -= 0.35
ball.move(speed)
dupe = targets.copy()
targets.clear()
for target in dupe:
if abs(target - ball) > 13:
targets.append(target)
draw()
"Count balls hit" # ***Exercise 1: count balls hit***
if len(dupe) != len(targets):
global count
diferencia = len(dupe)-len(targets)
count += diferencia
style = ('Courier', 30, 'bold')
write(count, font=style, align='right')
# Game never ends remove condition # ***Exercise 5: Game never ends***
#for target in targets:
#if not inside(target):
#return
ontimer(move, s)
setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
listen()
onkey(lambda: changeGravity(50), 'a') # ***Exercise 2: vary the effect of gravity***
onkey(lambda: changeGravity(25), 's')
onkey(lambda: changeGravity(12), 'd')
onkey(lambda: changeSpeed(100), 'q')
onkey(lambda: changeSpeed(50), 'w')
onkey(lambda: changeSpeed(25), 'e')
onscreenclick(tap)
move()
done()
| true
|
02a01f7bc44fcdb31cef4c4ae58ea0b1ea573326
|
imruljubair/imruljubair.github.io
|
/_site/teaching/material/Functions_getting_started/16.py
| 235
| 4.15625
| 4
|
def main():
first_name = input('Enter First Name: ')
last_name = input('Enter Last Name: ')
print('Reverse: ')
reverse_name(first_name, last_name)
def reverse_name(first, last):
print(last, first)
main()
| false
|
627a95962abed7b46f673bf813375562b3fa1cd2
|
imruljubair/imruljubair.github.io
|
/teaching/material/List/7.py
| 413
| 4.375
| 4
|
# append()
# Example 7.1
def main():
name_list = []
again = 'y'
while again == 'y':
name = input("Enter a name : ")
name_list.append(name)
print('Do you want to add another name ?')
again = input('y = yes, anything else = no: ')
print()
print('The names you have listed: ')
for name in name_list:
print(name)
main()
| true
|
0c110fece3e121665c41b7f1c039c190ed1b7866
|
imruljubair/imruljubair.github.io
|
/teaching/material/List/5.py
| 268
| 4.28125
| 4
|
# Concating and slicing list
# Example 5.1
list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1 + list2
print(list3)
# Example 5.2
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satureday']
mid_days = days[2:5]
print(mid_days)
| true
|
6399bf8b03d1f6ef5a68bec3b6cc8baa26000edc
|
imruljubair/imruljubair.github.io
|
/_site/teaching/material/Functions_getting_started/17.py
| 266
| 4.4375
| 4
|
def main():
first_name = input('Enter First Name: ')
last_name = input('Enter Last Name: ')
N = reverse_name(first_name, last_name)
print('Reverse: '+str(N))
def reverse_name(first, last):
name = last+' '+ first
return name
main()
| false
|
aea3ddf894c253cfe9bcdae7a3878f67bf76a5b7
|
softwaresaved/docandcover
|
/fileListGetter.py
| 1,118
| 4.375
| 4
|
import os
def fileListGetter(directory):
"""
Function to get list of files and language types
Inputs: directory: Stirng containing path to search for files in.
Outputs: List of Lists. Lists are of format, [filename, language type]
"""
fileLists = []
for root, dirs, files in os.walk(directory):
for filename in files:
file_extention = filename.split(".")[-1]
languageType = getLanguageType(file_extention)
filename = os.path.join(root, filename)
fileLists.append([filename, languageType])
return fileLists
def getLanguageType(file_extention):
"""
Function to assign language type based on file extention.
Input: file_extention: String that lists file type.
Output: languageType: string listsing identified language type.
"""
if file_extention == 'py':
return 'python'
else:
return 'Unknown'
def printFileLists(fileLists):
"""
Function to print out the contents of fileLists
Main use is debugging
"""
for fileList in fileLists:
print fileList
| true
|
06371106cc981aac3260a681d2868a4ccf24f5bf
|
Sergey-Laznenko/Coursera
|
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.3(slice)/2.py
| 782
| 4.28125
| 4
|
"""
Дана строка. Если в этой строке буква f встречается только один раз, выведите её индекс.
Если она встречается два и более раз, выведите индекс её первого и последнего появления.
Если буква f в данной строке не встречается, ничего не выводите.
При решении этой задачи нельзя использовать метод count и циклы.
"""
string = input()
first = string.find('f')
revers = string[::-1]
second = len(string) - revers.find('f') - 1
if first == second:
print(first)
elif first == -1 or second == -1:
print()
else:
print(first, second)
| false
|
384785ebd3f0e57cc68ac0cd00389f4bcfd8b245
|
AffanIndo/python-script
|
/caesar.py
| 702
| 4.21875
| 4
|
#!usr/bin/env python
"""
caesar.py
Encrypt or decrypt text based from caesar cipher
Source: http://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python
"""
def caesar(plainText, shift):
cipherText = ""
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print("Your ciphertext is: ", cipherText)
return cipherText
if __name__ == '__main__':
plainText = input("Insert your text:\n")
shift = int(input("Insert how many shift:"))
caesar(plainText, shift)
| true
|
20ffbd80d572fd4b75db8860c04c034cb6d87ab0
|
midephysco/midepython
|
/exercises2.py
| 250
| 4.125
| 4
|
#this is a program to enter 2 numbers and output the remainder
n0 = input("enter a number ")
n1 = input("enter another number")
div = int(n0) / int(n1)
remainder = int(n0) % int(n1)
print("the answer is {0} remainder {1}".format(div, remainder))
| true
|
19665f62b7fa38f9cbc82e17e02dacd6de092714
|
midephysco/midepython
|
/whileloop2.py
| 452
| 4.21875
| 4
|
#continous loop
print("Adding until rogue value")
print()
print("This program adds up values until a rogue values is entered ")
print()
print("it then displays the sum of the values entered ")
print()
Value = None
Total = 0
while Value != 0:
print("The total is: {0}.".format(Total))
print()
Value = int(input("Please enter a value to add to total: "))
Total = Total + Value
print()
print("The final total is: {0}.".format(Total))
| true
|
cdfad3f2a3b8d22c82c203195a5c03ec456111e6
|
VineethChandha/Cylinder
|
/loops.py
| 987
| 4.125
| 4
|
# PY.01.10 introduction to the loops
for a in range(1,11): # a will be valuated from 1 to 10
print("Hi")
print(a)
even_numbers = [x for x in range(1,100) if x%2 == 0]
print(even_numbers)
odd_numbers = [x for x in range(1,100) if x%2 != 0]
print(odd_numbers)
words = ["ram","krishna","sai"]
answer = [[w.upper(),w.lower(),len(w)] for w in words]
print(answer)
word = ["Happy","Birthday","To","You"]
word="-".join(word) #Join key word is used to join the list of the words with some specific sign or space as required
print(word)
Word2 = "Happy Birthday To You"
split_word = Word2.split() #.split() funtion is used to make the sentance to the list of words
print(split_word)
# This brings out the names of friends in which letter a is present
names={"male":["sandeep","rakesh","sudheer",],"female":["sravani","dolly"]}
for gender in names.keys():
for friend in names[gender]:
if "a" in friend:
print(friend)
| true
|
daf4203e12c8e480fe1b6b0b9f1f3e63b2f292fa
|
awanisazizan/awanis-kl-oct18
|
/birthday.py
| 439
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 10:41:07 2018
@author: awanis.azizan
"""
import datetime
#birthday = input("What is your birthday? (dd/mm/yyyy)" )
#birthdate = datetime.datetime.strptime(birthday,"%d/%m/%Y").date()
#print("Your birth month is " +birthdate.strftime('%B'))
nextBirthday = datetime.datetime.strptime('11/26/2018',"%m/%d/%Y").date()
currentDate = datetime.date.today()
print(nextBirthday - currentDate)
| false
|
aaf7a5a0a5195ff1376ef2f0d6e6f84ffc273341
|
XxdpavelxX/Python3
|
/L3 Iteration in Python/decoder.py
| 1,682
| 4.625
| 5
|
"""Create a Python3_Homework03 project and assign it to your Python3_Homework working set. In the
Python3_Homework03/src folder, create a file named decoder.py, which contains an iterator named alphabator.
When passed a list, simply return objects as-is unless they are integers between 1 and 26, in which case it
should convert that number to the corresponding letter. The integer-to-letter correspondence is 1=A, 2=B, 3=C, 4=D,
and so on.
You may use any technique you've learned in lesson 3 to execute this project.
Your alphabator iterator must pass the unittest below:
test_decoder.py
from string import ascii_uppercase
import unittest
from decoder import alphabator
class TestAlpha(unittest.TestCase):
def test_easy_26(self):
a = alphabator(range(1,27))
self.assertEqual(list(ascii_uppercase), list(a))
def test_upper_range(self):
a = alphabator(range(40,50))
self.assertEqual(list(range(40, 50)), list(a))
def test_various_objects(self):
l = ['python', object, ascii_uppercase, 10, alphabator]
a = list(alphabator(l))
self.assertNotEqual(l[3], a[3])
self.assertEqual("J", a[3])
self.assertTrue(isinstance(a[1], object))
if __name__ == "__main__":
unittest.main()
Submit decoder.py and test_decoder.py when they are working to your satisfaction.
"""
####################################################################################################################################################################
def alphabator(lst):
for num in lst:
if num in range(1,27):
yield chr(num+64)
else:
yield num
| true
|
0a78c83f9ef57d9b72a23fe657ed93c9761f3e3e
|
XxdpavelxX/Python3
|
/L4 Basic Regular Expressions/find_regex.py
| 1,719
| 4.3125
| 4
|
"""Here are your instructions:
Create a Python3_Homework04 project and assign it to your Python3_Homework working set. In the Python3_Homework04/src
folder, create a program named find_regex.py that takes the following text and finds the start and end positions of the
phrase, "Regular Expressions".
Text to use in find_regex.py
In the 1950s, mathematician Stephen Cole Kleene described automata theory and formal language theoryin a set of models
using a notation called "regular sets" as a method to do pattern matching. Activeusage of this system, called Regular
Expressions, started in the 1960s and continued under such pioneers as David J. Farber, Ralph E. Griswold, Ivan P. Polonsky,
Ken Thompson, and Henry Spencer.
Your project should meet the following conditions:
•Your code must return 231 as the start and 250 as the end.
•You must include a separate test_find_regex.py program that confirms that your code functions as instructed.
Submit find_regex.py and test_find_regex.py when they are working to your satisfaction."""
##############################################################################################################################################################
import re
a = """In the 1950s, mathematician Stephen Cole Kleene described automata theory and formal language theory
in a set of models using a notation called "regular sets" as a method to do pattern matching. Activeusage of this system,
called Regular Expressions, started in the 1960s and continued under such pioneers as David J. Farber, Ralph E. Griswold,
Ivan P. Polonsky, Ken Thompson, and Henry Spencer."""
def searcher():
match = re.search("Regular Expressions", a)
beginning = match.start()
ending = match.end()
return (("Starts at:%d, Ends at:%d")%(beginning, ending))
print (searcher())
| true
|
ccc8620d0ec8f4dd1fdf13800ce16db8efa218ff
|
BiancaHofman/python_practice
|
/ex37_return_and_lambda.py
| 744
| 4.3125
| 4
|
#1. Normal function that returns the result 36
#And this result is printed
def name():
a = 6
return a * 6
print(name())
#2. Normal function that only prints the result 36
def name():
a = 6
print(a * 6)
name()
#3. Anonymous function that returns the result 36
#And this result is printed
x = lambda a: a * 6
print(x(6))
#4. Normal function that returns the result 30
#And this result is printed
def multiply():
a = 6
b = 5
return a * b
print(multiply())
#5. Normal function that only prints the result 30
def multiply():
a = 6
b = 5
print(a * b)
multiply()
#6.Anonymous function that returns result 30
#And this result is prints
multiply = lambda a, b: a * b
print(multiply (6,5))
| true
|
2cf1813ba0c933c00afef4c26bec91ec7b1494ff
|
johnsbuck/MapGeneration
|
/Utilities/norm.py
| 1,596
| 4.34375
| 4
|
"""N-Dimensional Norm
Defines the norm of 2 points in N dimensional space with different norms.
"""
import numpy as np
def norm(a, pow=2):
""" Lp Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,). Defines a point in 2-D space.
pow (float): The norm used for distance (Default: 2)
Returns:
(float) The distance between point a and point b with Lp Norm.
"""
return np.float_power(np.sum([np.float_power(np.abs(a[i]), pow) for i in range(len(a))]), 1./pow)
def manhattan(a):
"""Manhattan Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L1 norm.
"""
return norm(a, pow=1)
def euclidean(a):
"""Euclidean Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L2 norm.
"""
return norm(a, pow=2)
def minkowski(a):
"""Minkowski Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L3 norm.
"""
return norm(a, pow=3)
def chebyshev(a):
"""Chebyshev Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L-Infinity norm.
"""
return np.max([np.abs(a[i]) for i in range(len(a))])
| true
|
1040a092ef92aa80822e0cada2d5df026a95b1e2
|
snahor/chicharron
|
/cracking-the-code-interview/02.06.py
| 860
| 4.15625
| 4
|
from linked_list import Node
def reverse(head):
'''
>>> head = Node(1)
>>> reverse(head)
1
>>> head = Node(1, Node(2, Node(3)))
>>> reverse(head)
3 -> 2 -> 1
>>> reverse(reverse(head))
1 -> 2 -> 3
'''
new_head = None
curr = head
while curr:
new_head = Node(curr.value, new_head)
curr = curr.next
return new_head
def is_palindrome(head):
'''
>>> is_palindrome(Node(1))
True
>>> is_palindrome(Node(1, Node(2, Node(3))))
False
>>> is_palindrome(Node(1, Node(2, Node(3, Node(2, Node(1))))))
True
'''
new_head = reverse(head)
while head:
if head.value != new_head.value:
return False
head = head.next
new_head = new_head.next
return True
if __name__ == '__main__':
import doctest
doctest.testmod()
| false
|
81a1ab2f702bd56d5379540bee0e14044661a958
|
Manmohit10/data-analysis-with-python-summer-2021
|
/part01-e07_areas_of_shapes/src/areas_of_shapes.py
| 864
| 4.21875
| 4
|
#!/usr/bin/env python3
import math
def main():
while True:
shape=input("Choose a shape (triangle, rectangle, circle):")
shape=str(shape)
if shape=="":
break
elif shape=='triangle':
base=float(input('Give base of the triangle:'))
height=float(input('Give height of the triangle:'))
print(f"The area is {base*height*0.5}")
elif shape=='rectangle':
base=float(input('Give width of the rectangle:'))
height=float(input('Give height of the rectangle:'))
print(f"The area is {base*height}")
elif shape=='circle':
radius=float(input('Give radius of the circle:'))
print(f"The area is {math.pi*(radius**2)}")
else:
print('Unknown shape!')
if __name__ == "__main__":
main()
| true
|
87b47edb3ac4c944e7498021311d29a683de4873
|
mashanivas/python
|
/scripts/fl.py
| 208
| 4.28125
| 4
|
#!/usr/bin/python
#Function for powering
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(2, 3))
| true
|
cc6c58e549f132112a68038f4d71c8c582e63552
|
moon-light-night/learn_python
|
/project.py
| 577
| 4.3125
| 4
|
#Дэбильный калькулятор
what = input ('Что делаем? (+, -, *, /)')
a = float(input ('Введи первое число: '))
b = float(input ('Введи второе число: '))
if what == '+':
c = a + b
print('Результат:' + str(c))
elif what == '-':
c = a - b
print('Результат:' + str(c))
elif what == '*':
c = a * b
print('Результат:' + str(c))
elif what == '/':
c = a / b
print('Результат:' + str(c))
else:
print('Выбрана неверная операция')
| false
|
8570e157445bcbb0d2ff72b5d3c62921d5e084fd
|
prahaladbelavadi/codecademy
|
/python/5.making-a-request.py
| 1,129
| 4.40625
| 4
|
# Making a Request
# You saw a request in the first exercise. Now it's time for you to make your own! (Don't worry, we'll help.)
#
# On line 1, we've imported urlopen from the urllib2 module, which is the Python way of bringing in additional functionality we'll need to make our HTTP request. A module is just a collection of extra Python tools.
#
# On line 4, we'll use urlopen on placekitten.com in preparation for our GET request, which we make when we read from the site on line 5. (On line 6, we limit the response to specific character numbers to control the input we get back—this is what gives us our cat image.)
#
# We'll need your help to complete the request!
#
# Instructions
# On line 4, declare a variable, kittens, and set it equal to calling urlopen on http://placekitten.com. No need for the "www"!
#
# On line 8, print the body variable so we can see some of the data we got back.
from urllib2 import urlopen
# Open http://placekitten.com/ for reading on line 4!
kittens = urlopen('http://placekitten.com')
response = kittens.read()
body = response[559:1000]
# Add your 'print' statement here!
print body
| true
|
ac3a6fcb8237f80f54bd88856cc669d578ea08b5
|
kieranmcgregor/Python
|
/PythonForEverybody/Ch2/Ex2_prime_calc.py
| 2,439
| 4.125
| 4
|
import sys
def prime_point_calc(numerator, denominator):
# Returns a number if it is a prime number
prime = True
while denominator < numerator:
if (numerator % denominator) == 0:
prime = False
break
else:
denominator += 1
if prime:
return numerator
def prime_list_calc(numerator_limit, denominator):
# Returns list of prime numbers from 1 to user defined limit
primes = [1, 2]
numerator = 3
while numerator <= numerator_limit:
prime = prime_point_calc(numerator, denominator)
if prime != None:
primes.append(prime)
if denominator == numerator:
denominator == 0
numerator += 1
return primes
def prime_start_calc(start, denominator):
# Returns next prime after given user input
not_prime = True
prime = 0
numerator = start
while not_prime:
prime = prime_point_calc(numerator, denominator)
if prime != None:
not_prime = False
numerator += 1
return prime
def main():
numerator_empty = True
lps_empty = True
denominator = 2
prime = None
primes = None
print ("\nThis program will calculate prime numbers.")
while numerator_empty:
numerator = input("Please enter an integer: ")
try:
numerator = int(numerator)
numerator_empty = False
except:
print ("Invalid entry, not an integer.")
while lps_empty:
lps = input("Is this number a [l]imit, a [p]oint or a [s]tart? ")
if lps != 'l' and lps != 'p' and lps != 's':
print("Invalid entry, type 'l' for limit, 'p' for point or 's' for start.")
else:
lps_empty = False
if numerator > sys.maxsize:
numerator = sys.maxsize - 10
if lps[0].lower() == 'l':
numerator_limit = numerator
primes = prime_list_calc(numerator_limit, denominator)
elif lps[0].lower() == 'p':
prime = prime_point_calc(numerator, denominator)
elif lps[0].lower() == 's':
start = numerator
prime = prime_start_calc(start, denominator)
if prime != None:
print ("{} is a prime number.".format(prime))
elif primes != None:
print ("The following numbers are primes.\n{}".format(primes))
elif prime == None:
print ("{} is not a prime number.".format(numerator))
main()
| true
|
58bfbf28aa758d222f0375e61b4ed2dc95c2c8da
|
kieranmcgregor/Python
|
/PythonForEverybody/Ch9/Ex2_Day_Sort.py
| 1,767
| 4.15625
| 4
|
def quit():
quit = ""
no_answer = True
while no_answer:
answer = input("Would you like to quit? (y/n) ")
try:
quit = answer[0].lower()
no_answer = False
except:
print ("Invalid entry please enter 'y' for yes and 'n' for no.")
continue
if quit == 'n':
return True
elif quit != 'y':
print ("Neither 'y' nor 'n' found, exiting program")
return False
def open_file(fname):
fpath = "../Files/" + fname
try:
fhand = open(fpath)
except:
print("Invalid file path, using default ../Files/mbox-short.txt")
fpath = "../Files/mbox-short.txt"
fhand = open(fpath)
return fhand
def search(days_of_week):
search_on = True
while search_on:
search = input("Enter day of the week:\n").title()
if search in days_of_week:
print ("{} commits were done on {}".format(days_of_week[search], search))
else:
print ("Your search was not found")
answer = input("Would you like to continue searching? (y/n) ")
if 'y' in answer.lower():
continue
else:
search_on = False
no_quit = True
days_of_week = {}
while no_quit:
fname = input("Please enter just the file name with extension:\n")
fhand = open_file(fname)
for line in fhand:
if line.startswith("From "):
words = line.split()
if len(words) > 3:
day_of_week = words[2]
try:
days_of_week[day_of_week] += 1
except:
days_of_week[day_of_week] = 1
fhand.close()
print (days_of_week)
search(days_of_week)
no_quit = quit()
| true
|
81567c5895ebec2009ffac7000a0dcb7db71387e
|
mrupesh/US-INR
|
/USD&INR.py
| 523
| 4.3125
| 4
|
print("Currency Converter(Only Dollars And Indian Rupees)")
while True:
currency = input("($)Dollars or (R)Rupees:")
if currency == "$":
amount = int(input('Enter the amount:'))
Rupees = amount * 76.50
print(f"${amount} is equal to: ₹{Rupees}")
elif currency.upper() == "R":
amount = int(input('Enter the amount:'))
Dollars = amount / 76.50
print(f"₹{amount} is equal to: ${Dollars}")
else:
print("Sorry! I don't understand that...")
break
| false
|
86f91d794953d183366e9290564313d1dcaa594e
|
gmanacce/STUDENT-REGISTERATION
|
/looping.py
| 348
| 4.34375
| 4
|
###### 11 / 05 / 2019
###### Author Geofrey Manacce
###### LOOPING PROGRAM
####CREATE A LIST
months = ['january','february', 'match', 'april', 'may','june','july','august','september','october','november','december']
print(months)
#####using For loop
for month in months:
print(month.title() + "\n")
print("go for next month:")
print("GOODBYE!!!!")
| true
|
4407c72830681d2263c4882d39ab84070af61a77
|
Compileworx/Python
|
/De Cipher Text.py
| 348
| 4.34375
| 4
|
code = input("Please enter the coded text")
distance = int(input("Please enter the distance value"))
plainText = ''
for ch in code:
ordValue = ord(ch)
cipherValue = ordValue - distance
if(cipherValue < ord('a')):
cipherValue = ord('z') - (distance - (ord('a') - ordValue + 1))
plainText += chr(cipherValue)
print(plainText)
| false
|
d830adc3169ec263a5043079c99d8a8a65cda037
|
orrettb/python_fundamental_course
|
/02_basic_datatypes/2_strings/02_11_slicing.py
| 562
| 4.40625
| 4
|
'''
Using string slicing, take in the user's name and print out their name translated to pig latin.
For the purpose of this program, we will say that any word or name can be
translated to pig latin by moving the first letter to the end, followed by "ay".
For example: ryan -> yanray, caden -> adencay
'''
#take the users name via input
user_name = input("Enter your first name:")
#select the first letter
fist_letter = user_name[0]
#add pig latin variable
pig_value = "ay"
pig_latin_ver = user_name[1:]+fist_letter+pig_value
#print result
print(pig_latin_ver)
| true
|
482a4ab3e78e3f5e755ea3ff9b66fc48d3e5860f
|
BrandonMayU/Think-Like-A-Computer-Scientist-Homework
|
/7.10 Problems/5.6-17.py
| 367
| 4.1875
| 4
|
# Use a for statement to print 10 random numbers.
# Repeat the above exercise but this time print 10 random numbers between 25 and 35, inclusive.
import random
count = 1 # This keeps track of how many times the for-loop has looped
print("2")
for i in range(10):
number = random.randint(25,35)
print("Loop: ",count," Random Number: ", number)
count += 1
| true
|
63d9e51100db4792259157df2e315f920b23f46f
|
Shashanksingh17/python-functional-program
|
/LeapYear.py
| 227
| 4.125
| 4
|
year = int(input("Enter Year"))
if year < 1000 and year > 9999:
print("Wrong Year")
else:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("Leap year")
else:
print("Not a Leap Year")
| false
|
b5c3a44e099edcc1974e5854b17e4b2475dc6a76
|
Appu13/RandomCodes
|
/DivideandConquer.py
| 678
| 4.1875
| 4
|
'''
Given a mixed array of number and string representations of integers,
add up the string integers and subtract this from the total of the non-string integers.
Return as a number.
'''
def div_con(x):
# Variable to hold the string total
strtot = 0
# Variable to hold the digit total
digitot = 0
# Iterate through the list
for ch in x:
# Check if the current element is of type string
if isinstance(ch, str):
# Convert to integer and add to string total
strtot += int(ch)
# Else add to digit total
else:
digitot += ch
# return the difference
return digitot - strtot
| true
|
7a049ad9b04e1243ad1f440447d89fe112979633
|
Mvk122/misc
|
/CoinCounterInterviewQuestion.py
| 948
| 4.15625
| 4
|
"""
Question: Find the amount of coins required to give the amount of cents given
The second function gets the types of coins whereas the first one only gives the total amount.
"""
def coin_number(cents):
coinlist = [25, 10, 5, 1]
coinlist.sort(reverse=True)
"""
list must be in descending order
"""
cointotal = 0
while cents != 0:
for coin in coinlist:
if coin <= cents:
cents -= coin
cointotal += 1
break
return cointotal
def cointype(cents):
coinlist = [25, 10, 5, 1]
coinlist.sort(reverse=True)
coincount = [[25,0],
[10,0],
[5,0],
[1,0]]
while cents != 0:
for coin in coinlist:
if coin <= cents:
cents -= coin
coincount[coinlist.index(coin)][1] += 1
break
return coincount
print(coin_number(50))
| true
|
d25ac7c10ce42fed83f392ed9c5a02a3246eb146
|
Svanfridurjulia/FORRITUN-SJS-HR
|
/Verkefni í tímum/assignment 3 while/assignment3.6.py
| 222
| 4.125
| 4
|
a0 = int(input("Input a positive int: ")) # Do not change this line
print(a0)
while a0 != 1:
if a0 % 2 == 0:
a0 = a0/2
print(int(a0))
elif a0 % 2 != 0:
a0 = 3*a0+1
print(int(a0))
| false
|
8ce075118b7aca2dd2dc8f54eb59146e8c4edaf4
|
Svanfridurjulia/FORRITUN-SJS-HR
|
/Hlutapróf 2/prófdæmi.py
| 1,553
| 4.3125
| 4
|
def sum_number(n):
'''A function which finds the sum of 1..n and returns it'''
sum_of_range = 0
for num in range (1,n+1):
sum_of_range += num
return sum_of_range
def product(n):
'''A function which finds the product of 1..n and returns it'''
multi = 1
for num in range(1,n+1):
multi = multi * num
return multi
def print_choices():
'''A function which prints the choices and gets the choice from the user and returns it'''
print("""1: Compute the sum of 1..n
2: Compute the product of 1..n
9: Quit""")
choice = input("Choice: ")
return choice
def choice_1(int_list):
'''A function for the choice 1 which calls the sum function and prints out the sum, returns nothing'''
sum_of_numbers = sum_number(int_list)
print("The result is:",sum_of_numbers)
def choice_2(int_list):
'''A function for the choice 2 which calls the product function and prints out the product, returns nothing'''
product_of_numbers = product(int_list)
print("The result is:",product_of_numbers)
def choices(choice, n):
'''A function which calls other functions depending on what the user choice is and returns nothing'''
if choice == "1":
choice_1(n)
elif choice == "2":
choice_2(n)
#Main
choice = print_choices()
while choice != "9":
if choice == "1" or choice == "2":
try:
n = int(input("Enter value for n: "))
choices(choice, n)
except ValueError:
pass
choice = print_choices()
| true
|
7c041a0333ad9a58383c495981485c535f6aa8bd
|
Svanfridurjulia/FORRITUN-SJS-HR
|
/æfingapróf/dæmi2.py
| 878
| 4.21875
| 4
|
def open_file(filename):
opened_file = open(filename,"r")
return opened_file
def make_list(opened_file):
file_list = []
for lines in opened_file:
split_lines = lines.split()
file_list.append(split_lines)
return file_list
def count_words(file_list):
word_count = 0
punctuation_count = 0
for lines in file_list:
for element in lines:
word_count += 1
for chr in element:
if chr == "," or chr == "." or chr == "!" or chr == "?":
punctuation_count += 1
return word_count + punctuation_count
#main
filename = input("Enter filename: ")
try:
opened_file = open_file(filename)
file_list = make_list(opened_file)
word_count = count_words(file_list)
print(word_count)
except FileNotFoundError:
print("File {} not found!".format(filename))
| true
|
9be417a8ba86044f1b8717d993f44660adfbf9cd
|
Svanfridurjulia/FORRITUN-SJS-HR
|
/æfing.py
| 1,056
| 4.3125
| 4
|
def find_and_replace(string,find_string,replace_string):
if find_string in string:
final_string = string.replace(find_string,replace_string)
return final_string
else:
print("Invalid input!")
def remove(string,remove_string):
if remove_string in string:
final2_string = string.replace(remove_string,"")
return final2_string
else:
print("Invalid input!")
first_string = input("Please enter a string: ")
print("""\t1. Find and replace
\t2. Find and remove
\t3. Remove unnecessary spaces
\t4. Encode
\t5. Decode
\tQ. Quit""")
option = input("Enter one of the following: ")
if option == "1":
find_string = input("Please enter substring to find: ")
replace_string = input("Please enter substring to replace with: ")
final1_string = find_and_replace(first_string,find_string,replace_string)
print(final1_string)
elif option == "2":
remove_string = input("Please enter substring to remove: ")
final2_string = remove(first_string,remove_string)
print(final2_string)
| true
|
f0d663cbc1f64b3d08e61927d47f451272dfd746
|
Hiradoras/Python-Exercies
|
/30-May/Valid Parentheses.py
| 1,180
| 4.375
| 4
|
'''
Write a function that takes a string of parentheses, and determines
if the order of the parentheses is valid. The function should return
true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
Constraints
0 <= input.length <= 100
Along with opening (() and closing ()) parenthesis, input may contain any
valid ASCII characters. Furthermore, the input string may be empty and/or
not contain any parentheses at all. Do not treat other forms of brackets
as parentheses (e.g. [], {}, <>).
'''
def valid_parentheses(string):
is_valid = None
cleared = "".join(i for i in string if i=="(" or i==")")
uncompletes = []
for i in range(len(cleared)):
if cleared[i]=="(": uncompletes.append(cleared[i])
elif cleared[i]==")":
try:
uncompletes.pop()
except:
return False
if len(uncompletes) == 0:
is_valid = True
else:
is_valid = False
return is_valid
print(valid_parentheses("()"))
print(valid_parentheses("())"))
print(valid_parentheses("((((()"))
| true
|
cf9270abd93e8b59cdb717deeea731308bf5528d
|
Hiradoras/Python-Exercies
|
/29-May-2021/Reverse every other word in the string.py
| 895
| 4.25
| 4
|
'''
Reverse every other word in a given string, then return the string.
Throw away any leading or trailing whitespace, while ensuring there
is exactly one space between each word. Punctuation marks should be
treated as if they are a part of the word in this kata.
'''
def reverse_alternate(string):
words = string.split()
new_words = []
for i in range(0,len(words)):
if i % 2 == 0:
new_words.append(words[i])
else:
word = words[i]
new_words.append(word[::-1])
return " ".join(new_words)
print(reverse_alternate("Did it work?"))
############# Or ###############
def shorter_reverse_alternative(string):
return " ".join([element[::-1] if i % 2 else element for i,element in enumerate(string.split())])
print(shorter_reverse_alternative("Did it work?"))
### Same function but smarter and shorted with enumerate() method.
| true
|
224160811a676654cbfe88c9d0ba15d89620450f
|
zhangxinzhou/PythonLearn
|
/helloworld/chapter04/demo03.02.py
| 235
| 4.1875
| 4
|
coffeename = ('蓝山', '卡布奇诺', '慢的宁')
for name in coffeename:
print(name, end=" ")
print()
tuple1 = coffeename
print("原元组:", tuple1)
tuple1 = tuple1 + ("哥伦比亚", "麝香猫")
print("新元组:", tuple1)
| false
|
dc4cfcc11c9b26f1e27874d1b9ac84291664b33c
|
susanbruce707/hexatrigesimal-to-decimal-calculator
|
/dec_to_base36_2.py
| 696
| 4.34375
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 21 23:38:34 2018
Decimal to hexatrigesimal calculator.
convert decimal number to base 36 encoding; use of letters with digits.
@author: susan
"""
def dec_to_base36(dec):
"""
converts decimal dec to base36 number.
returns
-------
sign+result
"""
chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
sign = '-' if dec < 0 else ''
dec = abs(dec)
result = ''
while dec > 0:
dec, remainder = divmod(dec, 36)
result = chars[remainder]+result
return sign+result
dec = int(input("please enter a Decimal number, e.g. 683248722 :> "))
A = dec_to_base36(dec)
print(A)
| true
|
58a9223e31c487b45859dd346238ee84bb2f61c8
|
ao-kamal/100-days-of-code
|
/binarytodecimalconverter.py
| 1,485
| 4.34375
| 4
|
"""Binary to Decimal and Back Converter - Develop a converter to convert a decimal number
to binary or a binary number to its decimal equivalent.
"""
import sys
print(
'This program converts a number from Binary to Decimal or from Decimal to Binary.')
def binary_to_decimal(n):
print(int(str(n), 2), '\n')
def decimal_to_binary(n):
print(format(int(n), 'b'), '\n')
def convert_again():
prompt = input('Run the program again? (Y/N)\n')
if prompt == 'Y':
converter()
elif prompt == 'N':
print('Bye!')
sys.exit()
else:
print("You typed '{0}'.'.format{0}\n")
convert_again()
def converter():
print('-------------------------------------------\n')
choice = input(
"To convert from Binary to Decimal, type 'b'.\nTo convert from Decimal to Binary, type 'd'.\n")
if choice == 'b':
print('---------------------------------------')
print('Converting from Binary to Decimal...\n')
number = input('Enter the number you want to convert: \n')
binary_to_decimal(number)
convert_again()
elif choice == 'd':
print('---------------------------------------')
print('Converting from Binary to Decimal...\n')
number = input('Enter the number you want to convert: \n')
decimal_to_binary(number)
convert_again()
else:
print("You typed '{0}'.".format(choice))
converter()
print('\n')
converter()
| true
|
c296dab78893f00978039d1a8edee17c8d6d6b3d
|
lillyfae/cse210-tc05
|
/puzzle.py
| 1,812
| 4.125
| 4
|
import random
class Puzzle:
'''The purpose of this class is to randomly select a word from the word list.
Sterotyope:
Game display
Attributes:
word_list (list): a list of words for the puzzle to choose from
chosen_word (string): a random word from the word list
create_spaces (list of strings): a list of characters that will initially contain spaces and be filled in with player guesses
'''
def __init__(self):
'''Class constructor. Declares and initializes instance attributes.
Args:
self (Puzzle): An instance of Puzzle.
'''
self.word_list = ["teach","applied","remain","back","raise","pleasant"
"organization","plenty","continued","all","seldom","store"
"refer","toy","stick","by","shine","field"
"load","forth","well","mine","catch","complex"
"useful","camera","teacher","sit","spin","wind"
"drop","coal","every","friend","throw","wool"
"daughter","bound","sight","ordinary","inch","pan"]
self.chosen_word = self.random_word()
self.create_spaces()
def random_word(self):
'''Gets a random word from the word list.
Args:
self (Puzzle): An instance of Puzzle.
Returns: the word
'''
return random.choice(self.word_list)
def create_spaces(self):
'''Creates the list of spaces
Args:
self (Puzzle)
'''
self.spaces = []
for i in range(len(self.chosen_word)):
self.spaces.append('_')
def print_spaces(self):
'''Prints out the spaces
Args:
self (Puzzle)
'''
for ch in self.spaces:
print(ch + " ", end='')
print('\n')
| true
|
ca851a63737efa0dbef14a3d542e64797b808cce
|
prasertcbs/python_tutorial
|
/src/while_loop.py
| 677
| 4.15625
| 4
|
def demo1():
i = 1
while i <= 10:
print(i)
i += 1
print("bye")
def demo_for():
for i in range(1, 11):
print(i)
print("bye")
def sum_input():
n = int(input("enter number: "))
total = 0
while n != 0:
total += n
n = int(input("enter number: "))
print("total = ", total)
def sum_input_repeat_unit():
total = 0
while True:
n = int(input("enter number: "))
if n != 0:
total += n
else:
break
print("total = ", total)
# repeat until
# do ... while
# demo1()
# demo_for()
# sum_input()
sum_input_repeat_unit()
| false
|
e105386bcb9851004f3243f42f385ebc39bac8b7
|
KAOSAIN-AKBAR/Python-Walkthrough
|
/casting_Python.py
| 404
| 4.25
| 4
|
x = 7
# print the value in float
print(float(x))
# print the value in string format
print(str(x))
# print the value in boolean format
print(bool(x)) # *** in BOOLEAN data type, anything apart from 0 is TRUE. Only 0 is considered as FALSE *** #
print(bool(-2))
print(bool(0))
# type casting string to integer
print(int("34"))
# print(int("string")) ----> would produce error ; please donot try this
| true
|
f64eb90364c4acd68aac163e8f76c04c86479393
|
KAOSAIN-AKBAR/Python-Walkthrough
|
/calendar_Python.py
| 831
| 4.40625
| 4
|
import calendar
import time
# printing header of the week, starting from Monday
print(calendar.weekheader(9) + "\n")
# printing calendar for the a particular month of a year along with spacing between each day
print(calendar.month(2020, 4) + "\n")
# printing a particular month in 2-D array mode
print(calendar.monthcalendar(2020, 4))
print()
# printing calendar for the entire year
print(calendar.calendar(2020))
print()
# printing a particular day of the week in a month in terms of integer
print(calendar.weekday(2020, 4, 12)) # answer is 6, because according to python 6 is Sunday
print()
# finding whether a year is leap year or not
print(calendar.isleap(2020))
print()
# finding leap days within specific years, the year you put at the end is exclusive, 2000 and 2004 is leap year.
print(calendar.leapdays(2000,2005))
| true
|
5af9931029bef4345ffc1528219484cd363fbcfa
|
shade9795/Cursos
|
/python/problemas/Condiciones compuestas con operadores lógicos/problema5.py
| 257
| 4.125
| 4
|
x=int(input("Cordenada X: "))
y=int(input("Cordenada Y: "))
if x==0 or y==0:
print("Las coordenadas deben ser diferentes a 0")
else:
if x>0 and y>0:
print("1º Cuadrante")
else:
if x<0 and y>0:
print("2º Cuadrante")
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.