blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9bc55d22386ba51abf3e6d98261d1bae4aae5273 | bolducp/My-Think-Python-Solutions | /chps8/8.08.07.py | 245 | 4.3125 | 4 | """There is a string method called count that is similar to the
function in the previous exercise. Read the documentation of this
method and write an invocation that counts the number of as in 'banana'."""
word = "banana"
print word.count("a") | true |
921811a2b5184666b1859af4d9f5e9c6a93ad489 | wajdm/ICS3UR-4-05-Python | /positive_integer_adder.py | 686 | 4.34375 | 4 | # !/usr/bin/env python3
# Created by: Wajd Mariam
# Created on: November 2019
# This program adds all positive integers together
def main():
# counter and answer
answer = 0
counter = 0
positive_integer = 0
# input
loop_number = int(input("Enter the number of integers you want to add: "))
# loop & process & output
while counter < loop_number:
positive_integer = int(input("Enter a number: "))
counter = counter + 1
if positive_integer < 0:
continue
else:
answer = answer + positive_integer
print("The sum of all positive integers is {}".format(answer))
if __name__ == "__main__":
main()
| true |
49ebe06c478235b304b969fd9615586b2a030609 | Rach1612/Python | /Python Short Pro/p12p3.py | 972 | 4.5 | 4 | #program using function to find the approximate square root of a number
#set function name and values : def approot (x,y):
#set step =y**2
#set root=0.0
#while abs(x-root**2)>= y ad root <=x: do
#increment the step, incremenet the number of guesses
#if abs(x-root**2) <=y and root <=x :
#if abs(x-root**2) <= y and root <=x:
# return root
def approot (x,y):
step =y**2
root=0.0
numGuesses=0
root=0.0
while abs(x - root**2) >= y and root <=x:
root +=step
numGuesses +=1
if abs(x -root**2)<=y and root <=x:
return root
number=float(input("enter a number for which you would like to find the square root of"))
tolerance=(float(input("enter the tolerance or epsilon number value")))
if number >=0:
print("the approximate square root of this number is", approot(number,tolerance))
else:
print("error , this number is a negative number, please try again")
| true |
87b5b6baecbd06679f404b1c30d56bfbd657bcd8 | Rach1612/Python | /p17p1 (3).py | 1,844 | 4.34375 | 4 | #Two suggested optimisations for the algorithm to calculate the divisors of a number are to initalise the divisors
#tuple to include 1 and the number itself and to only search from 2 and as far as half of the number.
#define function finddivisors(num1)
#divisors()#change this to include 1 and the numbers themselves = divisors (1,num1,num2)
#to find up to half of the numbers :do
#nnum1=num1//2
#nnum2=num2//2
#for i in range (2,min (nnum1,nnum2)+1): #change here = start at 2 instead of one and just search up until half of the numbers given .
# if num1% i==0 and num2%i ==0:
#divisors +=(i,)
#return divisors
#prompt user for input (number1= int(input(enter a number)))
#number2=int(input(enter another number))
#if number1 <= 0 or number2 <= 0: #check both numbers are positive
#print("Numbers should be > 0.")
#else:
#finddivisors (num1 , num2)
# print them out
#total =0
#for d in divisors :
#total +=d
# print("Sum of the common divisors is:", total)
#print("Finished!")
def findDivisors(num1):
#"""Finds the common divisors of num1 and num2,Assumes that num1 and num2 are positive integers,Returns a tuple containing the common divisors of num1 and num2"""
divisors = (1,num1)
nnum1=num1//2
for i in range(2,(nnum1)+ 1):
if num1 % i == 0:
divisors += (i,)
return divisors
number1 = int(input("Enter a positive integer: "))
if number1 <= 0:
print("Numbers should be > 0.")
else:
# First of all, get the common divisors and print them outdivisors =
divisors=findDivisors(number1)
print("The common divisors of,", number1,"are:", divisors)
# Now sum them and print the total
total = 0
for d in divisors:
total += d
print("Sum of the common divisors is:", total)
print("Finished!")
| true |
1862a321d7e14bddf642b518bf7d47332fabe3bb | Rach1612/Python | /Python Short Pro/p6p4.py | 1,051 | 4.28125 | 4 | #programm to check password and deny access if incorrect password used 3 times.
#correct password=HiRachel - saved in variable
#user input to store passwords which entered
#conditional statement If password correct:
#do the following : print (you have sucessfully logged in)
#and terminate program
#or else : (any other password or sequence of character inputted)
#while loop
#Limit = 3
#count =1
#while count<3 : do
#print incorrect password try again
#count +=1 -logging wrong password number 1
#repeat while loop until count =3 :
#then go back an indent print "you have been denied access"
#finish program
correctpassword=("HiRachel")
passwordentered=(input("Enter your password please"))
if passwordentered==correctpassword:
print("You have successfully logged in.")
else:
count=1
while count<3:
print("incorrect password try again!")
count += 1
passwordentered=(input("Enter your password please"))
print("you have been denied access")
| true |
e3b5f59b9496eb6f714eb392fa6a5c25f2cfcc17 | tmaunier/Team_Giteub | /KKO/ressources/scripts/7.py | 215 | 4.15625 | 4 | ##Python
##2
##Error 999 : loafer programmer.
##3
##../img/python_2_3.png
Word = str(input("Word : "))
Reverse = Word[::-1]
if Word == Reverse:
print("Palindrome")
else:
print("Not Palindrome")
| false |
61d992b3122e41a5e1a6bd40a56f757037ecf658 | mankarali/PYTHON_EDABIT_EXAMPLES | /radian_to_degree.py | 338 | 4.3125 | 4 | """
Radian to Degree
Create a function that takes an angle in radians and converts it into degrees.
Examples
to_degree(math.pi) ➞ 180
to_degree(math.pi/2) ➞ 90
to_degree(math.pi/4) ➞ 45
"""
import math
def to_degree(radian):
pi=math.pi
degree=(radian*180)/pi
return (degree)
to_degree(math.pi)
to_degree(math.pi/4)
| true |
1802541228ecdfd8bd2990be426fbc1deb33468f | mankarali/PYTHON_EDABIT_EXAMPLES | /33_identity_matrix.py | 1,978 | 4.28125 | 4 | """
Identity Matrix
An identity matrix is defined as a square matrix with 1s running from the top left of the square to the bottom right. The rest are 0s. The identity matrix has applications ranging from machine learning to the general theory of relativity.
Create a function that takes an integer n and returns the identity matrix of n x n dimensions. For this challenge, if the integer is negative, return the mirror image of the identity matrix of n x n dimensions.. It does not matter if the mirror image is left-right or top-bottom.
Examples
id_mtrx(2) ➞ [
[1, 0],
[0, 1]
]
id_mtrx(-2) ➞ [
[0, 1],
[1, 0]
]
id_mtrx(0) ➞ []
Notes
Incompatible types passed as n should return the string "Error".
Test.assert_equals(id_mtrx(1), [[1]])
Test.assert_equals(id_mtrx(2), [[1, 0], [0, 1]])
Test.assert_equals(id_mtrx(3), [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
Test.assert_equals(id_mtrx(4), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
Test.assert_equals(id_mtrx(-6), [[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0]])
Test.assert_equals(id_mtrx("edabit"), "Error", 'Incompatible types passed as n should return the string "Error".')
"""
def id_mtrx(n):
if not isinstance(n,int):
return "Error"
a = []
b = []
if n > 0:
for i in range(n):
for j in range(n):
if i == j:
a.append(1)
else:
a.append((0))
for i in range(n):
b.append(a[n*i:n*i+n])
return (b)
elif n < 0:
for i in range(abs(n)):
for j in range(abs(n)):
if i == abs(n)-j-1:
a.append(1)
else:
a.append((0))
for i in range(abs(n)):
b.append(a[abs(n)*i:abs(n)*i+abs(n)])
return (b)
else:
return []
id_mtrx(-6) | true |
bb919ce373789c43af95ca95bdadf7c5d3b7a55a | mankarali/PYTHON_EDABIT_EXAMPLES | /55_move_capital_letters_to_the_front.py | 544 | 4.21875 | 4 | """
Move Capital Letters to the Front
Create a function that moves all capital letters to the front of a word.
Examples
cap_to_front("hApPy") ➞ "APhpy"
cap_to_front("moveMENT") ➞ "MENTmove"
cap_to_front("shOrtCAKE") ➞ "OCAKEshrt"
Notes
Keep the original relative order of the upper and lower case letters the same.
"""
def cap_to_front(s):
a=[]
b=[]
for i in s:
if i.islower():
a.append(i)
else:
b.append(i)
return ("".join(b)+"".join(a))
cap_to_front("shOrtCAKE") | true |
f8035c2c1454523bb474d2625e44d7ae2c22e15f | mankarali/PYTHON_EDABIT_EXAMPLES | /19__bitwise_operations.py | 2,105 | 4.375 | 4 | """
Bitwise Operations
A decimal number can be represented as a sequence of bits. To illustrate:
6 = 00000110
23 = 00010111
From the bitwise representation of numbers, we can calculate the bitwise AND, bitwise OR and bitwise XOR. Using the example above:
bitwise_and(6, 23) ➞ 00000110
bitwise_or(6, 23) ➞ 00010111
bitwise_xor(6, 23) ➞ 00010001
Write three functions to calculate the bitwise AND, bitwise OR and bitwise XOR of two numbers.
Examples
bitwise_and(7, 12) ➞ 4
bitwise_or(7, 12) ➞ 15
bitwise_xor(7, 12) ➞ 11
Test.assert_equals(bitwise_and(32, 17), 0)
Test.assert_equals(bitwise_or(32, 17), 49)
Test.assert_equals(bitwise_xor(32, 17), 49)
Test.assert_equals(bitwise_and(13, 19), 1)
Test.assert_equals(bitwise_or(13, 19), 31)
Test.assert_equals(bitwise_xor(13, 19), 30)
"""
def bitwise_and(n1, n2):
m = "%08d" % int(bin(n1)[2:])
n = "%08d" % int(bin(n2)[2:])
p = []
for i in range(8):
if m[i] == n[i]:
p.append(int(m[i]))
else:
p.append(0)
p10 = p[0]*128 + p[1]*64 + p[2]*32 + p[3]*16 + p[4]*8 + p[5]*4 + p[6]*2 + p[7]*1
return p10
def bitwise_or(n1, n2):
m = "%08d" % int(bin(n1)[2:])
n = "%08d" % int(bin(n2)[2:])
r = []
for i in range(8):
if int(m[i])==1 or int(n[i])==1:
r.append(1)
else:
r.append(0)
r10 = r[0]*128 + r[1]*64 + r[2]*32 + r[3]*16 + r[4]*8 + r[5]*4 + r[6]*2 + r[7]*1
return r10
def bitwise_xor(n1, n2):
m = "%08d" % int(bin(n1)[2:])
n = "%08d" % int(bin(n2)[2:])
p = []
for i in range(8):
if m[i] == n[i]:
p.append(int(m[i]))
else:
p.append(0)
p10 = p[0]*128 + p[1]*64 + p[2]*32 + p[3]*16 + p[4]*8 + p[5]*4 + p[6]*2 + p[7]*1
r = []
for i in range(8):
if int(m[i])==1 or int(n[i])==1:
r.append(1)
else:
r.append(0)
r10 = r[0]*128 + r[1]*64 + r[2]*32 + r[3]*16 + r[4]*8 + r[5]*4 + r[6]*2 + r[7]*1
return (r10-p10)
bitwise_and(7, 12)
bitwise_or(7, 12)
bitwise_xor(7, 12)
| true |
46831cf97fad02e426e32c2ae49e49985d906710 | mankarali/PYTHON_EDABIT_EXAMPLES | /letter_shifting.py | 549 | 4.125 | 4 |
"""
Letter Shifting
Create a function that takes a string and shifts the letters to the right by an amount n but not the whitespace.
Examples
shift_letters("Boom", 2) ➞ "omBo"
shift_letters("This is a test", 4) ➞ "test Th i sisa"
shift_letters("A B C D E F G H", 5) ➞ "D E F G H A B C"
Notes
Keep the case as it is.
n can be larger than the total number of letters.
"""
def shift_letters(txt, n):
a = "".join(txt.split())
a = list(a[-n%len(a):] + a[:-n%len(a)])
return ''.join(a.pop(0) if i != ' ' else i for i in txt) | true |
508fa9030901095d60d84eea6a5c47ed7f9d3d26 | mankarali/PYTHON_EDABIT_EXAMPLES | /53_convert_to_hex.py | 646 | 4.25 | 4 | """
Convert to Hex
Create a function that takes a strings characters as ASCII and returns each characters hexadecimal value as a string.
Examples
convert_to_hex("hello world") ➞ "68 65 6c 6c 6f 20 77 6f 72 6c 64"
convert_to_hex("Big Boi") ➞ "42 69 67 20 42 6f 69"
convert_to_hex("Marty Poppinson") ➞ "4d 61 72 74 79 20 50 6f 70 70 69 6e 73 6f 6e"
Notes
Each byte must be seperated by a space.
All alpha hex characters must be lowercase.
"""
def convert_to_hex(txt):
a = list(txt)
b = []
for i in a:
b.append((hex(ord(i)).lstrip("0x")))
return ((" ".join((b))))
convert_to_hex("Big Boi")
| true |
dc3beed27bc495bad3949baad5c8c1d3ffb457b3 | mankarali/PYTHON_EDABIT_EXAMPLES | /22_amplify.py | 853 | 4.3125 | 4 | """
Amplify the Multiples of Four
Create a function that takes an integer and returns a list from 1 to the given number, where:
If the number can be divided evenly by 4, amplify it by 10 (i.e. return 10 times the number).
If the number cannot be divided evenly by 4, simply return the number.
Examples
amplify(4) ➞ [1, 2, 3, 40]
amplify(3) ➞ [1, 2, 3]
amplify(25) ➞ [1, 2, 3, 40, 5, 6, 7, 80, 9, 10, 11, 120, 13, 14, 15, 160, 17, 18, 19, 200, 21, 22, 23, 240, 25]
Notes
The given integer will always be equal to or greater than 1.
Include the number (see example above).
To perform this problem with its intended purpose, try doing it with list comprehensions. If that's too difficult, just solve the challenge any way you can.
"""
def amplify(num):
return [ x if x%4 else x*10 for x in range(1, num+1) ]
amplify(25)
| true |
996a0c8335fb8a37d59fcb3c5e0d3c768d4ea036 | rolang12/archivospythonclase | /preguntasisi.py | 734 | 4.21875 | 4 | '''Realiza un programa que imprima una secuencia de numeros de uno en uno desde el
que el usuario desee, el programa debe pedirle al usuario después de que imprima un
numero en pantalla le pregunte si desea continuar o no mostrando en pantalla'''
n=int(input("Ingrese el número de inicio: "))
c=True
while c==True:
print(n)
re=int(input("¿Desea seguir - [1 = Si / 2 = No]"))
if re==2:
c=False
elif re==1:
c=True
elif re!=1 or re!=2:
print("El número ingresado es incorrecto")
c=False
n+=1
'''Modificar el programa anterior para que sea una función que devuelva si el usuario
ingresó o no la contraseña correctamente, mediante un valor booleano (True o False).''' | false |
43f21ed4eefcb7b2ec93583007786489b03cc880 | expressfrog/Guess-The-Number-Pack | /youguess.py | 1,491 | 4.1875 | 4 | import random #Importing random
answer = random.randint(1, 10) #The answer
guess = int(input("Guess a number from 1 to 10: ")) #The guess
if guess < answer: #Uh oh, you guessed it too low!
guess2 = int(input("Too low, try again: "))
if guess2 < answer:
print("You win, good job!")
else:
if guess2 < answer:
guess3 = int(input("Too low, one more chance: "))
if guess3 == answer:
print("you win!")
else:
print(f"You lost! Good game. The answer was {answer}.")
elif guess2 > answer:
guess3 = int(input("Too high, one more chance: "))
if guess3 == answer:
print("you win!")
else:
print(f"You lost! Good game. The answer was {answer}")
else:
print("You win!")
elif guess > answer: #Uh oh, you guessed it too high!
guess2 = int(input("Too high, try again: "))
if guess2 < answer:
guess3 = int(input("Too low, one more chance: "))
if guess3 == answer:
print("you win!")
else:
print(f"You lost! Good game. The answer was {answer}.")
elif guess2 > answer:
guess3 = int(input("Too high, one more chance: "))
if guess3 == answer:
print("you win!")
else:
print(f"You lost! Good game. The answer was {answer}")
else:
print("You win!")
else: #You win
print("You win!") | true |
bae7e0ea9bfb9de9fd5a89add10bb35bd750867f | bryanmuir98/LearnPython | /betterCalculator.py | 493 | 4.28125 | 4 | num1 = float(input("Enter first number: "))
op = (input("Enter operator: "))
num2 = float(input("Enter second number: "))
def betterCalc(num1,op,num2):
answer = 0
if op == "+":
answer = num1 + num2
elif op == "-":
answer = num1 - num2
elif op == "*":
answer = num1 * num2
elif op == "/":
answer = num1 / num2
else:
print("Please enter valid operator!")
return answer
print("Your answer is: " + str(betterCalc(num1,op,num2)))
| false |
689c1564bd87fb8d733f26788badf02a554c4877 | Christy538/Hacktoberfest-2021 | /PYTHON/Simple password hashing.py | 810 | 4.28125 | 4 |
# procedure is - first take password and store its hash(hashedPassword)
# now user on login give userPassword - check if this password matches with the hashedPassword
def encrypt(password):
hashed = 0
for digit in password:
hashed ^= int(digit)
return hashed
def decrypt(hashedPassword, userPassword):
for digit in userPassword:
hashedPassword ^= int(digit)
if(hashedPassword == 0):
return 1
return 0
password = input("give pin: ")
hashedPassword = encrypt(password)
print(f"the hash generated is {hashedPassword}")
userPassword = input("give password to check if valid: ")
if(decrypt(hashedPassword, userPassword)):
print("Yes! password matched")
else:
print("Opps! the password is incorrect")
| true |
b45bc3264f182c818ddd9cd48a2fc088e0bb6993 | Christy538/Hacktoberfest-2021 | /PYTHON/Average of an array.py | 372 | 4.3125 | 4 | # Python3 code to calculate
# average of array elements
# Function that return
# average of an array.
def average( a , n ):
# Find sum of array element
sum = 0
for i in range(n):
sum += a[i]
return sum/n;
# array
arr = [10, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print("The average of the array is:",average(arr, n))
# by aditya
| true |
bdc537233a4cc219747658b9e0d70346edbd0967 | jlifferth/Bio165_repo | /Lesson_9/Question 3: Calculate the Length of a DNA Sequence.py | 397 | 4.25 | 4 | # 3. Calculate the Length of a DNA Sequence
#
#
# We will test your code using the following commands:
#
# python studentcode.py ATATATATATATA
# python studentcode.py CGACGAGCAAAGCAAAAAGGGAAA
#
# Your code should produce the following output:
#
# 13
# 24
#! /usr/bin/env python3
import sys
seq = sys.argv[1]
# seq = input("Input : ")
index = 0
for nucleotide in seq:
index += 1
print(index) | true |
0fc250f55cd9e523a17eee2c6f8332d84b2be883 | DaniloBNascimento/Python3_Crash_Course | /repetition_loops/for_list_2.py | 396 | 4.53125 | 5 | #!/usr/bin/env python3.8
print("Trabalahando com listas...")
# listas
names = ['danilo', 'regina']
nomes = names[:]
# Adicionando itens as listas
names.append('telma')
nomes.append('valdemir')
# Provando que são listas diferentes
print("nomes que estão na lista names:")
for namess in names:
print(namess)
print("nomes que estão na lista nomes:")
for nomess in nomes:
print(nomess)
| false |
c2e38473a83ffe0a7f85b5e8789603afce456493 | DaniloBNascimento/Python3_Crash_Course | /class/class_restaurant.py | 597 | 4.375 | 4 | #!/usr/bin/env python3.8
# Código python criado para modelar uma classe de obejtos referente a um restaurante
class Restaurante():
def __init__(self, name, type):
self.name = name
self.type = type
def description(self):
print("Esse restaurante tem a cozinha do tipo: " + self.type.title())
def open(self):
print("O restaurante " + self.name + " está aberto!")
restaurant1 = Restaurante('cantina', 'italiano')
restaurant1.description()
restaurant1.open()
restaurant2 = Restaurante('bahia', 'brasileiro')
restaurant2.description()
restaurant2.open() | false |
22c7bc10176ae6d5a42cb4234dc49c0dde5b2086 | nakoyawilson/one-hundred-days | /NATO-alphabet/main.py | 612 | 4.4375 | 4 | import pandas
# Create a dictionary for NATO alphabet:
nato_alphabet = pandas.read_csv("nato_phonetic_alphabet.csv")
nato_dict = {row.letter:row.code for (index, row) in nato_alphabet.iterrows()}
# Create a list of the phonetic code words from a word that the user inputs.
word_not_submitted = True
while word_not_submitted:
user_input = input("Enter a word: ").upper()
try:
phonetic_code = [nato_dict[letter] for letter in user_input]
except KeyError:
print("Sorry, only letters in the alphabet please.")
else:
print(phonetic_code)
word_not_submitted = False
| true |
550f9f30f0e178e109c7119c21ff4e5395ec92aa | PrashanthPuneriya/CS-Lab-Programs | /Python/tkinter1.py | 923 | 4.34375 | 4 | from tkinter import *
"""
We have to pack the widget to display it.
l->label, b->button, t->text, f->frame,
By Default all the widgets are stacked on each other
"""
root = Tk()
root.title("Colors....")
root.geometry("500x300")
topFrame = Frame(root)
bottomFrame = Frame(root)
topFrame.pack() # Default side = TOP
bottomFrame.pack(side = BOTTOM)
l1 = Label(root, text = "MARK 1.0", bg = 'red', fg = 'white') # Appears in the middle since its in root frame
l2 = Label(root, text = "HELLO", bg = 'green', fg = 'black')
l3 = Label(root, text = "Prashanth!", bg = 'blue', fg = 'white')
b1 = Button(bottomFrame, text = "Hey!", activebackground = 'yellow', activeforeground = 'red')
b2 = Button(bottomFrame, text = "Bye!", activebackground = 'yellow', activeforeground = 'red')
l1.pack()
l2.pack(fill = X)
l3.pack(side = LEFT, fill = Y)
b1.pack(side = LEFT)
b2.pack(side = LEFT)
root.mainloop() | true |
8c35352e0edf5139b5334f00a847a193154a526d | ans-sharma/python | /ForwardBackwardPrint.py | 601 | 4.15625 | 4 | """Write a program in python that will print a string of text with
step length taken from user and also can print from backwards
with step length taken from user (without slicing technique)."""
strText = input("Enter the Text: ")
iStep = int(input("Enter the Step Length :"))
iMode = int(input("""Enter
1: Forward,
2: Backward
:"""))
if iMode == 1:
iStart = 0
iLen = len(strText)
elif iMode == 2:
iStart = -1
iStep = -iStep
iLen = -len(strText)-1
else:
print("Wrong Choice")
for letter in range(iStart, iLen, iStep):
print(strText[letter], end='')
| true |
98f2d10d7dc128e734ba9f0b505b8824a8d265d8 | steview-d/practicepython-org-exercises | /practice_python_org/33_bday_dict.py | 433 | 4.375 | 4 | birthday_dict = {
"Person A":"01/01/1960",
"Person B":"01/01/1970",
"Person C":"01/01/1980",
"Person D":"01/01/1990",
}
print("Welcome to the Birthday Dictionary!")
print("\nWe have the following birthdays stored:")
for name in birthday_dict:
print(name)
user_input = str(input("\nPlease enter a name > "))
bday = birthday_dict.get(user_input, "not listed")
print("{}'s birthday is {}".format(user_input, bday)) | true |
3f6e0d5004da5597c615c957df42e5597fc71a67 | rajui67/learnpython | /python_code_exaples/formatting_strings/string1.py | 1,073 | 4.25 | 4 | income = 12 * 8900
tax = int(income * .3)
print("\nSTRING FORMATTING, OLD STYLE (DEPRECATED):\n")
text_os1 = 'Your yearly income is %s and tax is %s' % (income, tax)
print('Old style string formatting using %s', text_os1, sep=': ')
text_os2 = 'Your yearly income is %(print_income)s and tax is %(print_tax)s' % {
"print_income": income, "print_tax": tax } # "income": income, "tax": tax will also work
print('Old style string formatting using %(<varible_name>)s', text_os2, sep=': ')
print("\nSTRING FORMATTING, NEW STYLE (str.format):\n")
text_f1 = 'Your yearly income is {} and tax is {}'.format(income, tax)
print('New style string formatting using empty braces', text_f1, sep=': ')
text_f2 = 'Your yearly income is {fs2_income} and tax is {fs2_tax}'.format(fs2_income = income, fs2_tax = tax)
print('New style string formatting using names in braces', text_f1, sep=': ')
print("\nSTRING FORMATTING, NEW STYLE (f-string):\n")
text_fs1 = f'Your yearly income is {income} and tax is {tax}'
print('New style string formatting using f-string', text_fs1, sep=': ') | true |
92b9f2358ff19392f6a9a6ac0fe853c34b2fb10d | rajui67/learnpython | /python_code_exaples/classes/str_vs_repr.py | 1,010 | 4.375 | 4 | from typing import Optional, Union
class Car:
def __init__(self, color: str, mileage: Union[int, float], uom_mileage: Optional[str] = 'Miles',
uom_fuel_qty: Optional[str] = "Gallon"):
"""Car Class Constructor to initialize the object
Input Arguments: color must be str
mileage must be int or float.
uom_mileage is optional. must be str if specified. Default value is "Miles"
uom_fuel_qty is optional. must be str if specified. Default value is "Gallon"
"""
self.color = color
self.mileage = mileage
self.uom_mileage = uom_mileage
self.uom_fuel_qty = uom_fuel_qty
def __repr__(self):
return '__repr__ for Car'
def __str__(self):
return '__str__ for Car'
car = Car("Red", 100)
'''Enter the following in interactive window and run it to see values returned
Check the values of str(car), print(car), repr(car), car'''
| true |
b1157059ce4a494000fa0970b723b87e340e50bd | rajui67/learnpython | /python_code_exaples/testing/xxx_arithmetic.py | 419 | 4.25 | 4 | def subtract_divide(dividend, x, y):
"""This function divides dividend with the result derived by subtracting y from x
Input Arguments: dividend, x, y must be numbers.
Returns: quotient.
"""
try:
z = x - y
return dividend / z
# except ZeroDivisionError:
# raise ZeroDivisionError
except ZeroDivisionError:
return f"this won't work, {x} - {y} is 0 or lower." | true |
f385cb87b965fcefbe2d442501b940918cb8d7ce | rajui67/learnpython | /python_code_exaples/classes/access_class_variables/access_using_class_getter_method.py | 680 | 4.28125 | 4 | from aqua import Aqua
class Fish(Aqua):
''' This class denomstrates one way of accessing private class variables of the parent class.
The class Aqua has a method get_waterbodies. Methods in the class access the method by invoking get_waterbodies
'''
def __init__(self, waterbody: str):
"""Fish Class Constructor to initialize the object.
Input Arguments: waterbody must be str
"""
pass
if waterbody in super().get_waterbodies():
self.habitat = {'waterbody': waterbody}
else:
self.habitat = {'waterbody': 'Invalid'}
guppy = Fish('Puddle')
print(guppy.habitat['waterbody'])
| true |
f91ebc9887e26dbf2296fcf851312b727bc2dc2c | bettyYHchen/discount_calculator | /discount_calculator.py | 1,065 | 4.125 | 4 | def calculate_discount(item_cost, relative_discount, absolute_discount):
if (type(item_cost) != float) and (item_cost != 0):
raise ValueError("item_cost must be a float or a zero")
if (type(relative_discount) != float) and (relative_discount != 0):
raise ValueError("relative_discount must be a float or a zero")
if (type(absolute_discount) != float) and (absolute_discount != 0):
raise ValueError("absolute_discount must be a float or a zero")
rdiscount = relative_discount/100.0
rrate = 1.0-rdiscount
price1 = item_cost * rrate
price2 = price1 - absolute_discount
if price2 < 0:
raise ValueError("Absolute discount is too large")
else:
return price2
def main():
item_cost = 200.0
relative_discount = -10.0
absolute_discount = 20.0
print "the original price is {:.2f}, after applying the relative discount {:.2f} and\
the absolute discount {:.2f}, the price is now {:.2f}".format(item_cost,relative_discount\
,absolute_discount,calculate_discount(item_cost,relative_discount,absolute_discount))
if __name__ == "__main__":
main()
| true |
5b9d7724a5f5b7c02ff7790a9268767d42ef5df6 | jacqdanso/cp_homework | /antwidanso_hw3_prob2c.py | 1,135 | 4.34375 | 4 | #########################################################################################
# Computational Physics HW3 Problem 2 c
#
# This program accepts user-specified coefficients of a quadratic equation and calculates
# its roots using the appropriate method
#
# INPUT:
# a,b,c ---> coefficients
#
# OUTPUT:
# x1, x2 --> roots
#
# Written by Jacqueline Antwi-Danso 02/17
#########################################################################################
from math import sqrt
from decimal import getcontext, Decimal
# take user input
a = float(input("Enter quadratic term coefficient : "))
b = float(input("Enter linear term coefficient : "))
c = float(input("Enter constant term coefficient : "))
#check difference between b and discriminant
diff = b - sqrt((b**2) - 4*a*c)
if diff > 10**(-3):
#calculate both roots with formula 1
x1 = (-1*b + sqrt((b**2) - 4*a*c))/(2*a)
x2 = (-1*b - sqrt((b**2) - 4*a*c))/(2*a)
else:
#calculate root 2 using formula 1 and root 1 using formula 2
x1 = (2*c)/((-1*b) - sqrt((b**2) - 4*a*c))
x2 = (-1*b - sqrt((b**2) - 4*a*c))/(2*a)
#output
print("The roots are",x1,"and",x2)
| true |
b157648fb51be6ceb23ef18b728970f20ec9a428 | jacqdanso/cp_homework | /antwidanso_hw3_prob2.py | 1,120 | 4.5625 | 5 | #########################################################################################
# Computational Physics HW3 Problem 2 a, b
#
# This program accepts user-specified coefficients of a quadratic equation and calculates
# its roots using two equivalent methods
#
# INPUT:
# a,b,c ---> coefficients
#
# OUTPUT:
# x1, x2 --> roots using formula 1
# y1, y2 --> roots using formula 1
#
# Written by Jacqueline Antwi-Danso 02/17
#########################################################################################
from math import sqrt
from decimal import getcontext, Decimal
# take user input
a = float(input("Enter quadratic term coefficient : "))
b = float(input("Enter linear term coefficient : "))
c = float(input("Enter constant term coefficient : "))
#calculate roots with formula 1
x1 = (-1*b + sqrt((b**2) - 4*a*c))/(2*a)
x2 = (-1*b - sqrt((b**2) - 4*a*c))/(2*a)
#output
print("With formula 1, the roots are",x1,"and",x2)
#calculate roots with formula 2
y1 = (2*c)/((-1*b) - sqrt((b**2) - 4*a*c))
y2 = (2*c)/((-1*b) + sqrt((b**2) - 4*a*c))
#output
print("With formula 2, the roots are",y1,"and",y2)
| true |
3953e874bf7e293bc16c1e4309d4ac717e42ae63 | namelessvoid/piranhas | /nibbles/circularlist.py | 900 | 4.25 | 4 |
class CircularList(list):
"""A list which provides a function to iterate through it. If the end is
reaced, it continues from the beginning. You get a endless repeating
list so to speak."""
def __init__(self):
"""Initializes the list."""
list.__init__(self)
self._current = 0
def next(self):
"""Returns the next item in the list.
Return:
next object in the list or None if list is empty"""
if len(self) == 0:
return None
else:
self._current += 1
self._current %= len(self)
return self.current()
def current(self):
"""Returns the current item in the list.
Return:
current object in the list or None if list is empty"""
if len(self) == 0:
return None
return self[self._current]
| true |
de27b3fe3cb460ee8e9295c01b75aa89e12b6173 | juneju-darad/simple-guessing-game | /guessingGame.py | 328 | 4.1875 | 4 | import random
actual_number = random.randint(1,10)
chance = 0
print('Guess an integer between 1 to 10. You have only 3 Chances!')
while chance < 3:
x = int(input('Your Guess: '))
if x == actual_number:
print("You Won!")
break
else:
chance += 1
else:
print("You Failed :( Computer Won!")
| true |
5b7ea07e4890a781501376a55236afe2a4b7efa5 | asamattson/Python | /Imperial to Metric Converter.py | 767 | 4.21875 | 4 | print("-=-=-=-=-=-=-=-=-=-=Imperial to Metric Converter-=-=-=-=-=-=-=-=-=-=")
print("Putting in non-numerical values will result in a program crash.")
# Inches to Centimeters converter
inches = input("How many inches would you like to convert to centimeters? ")
inches = int(inches)
cm = (inches * 2.54)
print(cm)
# Pounds to Kilograms converter
pounds = input("How many pounds would you like to convert to kilograms? ")
pounds = int(pounds)
kg = (pounds / 2.2)
print(kg)
# Miles to Kilometers
miles = input("How many miles would you like to convert to kilometers?")
miles = int(miles)
kilo = (miles * 1.609)
print(kilo)
# Yards to meters
yards = input("How many yards would you like to convert to meters")
yards = int(yards)
meters = (yards / 1.094)
print(meters) | true |
cefa8f8518374f04fc088f3e9416ed0675a532f0 | alexandrucatanescu/neural-program-comprehension | /stimuli/Python/one_file_per_item/en/102_# str_if 12.py | 207 | 4.15625 | 4 | letters = ["a", "e", "t", "o", "u"]
word = "CreepyNuts"
if (word[1] in letters) and (word[6] in letters):
print(0)
elif (word[1] in letters) or (word[6] in letters):
print(1)
else:
print(2)
| false |
935d5a95a65f52c34c990a51fdd4f2321bcefb0a | kelr/practice-stuff | /project_euler/1.py | 432 | 4.25 | 4 | """
Project Euler Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def calc_multiples():
curr_sum = 0
for n in range(1,1000):
if n % 3 == 0:
curr_sum += n
elif n % 5 == 0:
curr_sum += n
return curr_sum
print(calc_multiples())
| true |
4a01d0e115918d34d89eb569bd845c47dfa304ca | lpb3296/CSCI-141 | /hw/hw1/hw1/cmd_divisible.py | 586 | 4.28125 | 4 | # Liam Barry
# CSCI-141: hw1
# Conditionals
"""
determining whether the greater of the two numbers are divisible by each other
return True if numbers are divisible
returns False if the numbers are not
"""
def divisible(num1, num2):
if num1 > num2:
ans = num1 % num2
if ans == 0:
print('true')
return True
else:
print('false')
return False
else:
ans = num2 % num1
if ans == 0:
print('true')
return True
else:
print('false')
return False
| true |
9be82fbad7e1a6e6bd1578b80799c81c40d35558 | jiatongw/notes | /code/queue_stack/stack_dequeue.py | 1,482 | 4.21875 | 4 | """ How to use multiple stacks to implement a de-queue
De-queue
Left xxxxxxxxxxxx Right
left.add() right.add()
left.remove() right.remove()
Method 1: use two stacks
stack 1 || || stack 2
<-- 8 7 6 5 || || 1 2 3 4 -->
left.add() == stack1.appnd() O(1)
right.add() == stack2.appnd() O(1)
left.remove():
case 1 : stack1.pop() if stack 1 is not empty
case 2 : stack 1 == empty, then move all element from stack2 to stack 1, then call stack1.pop()
O(n)
right.remove(): similiar to left.remove()
极端case: 如果一直循环往复调用left.remove()后在调用right.remove(), 那么每次都要先把element从一个stack移动到另一个stack
"""
"""
follow up: 优化
给一个stack 3 as buffer
stack 1 || || stack 2
empty || || 1 2 3 4 5 6 7 8
如果遇到一个stack 空了,需要用到stack3 为Buffer,把stack2 中 一半 的element 放到stack1,
empty || || 1 2 3 4 5 6 7 8 --> 4 3 2 1 || || 5 6 7 8
先把 half element 放到stack3:
stack 1 || || stack 2
empty || || 1 2 3 4
stack3 || 8 7 6 5
然后把stack 2剩下的element放到 stack 1
stack 1 || || stack 2
4 3 2 1 || || empty
stack3 || 8 7 6 5
再把stack 3 element放回 stack 2
stack 1 || || stack 2
4 3 2 1 || || 5 6 7 8
stack3 ||
保证 左右stack 数据平均
这样的话 remove()操作平均时间复杂度 amortized time == O(1)
stack1: for left head
stack2: for right head
stack3: for buffer half element
"""
| false |
dcc663ab37a3d54b2832f32e5301e3226d2fb1e3 | PrathapReddy456/SeleniumPython | /PythonBasics/Demo1.py | 582 | 4.53125 | 5 |
print("Hello")
# Comments
a =3;
print(a)
Str ="Hello World"
print(Str)
##format example
b,c,d = 5,6.4,"Great"
"{}{}".format("Value is", b)
## List Examples
values = [1, 2, "Prathap", 4, 5]
print(values[0]) #1
print(values[-1]) # to get last value from list
print(values[1:3])
values.insert(3,"Reddy")
values.append("End")
print(values)
## Tuple Examples
val = (1, 2, "Pathap", 4.5)
## Dictionary Example
dict = {"a":2, 4:"bcd", "c":"Hello"}
print(dict[4])
print(dict["c"])
dictt = {}
dictt["firstName"] = "Prathap"
dictt["lastName"] = "Reddy"
dictt["age"] = "28"
print(dictt) | false |
9c072994be86a7e797221d3485afc8a76996e7ab | qixiaobo/navi-misc | /motion/py/Dance/Systems.py | 2,987 | 4.125 | 4 | """A collection of chaotic systems.
These classes represent chaotic systems. They are intended for use with the
ODE classes in ODE.py.
:Authors:
Evan Sheehan <Wallace.Sheehan@gmail.com>
"""
import Numeric
class System:
"""Interface implemented by all systems.
Implementing this interface requires all `System`\s to be callable. This
insures that they are compatible with any class inheriting from `ODE`.
"""
def __call__(self, args, time, step):
"""Abstract `__call__` function.
All `System` subclasses should override this function. Raises an
exception if it gets called, indicating that the subclass did not
implement `__call__`.
"""
raise Exception ("__call__ not implemented in %s" % (self.__class__))
class Lorenz(System):
"""The Lorenz system.
Members:
- ``a``, ``r``, ``b`` The parameters of the system
"""
def __init__(self, a, r, b):
"""Create a Lorenz object with parameters ``a``, ``r``, and ``b``."""
self.a = a
self.r = r
self.b = b
def __call__(self, args, time, step):
"""Calculate a value in the system.
Arguments:
- ``args`` A list or tuple of 3 values
- ``time`` IGNORED
- ``step`` IGNORED
Returns:
A Numeric array that is the solution given the 3 values in args.
"""
x, y, z = args
return Numeric.array([self.a*(y - x),
self.r*x - y - x*z,
x*y - self.b*z])
class Rossler(System):
"""The Rossler system.
Members:
- ``a``, ``b``, ``c`` Parameters of the system
- ``deltaMatrix``
"""
def __init__(self, a, b, c, delta=False):
"""Create a Rossler object.
Arguments:
- ``a``, ``b``, ``c`` Parameters of the system
- ``delta``
"""
self.a = a
self.b = b
self.c = c
self.deltaMatrix = delta
def __call__(self, args, time, step):
"""Calculate a value in the system.
Arguments:
- ``args`` A list or tuple of 3 values
- ``time`` IGNORED
- ``step`` IGNORED
Returns:
A Numeric array that is the solution given the values in args.
"""
x, y, z = args
if self.deltaMatrix:
matrix = [
[self.a*(y-x), self.r*x-y-x*z, x*y-self.b*z],
[-self.a*xx+self.a*xy, -self.a*yx+self.a*yy,
-self.a*zx + self.a*zy],
[xx*(self.r-z)-xy-x*xz, yx*(self.r-z)-yy-x*yz,
zx*(self.r-z)-zy-x*zz],
[y*xx+x*xy-self.b*xz, y*yx+x*yy-self.b*yz, y*zx+x*zy-self.b*zz]]
else:
matrix = [-(y + z),
x + self.a*y,
self.b + z*(x - self.c)]
return Numeric.array(matrix)
# vim:ts=4:sw=4:et
| true |
c4575271bd93383b4f1ffd4f2ee3e988a9d0239a | gsuryalss/sorting-algorithms-py | /heap_sort.py | 1,937 | 4.25 | 4 | """
In max-heaps, maximum element will always be at the root. Heap Sort uses this property of heap to sort the array.
* Initially build a max heap of elements in Arr.
* The root element, that is Arr[1], will contain maximum element of
* Arr. After that, swap this element with the last element of
* Arr and heapify the max heap excluding the last element which is already in its correct position and then decrease
the length of heap by one.
* Repeat the step 2, until all the elements are in their correct position.
"""
def build_heap(arr_hp, hp_size, j):
max_val = j
left_val = 2 * j + 1
right_val = 2 * j + 2
# print(j, left_val, right_val)
if left_val < hp_size and arr_hp[max_val] < arr_hp[left_val]:
max_val = left_val
# print("left_val", left_val)
# print(j)
# print(arr_hp[max_val])
if right_val < hp_size and arr_hp[max_val] < arr_hp[right_val]:
max_val = right_val
# print("right_val", right_val)
# print(j)
# print(arr_hp[max_val])
# print("Max_val", max_val)
if max_val != j:
arr_hp[j], arr_hp[max_val] = arr_hp[max_val], arr_hp[j]
# re-build the heap with parent maximum node
arr_hp = build_heap(arr_hp, hp_size, max_val)
# print("build array", arr_hp)
return arr_hp
def heap_sort(arr_param, n):
# print("Array", arr_param)
# build a max heap
for i in range(n, -1, -1):
arr_param = build_heap(arr_param, n, i)
# list the elements one by one
for p in range(n-1, 0, -1):
arr_param[p], arr_param[0] = arr_param[0], arr_param[p]
arr_param = build_heap(arr_param, p, 0)
# print("Sorted", arr_param)
return arr_param
arr = []
print("Heap Sort\n")
m = int(input("Enter the number of elements>>"))
for k in range(m):
arr.append(int(input()))
# heap_sort(arr, m)
print("Sorted Array: ", heap_sort(arr, m))
| true |
ed12a386e1139b924176f7a07c6d1b959fab7da0 | Giantcatasaurus/All-my-projects | /Trapesoid Calc.py | 266 | 4.1875 | 4 | print ("Area of a trapezoid")
h = float(input("Enter the height of the trapezoid: "))
a = float(input("Enter the length of the bottom base: "))
b = float(input("Enter the length of the top base: "))
x = (a + b) / 2
z = x * h
print ("the area of the trapezoid is", z) | true |
d88991154ebb255f93876c4b81d1fa85fee6efc7 | abate2283/PYTHON | /userInput.py | 697 | 4.3125 | 4 | #name = "Joe"
#result = input("What is your name?")
#print(f"Hello {result} My name is {name}? ")
#my_name = "Josiah"
#What_about = input("Hi, there what is your name?")
#print(f"{What_about} You can call me {my_name}")
# This section below are quizzes
#your_name = input('Enter your name: ')
#print(f'Hello {your_name}!')
# With these information you can program Alexa or Siri!
# Just use text to speech. Praise God!
#mon_nom = input("What is your name?")
#ton_nom = "Hello, I am Alfred"
#print(f"{mon_nom} {ton_nom}")
my_namesake = "Jonathan"
your_namesake = input("Please enter your name, thanks.")
print(f"{your_namesake} Thanks, I am {my_namesake} I will be happy to assist you.")
| true |
39dcf2dbcf29c61cffb2309df5959624e944c665 | Gayatri-Shastri7/100Days_Coding_Challenge | /Dictionaries/7.Frequency of numbers in a list.py | 953 | 4.3125 | 4 | '''
Frequency of numbers in a list
Given a list of integers, find the frequency of each integer in the list.
Complete the given method called solve which takes as parameter a list of integers called items, Print the frequency of Integers in sorted by keys.
Example Input:
1, 7, 9, 100, 3, 8, 2, 50, 21, 9 , 200, 1, 200, 200, 200
Output:
1 : 2
2 : 1
3 : 1
7 : 1
8 : 1
9 : 2
21 : 1
50 : 1
100 : 1
200 : 4
'''
def solve(items):
# write a code from here
all_freq = {}
for i in items:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
for i in sorted (all_freq) :
print (str(i)+':',all_freq[i])
'''
Status
Test Cases Passed
Expected Output
Input:
1 7 9 100 3 8 2 50 21 9 200 1 200 200 200
Output:
1: 2
2: 1
3: 1
7: 1
8: 1
9: 2
21: 1
50: 1
100: 1
200: 4
Your Output
Input:
1 7 9 100 3 8 2 50 21 9 200 1 200 200 200
Output:
1: 2
2: 1
3: 1
7: 1
8: 1
9: 2
21: 1
50: 1
100: 1
200: 4
''' | true |
7c3c41c624a18c1e14e9c3dec14af3cacf9ef4d3 | Gayatri-Shastri7/100Days_Coding_Challenge | /Queues/Queues_operations.py | 1,500 | 4.1875 | 4 | '''
Implement a Queue and its operations
Write a program to create a Queue and it's operations which is given below. Name you class as Queue. In Queue class use Integer array to implement Queue. Check the code for more details.
Operations:
enque accepts an integer and adds to the Queue
deque remove the element from Queue and prints the value which is removed.
peek it returns the latest element from the queue
isEmpty returns true if Queue is empty, and false otherwise
isFull returns true if Queue is Full, and false otherwise
'''
class Queue:
def __init__(self,n):
self.data=[]
self.number=n
self.front=self.rear=0
def enque(self,element):
if(self.rear!=self.number):
self.data.append(element)
self.rear += 1
def deque(self):
if(self.front!=self.rear):
x=self.data.pop(0)
print("deque:"+str(x))
self.rear -= 1
else:
print("deque:"+"None")
def peek(self):
return self.data[0]
def isEmpty(self):
if(self.rear==0):
return "true"
else:
return "false"
def isFull(self):
if(self.rear==self.number):
return "true"
else:
return "false"
'''
Status
Test Cases Passed
Input
6
5
1 1
1 2
4
5
2
3
Expected Output
enque:1
enque:2
isEmpty:false
isFull:false
deque:1
peek:2
Your Output
enque:1
enque:2
isEmpty:false
isFull:false
deque:1
peek:2
''' | true |
7ee95f02805f86ac7c4a77f605a3c5f5292cf16f | Gayatri-Shastri7/100Days_Coding_Challenge | /Stacks/stack_operations.py | 2,322 | 4.25 | 4 | ### write your solution below this line ###
class Stack:
# Constructor to initialize the stack
def __init__(self, size):
self.arr = [None] * size
self.capacity = size
self.top = -1
# Function to add an element `x` to the stack
def push(self, x):
if self.isFull():
exit(1)
self.top = self.top + 1
self.arr[self.top] = x
# Function to pop a top element from the stack
def pop(self):
# check for stack underflow
if self.isEmpty():
exit(1)
# decrease stack size by 1 and (optionally) return the popped element
top = self.arr[self.top]
self.top = self.top - 1
return top
# Function to return the top element of the stack
def peek(self):
if self.isEmpty():
exit(1)
return self.arr[self.top]
# Function to return the size of the stack
def size(self):
return self.top + 1
# Function to check if the stack is empty or not
def isEmpty(self):
if self.size() == 0:
return 1
else:
return 0
# Function to check if the stack is full or not
def isFull(self):
if self.size() == self.capacity:
return 1
else:
return 0
if __name__ == "__main__":
test_cases=int(input()) # number of test cases
size=int(input()) # size of Stack
stack=Stack(size) # creating new stack object
while(test_cases>0):
instruction=input().split()
val=0
if len(instruction)>1:
val=int(instruction[1])
instruction=int(instruction[0])
#####
# Instruction 1 means Push
# Instruction 2 means Pop
# Instruction 3 means Peek
# Instruction 4 means isEmpty
# Instruction 5 means isFull
#####
if(instruction==1):
print(f'push:{val}')
stack.push(val)
elif (instruction==2):
print(f'pop:{stack.pop()}')
elif (instruction==3):
print(f'peek:{stack.peek()}')
elif(instruction==4):
print(f'isEmpty:{stack.isEmpty()}')
elif(instruction==5):
print(f'isFull:{stack.isFull()}')
test_cases=test_cases-1 | true |
9575e49dfe07d51ef276f488a7e3bf205d629619 | explosivelamp/hello-world | /Week10Project1-Schultze.py | 326 | 4.46875 | 4 | from turtle import *
def drawCircle(t, x, y, radius):
"""Draws a circle using turtle t, with origin at x, y, with a specified radius"""
t.up()
t.goto(x, y - radius)
t.down()
for count in range(120):
distance = (2.0 * 3.14 * radius )/ 120.0
t.left(3)
t.forward(distance)
| true |
248dd9724b55d15db0b59ba308da797e648e45ae | fovegage/learn-python | /Python设计模式/代理模式/代理模式.py | 1,608 | 4.25 | 4 | from abc import ABC, abstractmethod
"""
参考文档
https://www.starky.ltd/2020/12/25/python-design-patterns-proxy-pattern/
"""
class Payment(ABC):
@abstractmethod
def do_buy(self, ticket):
"""
must implement
"""
class ScenicArea(Payment):
"""
真正的出票处
"""
def __init__(self):
self.tickets = 100
def check(self):
if self.tickets < 0:
return False
return True
@property
def modify_tickets(self):
return self.tickets
@modify_tickets.setter
def modify_tickets(self, ticket):
self.tickets -= ticket
def do_buy(self, ticket):
status = self.check()
if status:
print('buy success')
self.modify_tickets = ticket
else:
print('buy fail')
class TravelAgency(Payment):
"""
代理出票处
"""
def __init__(self):
# 构造方法 实例化真正操作的对象
self.scenic = ScenicArea()
def do_buy(self, ticket):
self.scenic.do_buy(ticket)
class Tourist:
def __init__(self):
self.travel = TravelAgency()
def make_pay(self):
self.travel.do_buy(9)
if __name__ == '__main__':
"""
加入 我去买景点门票 我需要一个代理商去购买
在 价格一样的情况下消费者看来 代理商出票和 景区出票 是一回事 程序中就是继承于同一个基类
寻找方是发出请求的一方 提供方是根据请求提供资源的一方
"""
tourist = Tourist()
tourist.make_pay()
| true |
2195eb246ce8e1d0d26b9656bc454462d1921a27 | lony25/Stuff | /QAM/quesId.py | 789 | 4.125 | 4 |
def quesId(str):
for word in str.split(" "):
if word.lower() == 'who':
print 'Who question'
elif word.lower() == 'how':
print 'How question'
elif word.lower() == 'when':
print 'When question'
elif word.lower() == 'where':
print 'Where question'
elif word.lower() == 'why':
print 'Why question'
elif word.lower() == 'what':
print 'What question'
elif word.lower() == 'which':
print 'Which question'
elif word.lower() == 'whom':
print 'Whom question'
elif word.lower() == 'name':
print 'Name question'
if __name__ == '__main__':
question = 'Who is going to do the utensils now ?'
quesId(question)
| false |
209c57da798ce8e37e6ad7db8ab4aa5264a4e14f | dogac00/Algorithms | /random-walk-algorithm.py | 1,370 | 4.1875 | 4 | import random
def random_walk(n):
"""Return coordinates after 'n' block random walk."""
x=0
y=0
for i in range(n):
step = random.choice(['N','S','E','W'])
if step == 'N':
y += 1
elif step == 'S':
y -= 1
elif step == 'E':
x += 1
else:
x -= 1
return (x,y)
for i in range(25):
walk = random_walk(10) # take 10 steps each random walk
print(walk, "Distance from home = ", abs(walk[0]), abs(walk[1]))
# Example Output
# (2, 2) Distance from home = 2 2
# (-1, -3) Distance from home = 1 3
# (3, -1) Distance from home = 3 1
# (2, -2) Distance from home = 2 2
# (-2, -4) Distance from home = 2 4
# (1, -1) Distance from home = 1 1
# (4, 0) Distance from home = 4 0
# (1, 1) Distance from home = 1 1
# (0, 0) Distance from home = 0 0
# (1, 5) Distance from home = 1 5
# (0, 4) Distance from home = 0 4
# (2, 2) Distance from home = 2 2
# (2, 0) Distance from home = 2 0
# (3, -3) Distance from home = 3 3
# (-1, 1) Distance from home = 1 1
# (1, -1) Distance from home = 1 1
# (1, -3) Distance from home = 1 3
# (3, 3) Distance from home = 3 3
# (1, -1) Distance from home = 1 1
# (-4, 2) Distance from home = 4 2
# (-4, 2) Distance from home = 4 2
# (-3, 5) Distance from home = 3 5
# (-2, 2) Distance from home = 2 2
# (-1, 1) Distance from home = 1 1
# (0, 0) Distance from home = 0 0
| true |
4d18133761d4af500aad7dce3acc9da90dcf842e | yhyecho/Python3 | /day03/lambda.py | 1,176 | 4.125 | 4 | # 匿名函数
# 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。
# 在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:
L = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(L)
# 通过对比可以看出,匿名函数lambda x: x * x实际上就是:
def f(x):
return x * x
# 关键字lambda表示匿名函数,冒号前面的x表示函数参数。
# 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
# 用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。
# 此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
f2 = lambda x: x * x
print(f2)
print(f2(5))
# 同样,也可以把匿名函数作为返回值返回,比如:
def build(x, y):
return lambda: x * x + y * y
# Python对匿名函数的支持有限,只有一些简单的情况下可以使用匿名函数。
| false |
9929866836660b64551dffbf4b58debda22efd37 | im965/final_project | /portfolioFactory/utils/getFileLocation.py | 483 | 4.15625 | 4 | """
This function creates a pop-up that asks the user to select a file for input
Author: Peter Li
"""
import Tkinter,tkFileDialog
def getFileLocation(msg):
''' This function opens a GUI that takes in user selection files
Input:
- msg (str): Message displayed on the top of the window
'''
root = Tkinter.Tk()
root.withdraw()
filePath = tkFileDialog.askopenfilename(initialdir="./",title = msg)
return filePath
| true |
77517f7535d355649d1fa11c2693da0555041507 | Venkatesh123-dev/Python_Basics | /Day_04_05.py | 1,790 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 19:13:24 2020
@author: venky
"""
def is_prime(num):
for i in range(2,num):
if num % i == 0:
return False
return True
test = [3, 6, 11, 32]
for num in test:
print(f"{num} is a prime number {is_prime(num)}")
def nth_prime(x):
num = 3
prime = 2
if x ==1:
return 2
while prime < x:
num += 2
if is_prime(num):
prime += 1
print(num)
nth_prime(10)
primes = [i for i in range(1,101) if is_prime(i)]
print(primes)
import random
while True:
number = random.randint(1,20)
print(number)
try:
guess = int(input("Enter a number"))
while guess!=number:
if guess > number:
print("Please enter a small number")
guess = int(input("Enter a number"))
else:
print("Please enter a larger number")
guess = int(input("Enter a number"))
else:
print("You guess the correct number")
except ValueError:
print("oops Please enter correct number")
choice = input("Do you want to play again ? y/n :").lower()
if choice == 'n':
break
def leap_year(x):
if x %4 == 0:
if x % 100 == 0:
if x % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
years = [1992, 1600, 2000, 2020]
for year in years:
print(year,leap_year(year))
| true |
a9567c6fc2a06abe72f0354af4af481f5ea0ede7 | Venkatesh123-dev/Python_Basics | /Day_04_02.py | 1,225 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 11:35:16 2020
@author: venky
"""
import sqlite3
class Database(object):
def __init__(self):
self.connection = sqlite3.connect("Database.db")
self.cursor = self.connection.cursor()
self.table_name = "Table_Example"
self.cursor.execute(f"CREATE TABLE IF NOT EXISTS {self.table_name} \
(column_1 INT, column_2 TEXT, column_3 REAL)")
def insert_data(self):
column_1 = int(input("Enter Int: "))
column_2 = input("Enter String: ")
column_3 = float(input("Enter Float: "))
self.cursor.execute(f"INSERT INTO {self.table_name} \
(column_1, column_2, column_3) VALUES(?,?,?)",(column_1, column_2, column_3))
self.connection.commit()
print("Data Saved")
def read_data(self):
self.cursor.execute(f"SELECT * FROM {self.table_name}")
for row in self.cursor.fetchall():
print(row)
print("task completed")
if __name__ == "__main__":
database = Database()
database.insert_data()
database.read_data()
database.cursor.close()
database.connection.close() | false |
8eac1c8b76e8e7aa4add2872bd63622706faa21f | Venkatesh123-dev/Python_Basics | /data_structure/Queue.py | 1,951 | 4.1875 | 4 | """A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear,” and the removal of existing items occurs at the other end, commonly called the “front.” As an element enters the queue it starts at the rear and makes its way toward the front, waiting until that time when it is the next element to be removed.
The most recently added item in the queue must wait at the end of the collection. The item that has been in the collection the longest is at the front. This ordering principle is sometimes called FIFO, first-in first-out. It is also known as “first-come first-served.
The queue abstract data type is defined by the following structure and operations. A queue is structured, as described above, as an ordered collection of items which are added at one end, called the “rear,” and removed from the other end, called the “front.” Queues maintain a FIFO ordering property. The queue operations are given below.
Queue() creates a new queue that is empty. It needs no parameters and returns an empty queue.
enqueue(item) adds a new item to the rear of the queue. It needs the item and returns nothing.
dequeue() removes the front item from the queue. It needs no parameters and returns the item. The queue is modified.
isEmpty() tests to see whether the queue is empty. It needs no parameters and returns a boolean value.
size() returns the number of items in the queue. It needs no parameters and returns an integer."""
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
q=Queue()
q.enqueue(4)
q.enqueue('dog')
q.enqueue(True)
print(q.size())
print(q.isEmpty())
print(q.enqueue(8.4))
q.dequeue()
q.dequeue()
print(q.size())
| true |
3677ba539c4dd3c9d78b1be30f85f494a6d16a27 | Venkatesh123-dev/Python_Basics | /Day_12_03.py | 2,989 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 4 12:14:34 2020
@author: venky
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3 """
s = raw_input()
d = {"DIGITS":0, "LETTERS":0}
for c in s:
if c.isdigit():
d["DIGITS"]+=1
elif c.isalpha():
d["LETTERS"]+=1
else:
pass
print "LETTERS", d["LETTERS"]
print "DIGITS", d["DIGITS"]
word = input()
letter,digit = 0,0
for i in word:
if ('a'<=i and i<='z') or ('A'<=i and i<='Z'):
letter+=1
if '0'<=i and i<='9':
digit+=1
print("LETTERS {0}\nDIGITS {1}".format(letter,digit))
word = input()
letter, digit = 0,0
for i in word:
if i.isalpha(): # returns True if alphabet
letter += 1
elif i.isnumeric(): # returns True if numeric
digit += 1
print(f"LETTERS {letter}\n{digits}") # two different types of formating method is shown in both solution
import re
input_string = input('> ')
print()
counter = {"LETTERS":len(re.findall("[a-zA-Z]", input_string)), "NUMBERS":len(re.findall("[0-9]", input_string))}
print(counter)
"""
Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
"""
s = raw_input()
d = {"UPPER CASE":0, "LOWER CASE":0}
for c in s:
if c.isupper():
d["UPPER CASE"]+=1
elif c.islower():
d["LOWER CASE"]+=1
else:
pass
print "UPPER CASE", d["UPPER CASE"]
print "LOWER CASE", d["LOWER CASE"]
word = input()
upper,lower = 0,0
for i in word:
if 'a'<=i and i<='z' :
lower+=1
if 'A'<=i and i<='Z':
upper+=1
print("UPPER CASE {0}\nLOWER CASE {1}".format(upper,lower))
word = input()
upper,lower = 0,0
for i in word:
lower+=i.islower()
upper+=i.isupper()
print("UPPER CASE {0}\nLOWER CASE {1}".format(upper,lower))
word = input()
upper = sum(1 for i in word if i.isupper()) # sum function cumulatively sum up 1's if the condition is True
lower = sum(1 for i in word if i.islower())
print("UPPER CASE {0}\nLOWER CASE {1}".format(upper,lower))
"""
Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
"""
a = raw_input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print n1+n2+n3+n4
a = input()
total = int(a) + int(2*a) + int(3*a) + int(4*a) # N*a=Na, for example a="23", 2*a="2323",3*a="232323"
print(total)
from functools import reduce
x = input('please enter a digit:')
reduce(lambda x, y: int(x) + int(y), [x*i for i in range(1,5)])
| true |
ba5b971c83c2bcaf5e025cdfe6f2b2423089962b | kislev-owo/Python-Loops-Lists-Tutorial-Exercises | /exercises/12.2-Map_function_inside_variable/app.py | 313 | 4.21875 | 4 | names = ['Alice','Bob','Marry','Joe','Hilary','Stevia','Dylan']
def prepender(name):
return "My name is: " + name
#Your code go here:
result = list(map(prepender, names)) ## como en el ejercicio anterior
## mapeamos la funcion prepender con la propiedad name que es
## devuelta en el return
print(result) | false |
f24a9daa126de0737c6d1f2b29fea0335f7c9674 | SebastianDica/ExpediaDOC-PythonCourse-London | /Session 2/p2/main.py | 257 | 4.28125 | 4 | x = {}
x['property3'] = [ "hello", "world" ]
print(x['property3']) # What would happen here?
#
# x['property4'] = { "property1": 10 }
# print(x['property4']) # What would happen here?
#
# x['property5'] = x
# print(x['property5']) # What would happen here? | false |
6163afa99abe2f10c85071a61e6e4123dac172fa | Oleona/ITMO_Python_Homeworks2 | /homework01/vigenere.py | 2,570 | 4.28125 | 4 | def encrypt_vigenere(plaintext: str, keyword: str) -> str:
"""
Encrypts plaintext using a Vigenere cipher.
>>> encrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> encrypt_vigenere("python", "a")
'python'
>>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
'LXFOPVEFRNHR'
"""
ciphertext = ""
# PUT YOUR CODE HERE
# plaintext = "ATTACKATDAWN"
# keyword = "LEMON"
codearray = []
keyarray = []
while len(plaintext) > len(keyword):
keyword += keyword
# print(keyword)
for letter in plaintext:
code = ord(letter)
codearray.append(code)
# print(codearray)
for keyletter in keyword:
keycode = ord(keyletter)
keyarray.append(keycode)
# print(keyarray)
for i in range(0, len(codearray)):
if ord('A') <= (codearray[i]) <= ord('Z'):
diff = codearray[i] - ord('A')
shift = keyarray[i] - ord('A')
code = (diff + shift) % 26 + ord('A')
elif ord('a') <= (codearray[i]) <= ord('z'):
diff = codearray[i] - ord('a')
shift = keyarray[i] - ord('a')
code = (diff + shift) % 26 + ord('a')
elif 32 <= codearray[i] <= 64:
code = codearray[i]
ciphertext += chr(code)
return ciphertext
def decrypt_vigenere(ciphertext: str, keyword: str) -> str:
"""
Decrypts a ciphertext using a Vigenere cipher.
>>> decrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> decrypt_vigenere("python", "a")
'python'
>>> decrypt_vigenere("LXFOPVEFRNHR", "LEMON")
'ATTACKATDAWN'
"""
plaintext = ""
# PUT YOUR CODE HERE
plainarray = []
keyarray = []
while len(ciphertext) > len(keyword):
keyword += keyword
# print(keyword)
for letter in ciphertext:
code = ord(letter)
plainarray.append(code)
# print(plainarray)
for keyletter in keyword:
keycode = ord(keyletter)
keyarray.append(keycode)
# print(keyarray)
for i in range(0, len(plainarray)):
if ord('A') <= (plainarray[i]) <= ord('Z'):
diff = plainarray[i] - ord('A')
shift = keyarray[i] - ord('A')
code = (diff - shift) % 26 + ord('A')
elif ord('a') <= (plainarray[i]) <= ord('z'):
diff = plainarray[i] - ord('a')
shift = keyarray[i] - ord('a')
code = (diff - shift) % 26 + ord('a')
elif 32 <= plainarray[i] <= 64:
code = plainarray[i]
plaintext += chr(code)
return plaintext
| false |
fc719c3dbe215cecab926bc32c7a0f4aae0fbcde | lnarasim/geekshub_python_playground | /geekshub_pyproblems/my_queue.py | 1,626 | 4.25 | 4 | """A simple queue - FIFO implementation that has fixed number of slots. Each slot
can hold any object
"""
DEFAULT_QUEUE_SIZE = 10
class Queue:
"""Queue has fixed number of slots and each slot can hold any object.
If the number of slots is not passed or invalid value, queue defaults to
DEFAULT_QUEUE_SIZE."""
def __init__(self, max_slots=DEFAULT_QUEUE_SIZE):
if not isinstance(max_slots, int) or max_slots < 1:
self.max_slots = DEFAULT_QUEUE_SIZE
else:
self.max_slots = max_slots
self._container = []
def add(self, an_object):
"""Add an object if queue is not full"""
if len(self._container) >= self.max_slots:
raise QueueOverflow("Queue is full")
self._container.append(an_object)
def retrieve(self):
"""Remove and get the first inserted item if the queue is not empty"""
if not self._container:
raise QueueUnderflow("Queue is empty")
return self._container.pop(0)
def __contains__(self, item):
return item in self._container
def __len__(self):
return len(self._container)
def clear(self):
"""Clears the queue"""
return self._container.clear()
class QueueOverflow(Exception):
"""Indicates that the queue is full"""
def __init__(self, message):
super(QueueOverflow, self).__init__(message)
self.message = message
class QueueUnderflow(Exception):
"""Indicates that the queue is empty"""
def __init__(self, message):
super(QueueUnderflow, self).__init__(message)
self.message = message
| true |
336925e06d85508424cc28b0f7b80753cbf1fa35 | leoloo0510/Enterprise | /2-work/Python/10pcs proj/10samples/nth_day_4.py | 853 | 4.25 | 4 | # -*- coding: utf-8 -*-
def leap(year):
if ((year%4==0) and (year%100 !=0)) or year%400 ==0:
return 1
else:
return 0
def enter_date():
date = input('pls input date as format yyyy-mm-dd:\n' )
[year,month,day] = date.split('-')
return int(year),int(month),int(day)
delta = [1,-2,1,0,1,0,1,1,0,1,0,1]
def month_days(month):
return delta[month-1] + 30
def passed_month_days(month):
# days = 0
if month ==1:
return 0
else:
return month_days(month-1) + passed_month_days(month-1)
if __name__ == '__main__':
(year,month,day) = enter_date()
# for i in range(1,12):
# print(month_days(i))
# print(passed_month_days(3)
days = passed_month_days(month) + day
if leap(year) and month >= 3:
days = days+1
print('this is %s,the %sth day' %(year,days))
| false |
6b9a0ef8ef699f3e7e2480d0a2196671efda4938 | tanyabolla/Coursera-Courses | /Python For Everybody/Assignment_3.2.py | 808 | 4.25 | 4 | '''
3.2 Rewrite the pay program from Assignment 3.1 using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program.
The following shows two executions of the program:
'''
hours = input("Enter hours: ")
rph = input("Enter hourly rate: ")
'''
try:
fhrs = float(hours)
except:
print("Error. Enter a numeric input.")
try:
frph = float(rph)
except:
print("Error. Enter a numeric input.")
'''
#Do this, because both data has to be numerical for the program to work
try:
fhrs = float(hours)
frph = float(rph)
except:
print("Error. Enter a numeric input.")
quit()
if fhrs > 40.0:
pay = (40 * frph)
overhrs = fhrs - 40.0
overpay = overhrs * frph * 1.5
print(pay + overpay)
else:
print(fhrs * frph)
| true |
b33e44b71d210d38748702d8e39921f4b569516f | KangboLu/Data-Structure-and-Algorithms | /Algorithms Techniques/1. Sorting and Selection/quick-sort/quickSortHoare.py | 1,149 | 4.15625 | 4 | """ Hoare partition scheme Quick Sort"""
# partition the array
def partition(array, left, right):
pivot = array[(left+right)/2]; # choose rightmost element for comparison
# swap elements < pivot with current element in a loop
while left <= right:
while array[left] < pivot:
left+=1; # index of left element should be on the right
while array[right] > pivot:
right-=1; # index of right element should be on the left
# swap elements and move left and right indices
if left <= right:
array[left], array[right] = array[right], array[left]
left+=1
right-=1
return left;
# divide array into halves
def quick_sort(array, left, right):
if left < right:
pivot = partition(array, left, right)
quick_sort(array, left, pivot - 1)
quick_sort(array, pivot + 1, right)
# testing the algorithm
print("\nHoare partition scheme------")
print("Quick sort O(nlogn) algorithm:\n")
# array before sorting
array = [9, 8, 7, 6, 5, 4, 3, 2, 1]
print("Array before sorting")
print(array)
# test the quick sort algorithm
print("Array after sorting")
quick_sort(array, 0, len(array)-1)
print(array) | true |
a43c7f5aae1bb6fb45450cd2197bc40e74156a92 | KangboLu/Data-Structure-and-Algorithms | /Data Structures/8. Tree/Trie/trie.py | 1,822 | 4.25 | 4 | # python implementation of trie
class Node:
# constructor
def __init__(self):
self.children = [None] * 26
self.isEOW = False # True if is the end of the word
# trie class
class Trie:
# constructor
def __init__(self):
self.root = self.getNode()
# return a new trie node
def getNode(self):
return Node()
# convert character to index
def char_to_index(self, char):
# using lowercase 'a' to 'z'
return ord(char) - ord('a')
# insert a word into the trie
def insert(self, word):
current = self.root
for level in range(len(word)):
index = self.char_to_index(word[level])
# if current char not present
if not current.children[index]:
current.children[index] = self.getNode()
current = current.children[index]
# mark last node as leaf
current.isEOW = True
# search a given word
def search(self, word):
current = self.root
for level in range(len(word)):
index = self.char_to_index(word[level])
if not current.children[index]:
return False
current = current.children[index]
return current != None and current.isEOW
# ======================
# testing the Trie class
# ======================
words = ["the", "a", "there", "answer", "any", "by", "bye", "their"]
output = ["Not present in trie", "Present in tire"]
# Create a Trie object
t = Trie()
print("- Trie object created!")
print
# Construct trie
for word in words:
t.insert(word)
print("- Words inserted!")
print
# Search for different keys
print("- Search for different words")
print("{} ---- {}".format("the",output[t.search("the")]))
print("{} ---- {}".format("these",output[t.search("these")]))
print("{} ---- {}".format("their",output[t.search("their")]))
print("{} ---- {}".format("thaw",output[t.search("thaw")])) | true |
f5ac206bfef0b3238a91ed6f29ecce9a892d592e | Icode4passion/practicepythonprogams | /Zodiac.py | 565 | 4.3125 | 4 | print("Know your Zodiac Sign")
def Zodiac(month):
dic = {
'january':'Aquarius','february':'Pisces','march':'Aries','april':'Taurus','may':'Gemini','june':'Cancer','july':'Leo','august':'Virgo','september':'Libra','october':'Scorpio',
'november':'Sagittarius','december':'Capricorn'}
if mnt in dic:
print ("**{}** is your Zodiac Sign for {} month".format(dic[month],month))
else :
print ("Please Enter a valid month")
month = input("Please enter the Month of your Birth : \n")
mnt = str.lower(month)
Zodiac(mnt)
print ("Thanks for using our Zodic Table") | false |
e3fe9b78ab2b3ddc26d3a7d7e767fe46fb708bed | aboulmagdApp/pythoneExample | /pythonLevelOne/Strings.py | 840 | 4.53125 | 5 | #[start:stop;step]
mystring = "Hello world"
#if remove 0 from start the default will be 0
# print(mystring[0:7:2])
# print(mystring[:7:2])
print(mystring[::2])
#Revers string
print(mystring[::-1])
#concatenate strings
print(mystring+mystring)
print('hello ' + 'aboulmagd')
print(mystring.upper())
print(mystring.lower())
print(mystring.split())
# We can use a print statement to print a string.
print('Hello World 1')
print('Hello World 2')
print('Use \nto print a new line')
print('\n')
print('See what I mean?')
# We can also use a function called len() to check the length of a string!
print(len('Hello World'))
# Assign s as a string
s = 'Hello World'
#Check
s
# Print the object
print(s)
username = "aboulmagd"
color = 'blue'
print("the {} favorite is {}.".format(username,color))
print(f"the {username} choose {color}") | true |
d2836f58737a20b656be36a39bd4682b1bb32725 | KyraCrawford/GameDesign | /Tuples&Lists.py | 1,490 | 4.28125 | 4 | #KYRA CRAWFORD
from copy import deepcopy
#tuple (1)
numbers = (1, 2, 3)
print(numbers)
#tuple with mixed data types (2)
mixed_tuple = (9, "Hello", 36.8)
print(mixed_tuple)
#print on number in tuple (3)
print(numbers[2])
# unpacking tuple into variables (4)
x,y,z = mixed_tuple
print(x)
print(y)
print(z)
# add an item to a tuple (5)
mixed_tuple = mixed_tuple + (29,)
print(mixed_tuple)
#cahnge tuple to string (6)
morenumbers = (2,4,5,8,1,0,8,5,4,5,3,10,13)
str = str(morenumbers)
print(str)
# find 4th and 4th to last item in tuple (7)
random_tuple = ('y',6,89,11,5,'a','l',2,'b',34)
item1 = random_tuple[3]
item2 = random_tuple[-4]
print(item1)
print(item2)
#clone a tuple (8)
rantuple_clone = deepcopy(random_tuple)
print(rantuple_clone)
#find repeated numbers (9)
for x in morenumbers:
count = morenumbers.count(x)
if count > 1:
print(x, 'is repeated')
#check if element is in a tuple (10)
print(3 in mixed_tuple)
#convert list to tuple (11)
List = ['red','green','blue','orange']
print(List)
List = tuple(List)
print(List)
#remove item from tuple (convert to list, remove,convert back)(12)
random_tuple = list(random_tuple)
random_tuple.remove('b')
random_tuple = tuple(random_tuple)
print(random_tuple)
#slice a tuple (13)
slice = morenumbers[6:] #from 6 index to end of tuple
print(slice)
#find index of an item in tuple (14)
index = List.index('red')
print('The word "red" is located at:',index)
#find size or length of a tuple (15)
print(len(mixed_tuple))
| true |
7d94eeba1d88429bfebf6e7e93a7b8e10ed7ad6d | SeyhmusGuler/goat | /goat/placeholder.py | 817 | 4.5 | 4 | from typing import Union
def multiply_by_2(x: int) -> int:
"""
Multiplies the input integer x by 2.
Parameters
----------
x : int
The input integer
Returns
-------
int
The input times 2
Raises
------
TypeError
If the type of input isn't int.
"""
if type(x) == int:
return x * 2
raise TypeError("The type of the input wasn't int.")
def add_two(x: Union[int, float]) -> Union[int, float]:
"""
Adds 2 to the input and returns the result.
Args:
x (int, float): The input is number
Raises:
TypeError: If the input is not a number
Returns:
int, float: Input + 2
"""
if type(x) == int or type(x) == float:
return x + 2
raise TypeError("Input is not a number.")
| true |
7c0ffd54f85a3ef8a78a88c639d97b2afb9ed97e | cs-richardson/presidential-eligibility-4-4-5-thoang21 | /president-eligibility.py | 616 | 4.125 | 4 | """
Tung Hoang - 08/28/19
This program ask user for their status and determine
whether they are eligible for president
"""
# Constant variables
requiredAge = 35
requiredCitizen = "Yes"
requiredResidency = 14
# Ask user for their input
age = int(input("Age: "))
citizen = input("Born in the U.S.? (Yes/No): ")
residency = int(input("Years of residency: "))
# Determining whether they are eligible for president
if age >= requiredAge and citizen == requiredCitizen \
and residency >= requiredResidency:
print("You are eligible to run for president.")
else:
print("You are not eligible to run for president.")
| true |
d0ac7d7ac6d07c104b5a67717028fdd40876e39b | AhmedAliGhanem/PythonForNetowrk-Cisco | /9 Function 1 fun examples.py | 2,890 | 4.4375 | 4 | #Example 1
def main():
testfunc()
def testfunc():
pass
if __name__ == "__main__": main()
#Example 2
def main():
testfunc()
def testfunc():
print('This is a test function')
if __name__ == "__main__": main()
#Example 3 , to pass argument to our function
def main():
testfunc(42)
def testfunc(num):
print('This is a test function', num)
if __name__ == "__main__": main()
#Example 4
def main():
testfunc(42, 9)
def testfunc(num, num2):
print('This is a test function', num, num2)
if __name__ == "__main__": main()
#Example 5
def main():
testfunc(42)
def testfunc(num, num2 = 9):
print('This is a test function', num, num2)
if __name__ == "__main__": main()
#Example 6
def main():
testfunc(42, 10)
def testfunc(num, num2 = 9):
print('This is a test function', num, num2)
if __name__ == "__main__": main()
#Example 7
def main():
testfunc(42)
def testfunc(num, num2 = None):
if num2 is None:
num2 = 10
print('This is a test function', num, num2)
if __name__ == "__main__": main()
#Example 8
#The asterisk is special in this place as it means that this is just a list of optional arguments
def main():
testfunc(1, 2, 3, 4, 5, 6, 7)
def testfunc(n1, n2, n3, *args):
print(n1, n2 ,n3)
if __name__ == "__main__": main()
#Example 9
#args will be tuple
def main():
testfunc(1, 2, 3, 4, 5, 6, 7)
def testfunc(n1, n2, n3, *args):
print(n1, n2 ,n3, args)
if __name__ == "__main__": main()
#*args and **kwargs are mostly used in function definitions.
#*args and **kwargs allow you to pass a variable number of arguments to a function.
#What variable means here is that you do not know beforehand how many arguments can
#be passed to your function by the user so in this case you use these two keywords.
#Example 10
def main():
testfunc(n1 = 1, n2 =2)
def testfunc(**kwargs):
print('This is a test function', kwargs['n1'], kwargs['n2'])
if __name__ == "__main__": main()
#arguments are not named on the receiving end,So these are specified
#with the two asterisks and very commonly called kwargs
##kwargs is actually a dictionary and so I can say kwargs sub 'n1', like
#that, and kwargs sub 'n2' then I save these and run it,
#Example 11
def main():
print(testfunc())
def testfunc():
return 'This is a test function'
if __name__ == "__main__": main()
#Example 12
def main():
print(testfunc())
def testfunc():
return 42
if __name__ == "__main__": main()
#Example 13
def main():
print(testfunc())
def testfunc():
return range(25)
if __name__ == "__main__": main()
#Example 124
def main():
for n in testfunc(): print(n, end= ' ')
def testfunc():
return range(25)
if __name__ == "__main__": main()
| false |
b81802e8ee625d2bc1299beae3af26da82f45a75 | AhmedAliGhanem/PythonForNetowrk-Cisco | /8 Loops dic2.py | 882 | 4.125 | 4 | #CCIE/CCSI:Yasser Ramzy Auda
#https://www.facebook.com/yasser.auda
#https://www.linkedin.com/in/yasserauda/
#https://github.com/YasserAuda/PythonForNetowrk-Cisco
# Python Program to Map Two Lists into a Dictionary
keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
#Enter number of elements for dictionary:4
#For keys:
#Enter element1:1
#Enter element2:2
#Enter element3:3
#Enter element4:4
#For values:
#Enter element1:5
#Enter element2:6
#Enter element3:7
#Enter element4:8
#The dictionary is:
#{1: 5, 2: 6, 3: 7, 4: 8}
| true |
89fd51a5d97d2561d1bf3f4333e0d3cac9b8b34f | jrbourbeau/dask-ctl | /dask_ctl/utils.py | 1,147 | 4.1875 | 4 | def format_table(rows, headers=None):
"""Formats list of lists into a table.
If headers is not provided the first row will be used as headers.
Examples
--------
>>> print(format_table([["foo", "bar"], ["fizz", "buzz"]], headers=["hello", "world"]))
HELLO WORLD
foo bar
fizz buzz
"""
if headers is None:
headers = rows.pop(0)
if len(set([len(row) for row in rows] + [len(headers)])) != 1:
raise ValueError("Headers and each row must be lists of equal length")
col_widths = [
max([len(str(row[i])) for row in rows] + [len(str(headers[i]))])
for i in range(len(headers))
]
try:
rows.insert(0, [h.upper() for h in headers])
except AttributeError:
raise ValueError("Headers must be strings")
def justify(value, length):
if isinstance(value, int) or isinstance(value, float):
return str(value).rjust(length)
return str(value).ljust(length)
return "\n".join(
[
" ".join([justify(row[i], col_widths[i]) for i in range(len(row))])
for row in rows
]
)
| true |
6ca17989c123eade73608969550e01ac0c25420e | siddhant1623/spoonerisms | /spoon.py | 2,509 | 4.125 | 4 | # Explores all non-trivial n-char substitution spoonerisms up to n=3
""" A trivial spoonerism is one where applying the spooning operation returns the
original words
"""
from hyphen import Hyphenator
from hyphen.dictools import *
h = Hyphenator()
data = open("/home/human/data/10000_most_common_thresh5.txt","r")
output = open("all_spoons.txt", "w")
all_words = set([word.split()[0] for word in data])
def one_one(word, neighbor):
word_spooned = neighbor[0] + word[1:]
neighbor_spooned = word[0] + neighbor[1:]
return word_spooned,neighbor_spooned
def two_two(word, neighbor):
word_spooned = neighbor[0:2] + word[2:]
neighbor_spooned = word[0:2] + neighbor[2:]
return word_spooned,neighbor_spooned
def three_three(word, neighbor):
word_spooned = neighbor[0:3] + word[3:]
neighbor_spooned = word[0:3] + neighbor[3:]
return word_spooned,neighbor_spooned
for word in sorted(all_words):
for neighbor in sorted(all_words):
if neighbor[0].lower() == word[0].lower():
continue #check for trivial spoonerism
funcs = [one_one]
for fun in funcs:
if len(word) < 3 or len(neighbor) < 3:
continue
p = fun(word,neighbor)
word_spooned = p[0]
neighbor_spooned = p[1]
if word_spooned == neighbor or word_spooned.lower() == neighbor.lower():
continue
if word_spooned == neighbor + 's' or neighbor == word_spooned +'s':
continue
if word_spooned == word or word_spooned.lower() == word.lower():
continue
if neighbor_spooned == neighbor or neighbor_spooned.lower() == neighbor.lower():
continue
if word_spooned in all_words and neighbor_spooned in all_words:
output.write( word + " " + neighbor + " => " + word_spooned + " " + neighbor_spooned + " " + str(fun).split()[1]+ " " + " \n")
print("success!")
"""
#this was bad and hard
word_syll = h.syllables(unicode(word,"utf-8"))
neighbor_syll = h.syllables(unicode(neighbor,"utf-8"))
if len(word_syll) < 2:
break
if len(neighbor_syll) < 2:
continue #can't make syllabic substitution
word_spooned = neighbor_syll[0] + ''.join(word_syll[1:])
neighbor_spooned = word_syll[0] + ''.join(neighbor_syll[1:])
if word_spooned == neighbor or word_spooned.lower() == neighbor.lower():
continue
if word_spooned == word or word_spooned.lower() == word.lower():
continue
if neighbor_spooned == neighbor or neighbor_spooned.lower() == neighbor.lower():
continue
"""
| true |
484abe382ab923beeba9e9e9e89ab97da532d6e6 | hxdxhe/Python | /代码/进阶/3-3、如何进行反向迭代以及如何实现反向迭代.py | 699 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/1/20 15:30
# @Author : Aiopr
# @Email : 5860034@qq.com
# @File : 3-3、如何进行反向迭代以及如何实现反向迭代
from decimal import Decimal
class FloatRange:
def __init__(self,a,b,step):
self.a = Decimal(str(a))
self.b = Decimal(str(b))
self.step = Decimal(str(step))
def __iter__(self):
t = self.a
while t <= self.b:
yield float(t)
t += self.step
def __reversed__(self):
t = self.b
while t >= self.a:
yield float(t)
t -= self.step
fr = FloatRange(2.0,3.0,0.2)
for x in fr:
print(x)
print('-'*20)
for x in reversed(fr):
print(x)
| false |
0b617bc5b47f44d8e7b3064eb95197706aaaf27d | akriticg/ASCII_art | /circle.py | 607 | 4.25 | 4 | #Version 1
#September 26, 2018
#Input from the user 'radius' defines the radius of the circle
#Diameter of a circle is twice the radius
#Going from top to bottom, and drawing chords of a circle at a perpendicular distance from the center
import sys
import math
def main():
radius = int(sys.argv[1])
dia = 2 * radius
SPACE = ' '
CIRCLE = 'o'
for k in range(-radius, radius, 1):
chord_length = 2 * round(math.sqrt(math.fabs(radius*radius - k*k)))
spaces = round((dia-chord_length) / 2)
print(SPACE*spaces + CIRCLE*chord_length + SPACE*spaces)
main()
| true |
33d991d4cbd439403cea539386239607d1d17154 | Boogie3D/GameJamCiv | /init.py | 1,699 | 4.1875 | 4 | 'Functions for initializing game'
from random import seed, randint
from itertools import combinations
def init_resources():
'''
Initializes the statistics for a country, such as population, food,
and industry
'''
seed()
resources = {
'population': randint(30, 60),
'food': 60,
'industry': 0
}
return resources
def init_relationships():
'''
Initalizes the country relationships from a range of 25 to 75.
Relationship ranges:
0-40: Enemy
41-60: Neutral
61-100: Ally
'''
seed()
relationships = {}
# Computer relationships
for comb in combinations('ABCD', 2):
relationships[''.join(comb)] = randint(25, 75)
# Player-Computer relationships
while True:
cheese_count = 0
for letter in 'ABCD':
relationships[letter + 'P'] = randint(25, 75)
# Count the number of initial allies
# Retry initialization if the game is too easy
cheese_count += (relationships[letter + 'P'] > 55)
if cheese_count < 3:
break
return relationships
def init_names():
'Asks the player to enter names for the other countries'
names = []
numeral = ['first', 'second', 'third', 'fourth']
for index in range(4):
while True:
names.append(input("Enter the {0} country's name: ".format(numeral[index])))
# Try again if invalid string
if (names[index] != ''
and names[index] not in names[0:index]
and names[index] != 'you'):
break
del names[index]
print('Please try again.')
return names
| true |
9bb47e1a566cbd2d57486d7b71a34006cc797210 | pratish-gupta/python-prog | /Calculator.py | 504 | 4.1875 | 4 | while True:
print("-----------------------")
print("Calculator Options")
print("-----------------------")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Quit")
user_input =input("Enter the Option :")
if user_input == 5:
break
if user_input == 1:
num1=float(input("Enter the First Number :"))
num2=float(input("Enter the Second Number :"))
result=str(num1+num2)
print("The answer is :"+result)
print(" ")
| true |
69eefb5344e66376343af3bcfa63761de6a24845 | teempe/turtle-crossing-game | /utils.py | 1,794 | 4.21875 | 4 | """Utility functions to create nice looking game board. """
from turtle import Turtle
line = Turtle()
line.hideturtle()
line.speed("fastest")
line.pensize(2)
def draw_dashed_line(start_pos, end_pos):
"""
Draws white dashed line between given points.
Arguments
---------
start_pos : pair of numbers
coordinates of starting point.
end_pos : pair of numbers
coordinates of end point
"""
line.color("white")
xs, ys = start_pos
xe, ye = end_pos
line.penup()
line.goto(xs, ys)
line.pendown()
cur_x = xs
while cur_x <= xe:
cur_x += 40
line.goto(cur_x, ys)
line.penup()
cur_x += 20
line.goto(cur_x, ys)
line.pendown()
def draw_lanes():
"""Draws paving, verges and median strip."""
# Draw road verges
line.color("white", "green")
# Bottom verge
points = ((300, -220), (-300, -220), (-300, -300), (300, -300), (300, -220))
line.begin_fill()
line.penup()
for point in points:
line.goto(point)
line.pendown()
line.end_fill()
# Median strip
points = ((300, -20), (-300, -20), (-300, 20), (300, 20), (300, -20))
line.begin_fill()
line.penup()
for point in points:
line.goto(point)
line.pendown()
line.end_fill()
# Top verge
points = ((300, 220), (-300, 220), (-300, 300), (300, 300), (300, 220))
line.begin_fill()
line.penup()
for point in points:
line.goto(point)
line.pendown()
line.end_fill()
# Draw top lanes
for start_y in range(20, 220, 40):
draw_dashed_line((-300, start_y), (300, start_y))
# Draw bottom lanes
for start_y in range(-20, -220, -40):
draw_dashed_line((-300, start_y), (300, start_y))
| true |
0c41c8063088d3bd833b3dfe39c1d456a894379c | Grosswood/Python | /GuessPython.py | 1,459 | 4.34375 | 4 | #Computer is guessing
def comStep(minVal, maxVal):
averageVal = (minVal + maxVal) // 2
print ('Your number is', averageVal,'?')
answer = input ()
if answer == "+":
comStep((averageVal + 1), maxVal)
elif answer == "-":
comStep(minVal, (averageVal - 1))
else:
print ('Haha! I knew it!')
#User is guessing
def humStep (randomNumber):
playerGuess = int(input ("Please, enter your guess "))
while playerGuess != randomNumber:
if playerGuess > randomNumber:
print ("Your guess is greater")
playerGuess = int(input ())
else:
print ("Your guess is less")
playerGuess = int(input ())
print ("Your guess is correct!")
def main():
gameType = input ("Print '0' if you want Computer to Guess Number in your mind or '1' if you want Computer to come up with random number and guess it yourself ")
if ((gameType != "0") and (gameType != "1")):
print ('I believe that mean you want to exit. Farewell though, hope to see you soon again!')
elif (gameType == "0"):
maxVal = int(input ("Please, input the desired range "))
print ('Come up with any number from desired range, type "-" if your number is less, "+" if greater, other inputs will be considered as computer being correct')
comStep (0, maxVal)
main ()
else:
maxVal = int(input ("Please, input the desired range "))
maxVal = randint (1, maxVal)
humStep (maxVal)
main ()
from random import randint
print ("Welcome to Guess Number Program!")
main () | true |
a348128c43c9b6cb38d76fade0f937fda0849fe8 | NickJJFisher/DigitalSolutions2020 | /Chapter3/3.py | 688 | 4.21875 | 4 | month = int(input("Enter a month's numeric counterpart: "))
if month < 3:
print("The month is in the first quarter")
if month == 4:
print("The month is in the second quarter")
if month == 5:
print("The month is in the second quarter")
if month == 6:
print("The month is in the second quarter")
if month == 7:
print("The month is in the third quarter")
if month == 8:
print("The month is in the third quarter")
if month == 9:
print("The month is in the third quarter")
if month == 10:
print("The month is in the fourth quarter")
if month == 11:
print("The month is in the fourth quarter")
if month == 12:
print("The month is in the fourth quarter")
| true |
c71a334c5f1d5ad2265f167226ea87c83336b7dd | Slytherin1112/Rutgers_Lib_Workshops | /Workshop 2 Exercise.py | 1,606 | 4.15625 | 4 | #Exercise 1
#Print out "b is larger than a.
# b-a=x" or "a and b are equal.
# a = b = x".
# x shows the result of "b-a" or the value of "a" and "b".
a = 450
b = 76
c = 23
if a > b:
print ("a is larger than B.", "a-b=", a-b)
elif a == b:
print("a and b are equal.", "a = b =", a)
else:
print("a is smaller than b")
#Exercise 2
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if
#a = input("Enter:")
#print(type(a))
num = int(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
#Exercise 4: Make a small program that helps you make decisions.
#Program that tells you how much money you're making or losing in stock market
Balance = float(input("Your account balance:")) #original balance in your bank account
Bal_week1 = [float(input("Day1:")), float(input("Day2:")),float(input("Day3:")),float(input("Day4:")),float(input("Day5:"))]
My_portfolio = []
for i in Bal_week1:
if i < Balance:
My_portfolio.append(int(i-Balance))
elif i > Balance:
My_portfolio.append(int(i - Balance))
else:
My_portfolio.append('-')
print(My_portfolio)
#Determine how many students fail/passed an exam
grades=[70, 86, 40, 94, 100, 83, 60, 42, 70, 98, 30, 55]
passed=0
failed=0
for i in grades:
if i>=55:
passed += 1
else:
failed += 1
print("There are ",passed,"students who passed the test")
print("There are ",failed,"students who failed the test")
| true |
c9c1b0cdebb6abc05fa791f6b9db008c866097a0 | filipgraniczny/basic-recursive-functions-python | /palindrome.py | 202 | 4.21875 | 4 | # This is a basic implementation of the recursive palindrome method in Python3
def palindrome(a):
if len(a) < 2:
return True
return (a[0] == a[len(a)-1]) and palindrome(a[1:len(a)-2])
| true |
d3ba4e3ec5cb2eff48508f7e0d672e99e67216ca | abiryusuf/Fluent_Python | /Chapter_6_Dictionary/looping.py | 1,431 | 4.125 | 4 | languages = {
'abir': "python",
"mim": 'java',
'sarah': 'c',
'yusuf': 'ruby',
'phil': 'c++'
}
for name, language in languages.items():
print("{}'s favorite language is {}".format(name.title(), language.title()))
x = languages['abir'].title()
print(x)
friends = ['phil', 'sarah']
for name in languages.keys():
print(name)
if name in friends:
print(" Hi " + name.title() + ", I see your favorite language is " + languages[name].title())
# sorted
for name in sorted(languages.keys()):
print(name.title() + ", thank for taking the poll")
# values
for language in sorted(languages.values()):
print(language.title())
for name, language in sorted(languages.items()):
print("{}'s likes {}".format(name.title(), language.title()))
for language in set(languages.values()):
print(language)
# try it yourself
rivers = {
'bangladesh': 'karnafuly',
'new york': "hudson",
'canada': 'abc'
}
for name, river in rivers.items():
print("The {} runs through {}.".format(name.title(), river.title()))
for name in rivers.keys():
print("Country: " + name.title())
for value in rivers.values():
print(value.title())
peoples = ['abir', 'mim', 'mukter', 'arafat']
for people in peoples:
if people in languages.keys():
print('Thank you for taking the poll, ' + people.title())
else:
print(people.title() + ' whats your favorite langiages') | false |
72e12f43386212a15b3107383700b352e9665faf | AlbanianSilka/TestTasks | /Task1.py | 2,364 | 4.125 | 4 | #В задании дана цель создать простой шифр Цезаря, а также второй функцией дешифратор к нему
#Дешифратор работает только на латиницу, для кириллицы нужна функция, в которой будет прописан кириллический алфавит
def caesar_cipher():
entered_text = str(input("Введите текст для шифровки: "))
if not entered_text:
return
try:
key_cipher = int(input("Количество элементов для шифрования: "))
except ValueError:
return entered_text
if key_cipher <= 0:
return entered_text
ciphered_text = ""
for ch in entered_text:
if ch.isalpha():
alph_stay = ord(ch) + key_cipher
if alph_stay > ord('z'):
alph_stay -= 26
final_letter = chr(alph_stay)
ciphered_text += final_letter
print("Ваш зашифрованный текст: ", ciphered_text)
return ciphered_text
ciphered_text = caesar_cipher()
# Функция дешифровки будет отличаться, потому что в прошлой отсутсвовала возможность отбросить символы, которые были
# за буквой "a"
def caesar_decipher():
decipher_text = ciphered_text
if not decipher_text:
return
try:
key_decipher = int(input("Количество элементов для дешифрования: "))
except ValueError:
return decipher_text
if key_decipher <= 0:
return decipher_text
eng_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
shifted_alphabet = eng_alphabet[26 - key_decipher:] + eng_alphabet[0:(26 - key_decipher)]
cipher_text = ""
for i in range(len(decipher_text)):
char = decipher_text[i]
idx = eng_alphabet.find(char.upper())
if idx == -1:
cipher_text = cipher_text + char
elif char.islower():
cipher_text = cipher_text + shifted_alphabet[idx].lower()
else:
cipher_text = cipher_text + shifted_alphabet[idx]
print("Дешифровка вашего текста: ", cipher_text)
return cipher_text
caesar_decipher()
| false |
a79c04e8305c5f32dfd9ca2c0bde7e06e3f3af3b | Hellrungj/CSC-226-Software-Design-and-Implementation | /Other Python Code/turtle.interactive(Example_By-Jan,Mario).py | 2,980 | 4.34375 | 4 | ######################################################################
# Author: Dr. Jan Pearce
# username: pearcej
#
# Purpose: demonstration of event-driven programming using the turtle library
######################################################################
# Acknowledgements:
# Mario Nakazawa added the quit_box to close more cleanly
######################################################################
import time
import turtle
import random
turtle.colormode(255)
wn = turtle.Screen() # Get a reference to the window
#wn.exitonclick() # wait for a user click on the canvas
# Create turtle for header
header = turtle.Turtle()
header.penup()
header.setpos(-10,150)
header.write("Click one of the big choices",move=False,align='center',font=("Arial",30,("bold","normal")))
header.hideturtle()
# Create turtle for choice of 1
one = turtle.Turtle()
one.color("purple")
one.shapesize(3)
one.penup()
one.setpos(-100,20)
one.shape("circle")
# Create turtle for choice of 2
two = turtle.Turtle()
two.color("#0000FF")
two.shapesize(3)
two.penup()
two.setpos(100,20)
two.shape("circle")
two.stamp()
two.color("#000099")
two.setpos(110,25)
two.stamp()
# use a "quitter" turtle to draw some text to stop the loop.
quit_box = turtle.Turtle()
quit_box.penup()
quit_box.hideturtle()
quit_box.setpos(-60,-200)
quit_box.write("Click to stop ->",move=False,align='center',font=("Courier New",15,("bold","normal")))
quit_box.showturtle()
quit_box.setpos(60,-190)
quit_box.shapesize(1,1,15)
quit_box.shape("square")
quit_box.color("#AFA4AF")
# Create turtle for text
text = turtle.Turtle()
text.penup()
text.setpos(0,-150)
text.hideturtle()
def handler_one(x, y):
'''called when circle one is clicked'''
wn.title("1 clicked")
text.clear()
text.write("1 clicked",move=False,align='center',font=("Arial",30,("bold","normal")))
# add more code here for when the user clicks 1
def handler_two(x, y):
'''called when circle two is clicked'''
wn.title("2 clicked")
text.clear()
text.write("2 clicked",move=False,align='center',font=("Arial",30,("bold","normal")))
# add more code here for when the user clicks 2
def display_nim(numb):
'''called to display numb many circles of random colors'''
turtle.colormode(255)
position=-150
for i in range(numb):
num = turtle.Turtle()
num.shape("circle")
num.color(random.randrange(256),random.randrange(256),random.randrange(256))
num.penup()
num.setposition(position+20*i, 130)
num.stamp()
def quit_nim(x,y):
'''called in order to return the true value'''
quit_box.hideturtle()
text.clear()
text.write("Quitting",move=False,align='center',font=("Arial",30,("bold","normal")))
wn.onkey(quit_nim,"q")
wn.listen()
#main loop
while quit_box.isvisible():
numb=15 # we will allow the user to enter this.
quit_box.onclick(quit_nim)
one.onclick(handler_one)
two.onclick(handler_two)
display_nim(numb)
wn.bye()
| true |
75c5f1682a126cdb8495a805872a6c6d9439f263 | HazelIP/Programming-21 | /week5/Lab 5.4 dict.py | 635 | 4.375 | 4 | # This program stores a student name and a list of her course and gradse in a dict
# then print out her data (number of course could change)
# Author: Ka Ling IP
student = { #create a dict that store student info
"name": "Mary",
"module": [{ #number of course could change, create a list to store
"course": "Programming", #create a nested dict to store each courses and grades
"grade": "45"},
{
"course": "History",
"grade": "99"}
]
}
print ("Student: ", student["name"])
for module in student["module"]:# do not understand
print ("\t{}:\t{}".format(module["course"],module["grade"])) | true |
3ffbf8eec334c7c2139ba14766db8ffb1226665a | HazelIP/Programming-21 | /week3/lab 3.2.3floor.py | 253 | 4.21875 | 4 | # This program takes in a float and returns an int rounded down
# Author: Ka Ling Ip
import math
numberToFloor = float(input("Enter a float number:"))
flooredNumber = math.floor(numberToFloor)
print("{} floored is {}.".format(numberToFloor,flooredNumber))
| true |
0ac0ab76573276bf1f65dcba1476dfe1f548c1e0 | HazelIP/Programming-21 | /week2/nameAndAge.py | 470 | 4.1875 | 4 | # This program contains the extra question of week 2
# Author: Ka Ling Ip
#Q.17 This program reads in name and age and output a message
name = input ("Enter your name:")
age = input ("Enter your age:")
print ("Hello {}, your age is {}.". format(name,age))
#Q.18 This modified program has a tab at the end of the name
print("Hello {}, \tyour age is {}.". format(name,age))
#Q.19 This program outputs 21-4
print(21-4)
#Q.20 This program outputs if 2 equals 3
print(2 == 3) | true |
6ddd5ec774210c98d106d2902fe3cabd67310f85 | maria-fernanda-tibanta/ert | /hnnj/busqueda.py | 1,545 | 4.25 | 4 | ## EPN-ESFOT-ASI Algoritmos Fundamentales 2016-B
## busca_en_lista.py
## Versión: 1.0
## Búsqueda de un elemento en una lista
## Autor: María Fernanda Tibanta
## Fecha: 04-Nov-2016
## Creación de lista
lista = []
elemento = input("ingrese un nuevo elemento de la lista: ")
while elemento != "":
lista.append(elemento)
elemento = input("ingrese un nuevo elemento de la lista: ")
print("La lista generada es: ", lista)
## Pide la palabra a buscar
palabra = input("Ingrese la palabra que desea buscar: ")
## BUSCA LA PALABRA
##Método 1: Usa funciones incorporadas en Python
print("\n## Método 1: Usa funciones incorporadas en Python")
print (palabra in lista) # función booleana
if palabra in lista:
print ("la palabra", palabra, "fue encontrada en la lista", lista)
else:
print ("la palabra", palabra, "NO fue encontrada en la lista", lista)
## Método 2: Recorre la lista al estilo Python
print("\n## Método 2: Recorre la lista al estilo Python")
for elemento in lista:
if elemento == palabra:
print ("la palabra", palabra, "corresponde al elemento", elemento)
else:
print ("la palabra", palabra, "NO corresponde al elemento", elemento)
## Método 3: Recorre la lista al estilo Java o C++
print("\n## Método 3: Recorre la lista al estilo Java o C++")
n = len(lista)
for i in range(n):
if lista[i] == palabra:
print ("la palabra", palabra, "corresponde al elemento", i, "que es", lista[i])
else:
print ("la palabra", palabra, "NO corresponde al elemento", i, "que es", lista[i])
| false |
4025ede64ffffb47e41bc5fc78ff9f876b285b0e | 7zmau/my-python-collection | /guessTheNumber.py | 534 | 4.125 | 4 | import random
secretNumber=random.randint(1,20)
print("I'm choosing a number between 1 and 20")
for guessesTaken in range(1,7):
guess=int(input("Take a guess \n"))
if guess < secretNumber:
print("Your guess is too low")
elif guess > secretNumber:
print("Your guess is too high")
else:
break
if guess == secretNumber:
print("Good Job! You guessed my number in " + str(guessesTaken) + " guesses!")
else:
print("The number I was thinking of was " + str(secretNumber))
| true |
2c06bc04c4de710b3617ab264beb1ac750ef3da7 | 7zmau/my-python-collection | /Temp.py | 395 | 4.125 | 4 | ch=int(input("Enter '1' to convert from Fahrenheit to Celcius or '2' to convert from Celcius to Fahrenheit \n"))
temp=float(input("Enter temperature: "))
if ch==1:
a=(temp-32)*5/9
print("The value in celcius is ",a)
elif ch==2:
b=(temp*9/5)+32
print("The value in Fahrenheit is ",b)
else:
print("Invalid choice")
| true |
f786b86ea2e1fd6691af8b44a7f2cc0e43f71e28 | AlexAlonso50/PythonWorkspace | /logicalOperators/logicalOutline.py | 955 | 4.46875 | 4 | '''
This outline will help solidify concepts from the Logical Operators lesson.
Fill in this outline as the instructor goes through the lesson.
'''
#EX) Make two boolean variables. Put them on either side of the and operator.
#Store this expression in a variable named a. Print the variable.
one = True
two = False
a = one and two
print(a)
#1) Make two boolean variables. Put them on either side of the and operator.
#Store this expression in a variable named a. Print the variable.
a = 2 == 4 and 5 == 5
print(a)
#2) Make two boolean variables. Put them on either side of the or operator.
#Store this expression in a variable named b. Print the variable.
b = 2 < 3 or 5 < 10
print(b)
#3) Make one boolean variable. Put the variable after the not. Store this
#expression in a variable named c. Print the variable.
c = not 4 == 5
print(c)
#4) Make a logical expression with one of the common SYNTAX errors.
p = 55 == 55 100 == 100 not
print(p)
| true |
3f9ec84eb8358f1617cb0577455b489c52cd94aa | Awn-Duqoum/WIEPythonTutorials | /Beginner/Tutorial_2_Rev-1.py | 1,499 | 4.4375 | 4 | # WIE Python Beginners Tutorial, Introduction to if statements
# Awn Duqoum - Jan 11 2017
# When coding there comes a time when the code needs to make a decision based on
# the value of a variable. To do this we need if statements
pieIsGood = True
if(pieIsGood == True):
print "Pie is always good"
# There are two important things to note about the if statement above, the first is
# the == sign. When equating two things we used the single = symbol but when we want
# compare the value of two things we use ==
# For example
A = 5
# Sets the variable A to 5 while
print A == 5
# Returns true
# The second thing that is important to note is the fact that the second line
# is indented. Unlike other languages, spaces in python matter ... a lot.
# the if statement ends when the indentation ends
if(pieIsGood == False):
print "This will not print"
#if(pieIsGood == False):
#print "This will throw an error"
# In addition to the if statement there is an else if. Which checks the first statement
# and if it's false moves on to the else
if(pieIsGood == 90):
print "This will not print"
elif(pieIsGood == True):
print "This will print"
# And an else statment, which will also excute if all that is above it is false
if(A == 4):
print "This will not print"
else:
print "Much print"
# You can use else and else if together and are not limited to the number of
# checks you have. The only rule is you need to start with an if and if you have
# and else it must be the last check | true |
b4368ff2e16af753463a452ebbb736546db5fa65 | Awn-Duqoum/WIEPythonTutorials | /Beginner/Tutorial_1_Rev-1.py | 1,731 | 4.15625 | 4 | # WIE Python Beginners Tutorial, Introduction to variables
# Awn Duqoum - Jan 11 2017
# In python there are 5 types of variables and or ways of defining data and the
# operations that can be performed on the data
# Numbers
a = 10; # Integers
b = 10.0; # Floating Point
c = 3.14j # Complex Numbers
# Strings
# Note that d is equal to e
d = 'Hello World !'
e = "Hello World !"
# Lists (One of the greatest things about python)
# List entries could all be the same type
sameTypeList = [1,2,3,4]
sameTypeList2 = ['one',"two",'three',"four"]
# List entries could also be anything
whyPythonIsSometimesBetterThenC = [1,"alpha",3.2j,"Pie","MOARPIE"]
# A specail Read-only type of lists are called Tuples
# A list is dynamic, it's size and content can change at any time
shortList = [1]
shortList[0] = 5
#The same cannot be dont with tuples
shortTuple = (1)
# The line below is invaild
# shortTuple[0] = 5
# The last type is a Dictionary, which is nothing more than a list whose index
# could be anything
exampleDictionary = {}
exampleDictionary['Pie'] = 'MorePie'
exampleDictionary[1] = 'LessPie'
exampleDictionary[10] = 'PiePiePie'
# In order to only have one print statement we need to wrap our none string
# variables # in str() which converts the variable into a string. Note we could've
# and maybe # should've had 2 print statements and no str()
print 'a = ' + str(a)
print 'b = ' + str(b)
print 'c = ' + str(c)
print 'd = ' + d
print 'e = ' + e
print 'shortTuple = ' + str(shortTuple)
print 'sameTypeList = '+ str(sameTypeList)
print 'sameTypeList2 = ' + str(sameTypeList2)
print 'exampleDictionary = ' + str(exampleDictionary)
print 'whyPythonIsSometimesBetterThenC = ' + str(whyPythonIsSometimesBetterThenC) | true |
9562265fd7ac7b8fdefd799dd4447067f9451395 | subash2617/Task-6 | /Task 6.py | 249 | 4.15625 | 4 | # program to loop through a list of numbers and add +2 to every value to elements in list #
List= [1,2,3,4,5]
for x in List:
print(x+2)
# 2
x = 5
for i in range(0,x+1):
print()
for j in range(x-i,0,-1):
print(j,end='') | true |
c8e0e0b9eb7f7f024271ab1f9f005081646009b4 | knitinjaideep/Python | /RotatedSearch.py | 1,590 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 30 18:39:10 2019
@author: nitinkotcherlakota
"""
def binary_search_func(arr, start_index, end_index, target):
if start_index > end_index:
return -1
mid_index = (start_index + end_index)//2
if arr[mid_index] == target:
return mid_index
index_right_side = binary_search_func(arr, start_index, mid_index - 1, target)
index_left_side = binary_search_func(arr, mid_index + 1, end_index, target)
return max(index_left_side, index_right_side)
def rotated_array_search(input_list: list, number: int) -> int:
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array): Input array to search
number (int): target to search
Returns:
int: Index or -1
"""
if len(input_list) == 0:
return -1
return binary_search_func(input_list, 0, len(input_list) - 1, number)
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
#edge cases
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
test_function([[], 1])
test_function([[1, 2, 3, 4, 5, 6], 4]) | true |
31172a8104aabbe74825466c790d6c343074bfcb | knitinjaideep/Python | /FindFiles.py | 1,365 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 08:29:29 2019
@author: nitinkotcherlakota
"""
import os
def find_files(suffix, path=[]):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
if suffix == '':
return []
if len(os.listdir(path)) == 0:
return []
paths = os.listdir(path)
files = [file for file in paths if '.' + suffix in file]
folders = [file for file in paths if '.' not in file]
for folder in folders:
files.extend(find_files(suffix=suffix, path=path + '/' + folder))
return files
path1 = os.getcwd() + '/testdir/subdir1'
path2 = os.getcwd() + '/testdir/subdir3'
path3 = os.getcwd() + '/testdir'
path4 = os.getcwd() + '/testdir/subdir3/subsubdir1'
print(find_files(suffix='c', path=path1))
print(find_files(suffix='h', path=path2))
print(find_files(suffix='c', path=path3))
print(find_files(suffix='c', path=path4))
# Edge Case
print(find_files(suffix='z', path=path1))
print(find_files(suffix='', path=path2)) | true |
58a9f3540a9825bc10adf1051d54483cee4fcc3f | knitinjaideep/Python | /New Process Problems/ReverseWordsInString.py | 1,303 | 4.375 | 4 | #ReverseWordsInString.py
# Given an input string s, reverse the order of the words.
# A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
# Return a string of the words in reverse order concatenated by a single space.
# Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
# Example 1:
# Input: s = "the sky is blue"
# Output: "blue is sky the"
# Example 2:
# Input: s = " hello world "
# Output: "world hello"
# Explanation: Your reversed string should not contain leading or trailing spaces.
# Example 3:
# Input: s = "a good example"
# Output: "example good a"
# Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
# Example 4:
# Input: s = " Bob Loves Alice "
# Output: "Alice Loves Bob"
# Example 5:
# Input: s = "Alice does not even like bob"
# Output: "bob like even not does Alice"
# Time: O(n) | Space: O(n)
def reverseWords(s):
"""
:type s: str
:rtype: str
"""
l = []
for i in s.split():
l.append(i.strip())
return ' '.join(l[::-1])
print(reverseWords(" Bob Loves Alice ")) | true |
bceefc17bb45e97ecbc0f0f2b22ccf6a1fd5770e | Blazingcoder21/coding-time | /Second_Keyboard_Program.py | 520 | 4.21875 | 4 | print ("This is a program to accept Name, Age and Address and display it on the screen")
myName = input ("Please Enter your Name: ")
myAge = input ("Please Enter your Age: ")
myAddress_houseNo = input ("Please Enter your House Number: ")
myAddress_Street = input ("Please Enter your street Name: ")
myAddress_postcode = input ("Please Enter your Post Code: ")
print ('Hello, my name is', myName,' ,I am', myAge,' years old, and I live at', myAddress_houseNo,', ',myAddress_Street,', ',myAddress_postcode)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.