blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
277c64a0ff66a46fe9a7376e5b3b82ef4fa53281 | tinashechihoro/python-testing | /folder_file/folder_file_recurser.py | 962 | 4.21875 | 4 | """
I have a folder and inside it I can put files and other sub folders containing files and so on so I can have recursive folders with files inside them
I want a way to pass the parent outermost folder name to a program and this program will recursively read out for me all the file names including those in nested folders and print them out
Could you think of a solution for that and implement a python program to do that in the most convenient way keeping in mind best practices
"""
import os
"""
Its assumed that the python script is running in the current folder
Get user parent folder name
get_parent_folder_name():
folder_directory = os.path
assert
"""
def get_parent_folder(folder_name=''):
parent_folder = os.getcwd()
files_list = os.listdir(parent_folder)
for file in files_list:
print(file)
with open('deck.py','r') as f:
contents = f.readlines()
print(contents)
f.close()
| true |
87dcecbbb85e5fc3706f70930ac5113879529188 | Andreo1111/pythonbook | /exercise7.3.py | 862 | 4.375 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
Exercise 7.3 Write a program that asks the user for ten numbers, and then prints the
largest, the smallest, and how many are dividable by 3. Use the algorithm described earlier
in this chapter.
'''
try:
amax = 1
bmin = 1
cdiv = 0
count = 1
while count <= 3:
number = int(input("Please input number :"))
count +=1
if amax <= number:
amax = number
if (number %3) == 0:
print('Divided on 3')
print("Max",amax)
continue
if bmin >=number:
bmin = number
if (number %3) == 0:
print('Divided on 3')
print("Min",bmin)
continue
except ValueError:
print("Error! Please input number!!!")
| true |
fd2485bd5acd046fe27f446eea8a0984a0246da3 | Nep-DC-Exercises/day-5 | /hotel_management.py | 2,160 | 4.25 | 4 | '''
Hotel Management App:
Display a menu asking whether to check in or check out.
Prompt the user for a floor number, then a room number.
If checking in, ask for the number of occupants and what their names are.
If checking out, remove the occupants from that room.
Do not allow anyone to check into a room that is already occupied.
Do not allow checking out of a room that isn't occupied.
Assuming hotel only has 3 floors with only rooms 101, 237, and 333.
Wrap total script in while: True to continuously check people in and out
'''
hotel = {
'1': {
'101': ['George Jefferson', 'Wheezy Jefferson'],
},
'2': {
'237': ['Jack Torrance', 'Wendy Torrance'],
},
'3': {
'333': ['Neo', 'Trinity', 'Morpheus']
}
}
def check_in(floor, room):
names = []
num_guests = int(input("How many guests are with you? >> "))
for i in range(num_guests):
guest_name = input("Enter the guest name >> ")
names.append(guest_name)
hotel[floor].update({room: names})
print(hotel)
def check_out(floor, room):
# clear out the people in that room
names = []
try:
if len(hotel[floor][room]) > 0:
hotel[floor].update({room: names})
else:
print("You can't check out of a room that is empty.")
except KeyError:
print("You're trying to check out of a room that doesn't exist.")
print(hotel)
while True:
front_desk = input('Check in or check out? >>').lower()
if front_desk == 'check in':
floor = input('What floor would you like to stay on? >> ')
room = input('What room number would you like? >> ')
try:
if len(hotel[floor][room]) > 0:
print("That room is currently occupied at the moment")
else:
check_in(floor, room)
except KeyError:
print("That room doesn't exist in this hotel.")
elif front_desk == 'check out':
floor = input('What floor were you on? >> ')
room = input('What was your room number? >> ')
check_out(floor, room)
else:
print("Invalid input")
break
| true |
c60a76d0ddb6dc630ff426e7efe0d0b109180a49 | Eduardogit/Challenges | /CoderByte/python/4-LetterChanges.py | 936 | 4.4375 | 4 | #LetterChanges(str) take the str parameter being
#passed and modify it using the following algorithm.
#Replace every letter in the string with the letter
#following it in the alphabet
#(ie. c becomes d, z becomes a).
#Then capitalize every vowel in this new string
#(a, e, i, o, u) and finally return this modified
#string.
#Use the Parameter Testing feature in the box below to test your code with different arguments.
# Input = "hello*3"Output = "Ifmmp*3"
#Input = "fun times!"Output = "gvO Ujnft!"
import re
def LetterChanges(str):
vowel =['a','e','i','o','u']
count = 0
li = list(str)
for i in str:
li[count] = chr(ord(i)+1)
if not re.findall("[a-zA-Z]",str[count]) :
li[count] = i
if str[count] == " " :
li[count] = ' '
if str[count] == "z":
li[count] = 'a'
if li[count] in vowel:
li[count] = li[count].upper()
count +=1
str = li
return str
print LetterChanges(raw_input("Letter Changes \n>:")) | true |
813297e248c01818031bf3ab371f8ee8112a25be | Eduardogit/Challenges | /CoderByte/python/6-LetterCapitalize.py | 415 | 4.1875 | 4 | #have the function LetterCapitalize(str)
#take the str parameter being passed and
#capitalize the first letter of each word.
#Words will be separated by only one space.
def LetterCapitalize(str):
word = ""
for i in xrange(0,len(str)):
if str[i-1] == " " and str[i-2] != " " or i == 0:
word +=str[i].upper()
else:
word +=str[i]
str = word
return str
print LetterCapitalize("this is the phrase")
| true |
201e6aee6bbbb7e14cbdef39dc3b603575793256 | Eduardogit/Challenges | /CoderByte/python/7-SimpleSimbols.py | 1,058 | 4.28125 | 4 | # the function SimpleSymbols(str) take the str parameter
#being passed and determine if it is an acceptable sequence
#by either returning the string true or false. The str
# parameter will be composed of + and = symbols with several
# letters between them (ie. ++d+===+c++==a) and for the string to
# be true each letter must be surrounded by a + symbol. So the
#string to the left would be false. The string will not be empty and will have at least one letter.
# Input = "+d+=3=+s+"Output = "true"
# Input = "f++d+"Output = "false"
from time import sleep
simbols = ['+','=']
def SimpleSymbols(str):
validation = False
for i in xrange(0,len(str)):
if str[0] not in simbols:
validation = False
elif str[i] not in simbols:
if i == len(str)-1 and str[i] not in simbols:
validation = False
break
elif str[i+1] in simbols and str[i-1] in simbols :
validation = True;
str = validation
return str;
print SimpleSymbols("++d+===+c++==a") #False
print SimpleSymbols("+d+=3=+s+") #True
print SimpleSymbols("f++d+") #False
| true |
c1444bad8efe48506753508352c375f24cf662b8 | OpenSource-Programming/PythonTraining | /022021/Vanessa/Melissa/Lesson4/GradUraise_py_Exercise3_2.py | 687 | 4.15625 | 4 | # Exercise 3.1
hours = input('Enter Hours: ')
try:
hval = int(hours)
except:
hval = -1
rate = input('Enter Rate: ')
try:
rval = int(rate)
except:
rval = -1
if hval < 0 and rval < 0:
print('Error - Hours and Rate are not valid numbers; Please enter numeric values')
elif hval < 0:
print('Error - Hours is not a valid number; Please enter numeric value')
elif rval < 0:
print('Error - Rate is not a valid number; Please enter numeric value')
else:
if int(hours)<= 40:
pay = int(hours) * float(rate)
print('Pay:', pay)
else :
pay = (40 * float(rate) + ((int(hours) - 40) * float(rate) * 1.5))
print('Pay:', pay)
print()
| true |
777d2e03238506cdb07e2c4f1bf992de4c2502ad | OpenSource-Programming/PythonTraining | /022021/Mo/Kavya/kavyanataraj-dev_py_03_CtoF.py | 501 | 4.3125 | 4 | #Exercise 5: Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
Celsius = int(input("Enter a temp in Celsius(integers only): ")) # input() is used take user input & int is used so that Celsius value(string) entered by user is converted to int and can be multiplied by 9/5
Farenheit = ((9/5)*Celsius)+32 #formula used for converting celsius to farneheit
print("Temp in Farenheit", Farenheit) #final output
| true |
f0bc4e05f7d887ea82e73d784e5f352ac7f8493b | MonseAreli/Roboticaing | /4.numbers.py | 511 | 4.15625 | 4 | #NUMBERS
#Suma de enteros en python, resultado entero
print(2+3)
#Suma de flotantes, resultado flotante
print(0.2 + 0.3)
#Suma de entero y flotante, resultado flotante
print(1 + 0.5)
#Restas y multiplicaciones trabajan de la misma manera
print(3 - 2)
print(3 - 1.5)
print(2 * 3)
print(2 * 0.8)
#El resultado de la división siempre será flotante
print(3.2 / 2)
print(3 / 2)
#Para elevar a una potencia se utiliza ** donde: numero**potencia
print(3 ** 2)
#Genera número arbitrario de decimales
print(0.2 + 0.1) | false |
fcf705ca9c1381497acd3990b1a74707010d8d11 | ilan274/python_exercises | /01_sequencial_structure/13_ideal_weight_men_or_women.py | 1,174 | 4.375 | 4 | # Having as input a person's height, create an algorithm
# that calculates their ideal weight using the following
# formulas;
# Men: (72.7 * height) - 58
# Women: (62.1 * height) - 44.7
def isFloat(x):
return x % 1 != 0
# returns true if number is float (contains decimal places)
men_or_women = input("Are you man or woman? ")
if men_or_women == "man" or men_or_women == "men":
# returns true if user types either 'man' or 'men'
height = float(input("Enter your height: "))
calc = (72.7 * height) - 58
if isFloat(calc): # verify if number have decimals
print("Your ideal weight is: {:.2f}.".format(calc))
else: # if not, returns number with no decimals
print("Your ideal weight is: {:.0f}.".format(calc))
elif men_or_women == "woman" or men_or_women == "women":
# returns true if user types either 'woman' or 'women'
height = float(input("Enter your height: "))
calc = (62.1 * height) - 44.7
if isFloat(calc): # verify if number have decimals
print("Your ideal weight is: {:.2f}.".format(calc))
else: # if not, returns number with no decimals
print("Your ideal weight is: {:.0f}.".format(calc))
else:
print("Please type \"man\" or \"woman\".") | true |
fddc651d8218a03d424db120cb381788bd0d1fb9 | PMiskew/Year9DesignTeaching2020_PYTHON | /Project3 Python Demo/project3_demo_stage1csVID.py | 1,536 | 4.15625 | 4 | #A class is a blueprint that is used to make objects
import tkinter as tk
class App():
#Fields - Attributes
#Constructors - Special methods called when we first create an instance
def __init__(self):
print("Builing App")
#Build my GUI
self.root = tk.Tk() #Capitalize methods are constructors
self.frame = tk.Frame(self.root, padx = 20, pady = 20, bg = "#4E4187", relief = tk.SUNKEN)
self.lab1 = tk.Label(self.frame, text = "Enter First Name", bg = "#4E4187", fg = "#7DDE92")
self.lab2 = tk.Label(self.frame, text = "Enter Last Name", bg = "#4E4187", fg = "#7DDE92")
self.lab3 = tk.Label(self.frame, text = "Enter Access Code", bg = "#4E4187", fg = "#7DDE92")
self.text1 = tk.Text(self.frame, width = 30, height = 1, borderwidth = 2, relief= tk.GROOVE, fg = "#7DDE92")
self.text2 = tk.Text(self.frame, width = 30, height = 1, borderwidth = 2, relief= tk.GROOVE, fg = "#7DDE92")
self.text3 = tk.Text(self.frame, width = 30, height = 1, borderwidth = 2, relief= tk.GROOVE, fg = "#7DDE92")
self.btn = tk.Button(self.frame, text = "LOGIN")
self.lab1.grid(row = 0, column = 0)
self.lab2.grid(row = 1, column = 0)
self.lab3.grid(row = 2, column = 0)
self.text1.grid(row = 0, column = 1, columnspan = 2)
self.text2.grid(row = 1, column = 1, columnspan = 2)
self.text3.grid(row = 2, column = 1, columnspan = 2)
self.btn.grid(row = 3, column = 1, sticky = "NESW")
self.frame.pack()
self.root.mainloop()
#Method - Behaviours
a = App() #Create an app object and store the reference in a
| true |
f77fcfaa54590ce9eff9bf9b28102826d6b4cb9d | ACM-VIT/PyFlask_2k18 | /datatypes/examples/tuples.py | 1,403 | 4.46875 | 4 | # Creating Tuples
college=("VIT","DTU","IIT")
# Another method for creating tuples
Laptops=tuple(("Macbook-Air","Macbook-Pro","HP-Pavillion"))
print(Laptops)
#This will print the Laptops tuple
# Accessing Tuples
ACM_WEB=("Aditya","Shubham","Rakshit")
print(ACM_WEB[0])
#This will print Aditya
# Immutablity of Tuples
#**Example1**
ACM_WEB=("Aditya","Shubham","Rakshit")
ACM_WEB[0]="Shivank"
print(ACM_WEB)
#This will still print the original tuple
#**Example2**
pokemon=("Pickachu","Charizard","Blastoise")
pokemon[3]="Mr.Mime"
#This will raise an error
print(pokemon)
# Looping Through a Tuple
sports=("Cricket","Football","Basketball")
for x in sports:
print(x)
# Calculating Tuple Length
pokemon=("Pickachu","Charizard","Blastoise")
pokemon[3]="Mr.Mime"
#This will raise an error
print(pokemon)
# Deleting Tuple
pokemon=("Pickachu","Charizard","Blastoise")
del pokemon
#This will delete the Tuple
# count() method of tuples
# vowels tuple
vowels = ('a', 'e', 'i', 'o', 'i', 'o', 'e', 'i', 'u')
# count element 'i'
count = vowels.count('i')
#The ouput will be :3
# index() method of tuples
# vowels tuple
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
# element 'e' is searched
index = vowels.index('e')
# index is printed
print('The index of e:', index)
# element 'i' is searched
index = vowels.index('i')
# only the first index of the element is printed
print('The index of i:', index)
| false |
456b07ce58f9c420fed97a7bccbe095540b8e55b | ParulProgrammingHub/assignment-1-bansiundhad | /q2.py | 225 | 4.375 | 4 | # enter redius of circle and calculate area and circumference of circle.
pi=3.14
r=input("enter the radius :")
area=pi*r*r
cir=2*pi*r
print "the area of circle is %s"%area
print "the circumference of circle is %s"%cir
| true |
2cc9edd7c910bcb757a9d907e83010fc072da77c | imorerod/hello-world | /functions.py | 472 | 4.125 | 4 |
# 'def' is a key word to use a function
# Python naming convention is to use lowercase, snake-case for:
# 1) variables 2) methods 3) functions
def say_hi(name, age):
# line 12 has 27 as a number; 'str' converts the number to a string so it can concatenate
print('Hello ' + name + ', you are ' + str(age) + ' years old.')
say_hi('Isaac', 27)
say_hi('Morgan', 27)
# Return Statements
def cube(num):
return num*num*num
result = cube(5)
print(result)
| true |
cb951e94eee6900ca9cff00fbe792618ee136fc3 | ayushkhandelwal126/python | /test.py | 207 | 4.125 | 4 | x = int(input("enter the number"))
if x > 1:
for i in range(2, x):
if(x % i) == 0:
print("it is not a prime number")
break
else:
print("it is a prime no.")
| true |
01a43db3148f9125f16bc100d0aca23c32a7fa2e | yabhinav/Algorithms | /pythonds/bubblesort.py | 514 | 4.34375 | 4 | # bubble sort makes multiple passes through a list. It compares adjacent items
# and exchanges those that are out of order. Each pass through the list places
# the next largest value in its proper place. In essence, each item 'bubbles' up
# to the location where it belongs.
def bubblesort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i] > alist[i+1]:
alist[i],alist[i+1]=alist[i+1],alist[i] #swap
alist = [54,23,46,93,17,77,44,50,17]
bubblesort(alist)
print alist | true |
20b9e94e80c4cec30efe56e2124d780326b56e75 | theByteCoder/CorePython | /With.py | 669 | 4.1875 | 4 | # without using with
# write file
val = open("ReadWriteAppendFile.txt", "w")
try:
val.write("Coding is great")
finally:
val.close()
# read file
val = open("ReadWriteAppendFile.txt", "r")
print(val.read())
val.close()
# in the above code, notice that write and close have been handled in try finally blocks to avoid exception
# performing same action with WITH statement
# write file
with open("ReadWriteAppendFile.txt", mode="w") as new_val:
new_val.write("Coding is best")
# WITH statement automatically handles exceptions and closes the file
# read file
with open("ReadWriteAppendFile.txt", mode="r") as foo:
print(foo.read())
| true |
38b9ba5d280fb3f147b0b84e67d39be51baefcb1 | aadeshdhakal/python_assignment_dec1 | /happy_birthday.py | 221 | 4.21875 | 4 | def birthday(f_name):
print("{0} {1} {2} {3}\n{0} {1} {2} {3}\n{0} {1} {4} {5}\n{0} {1} {2} {3}!!".format("happy", "birthday", "to", "you", "dear", f_name))
name = input("Enter your friend's name: ")
birthday(name)
| false |
dc9d9c82cfe3b661ad491a2e109336465ad67f51 | zTaverna/Logica-de-Programacao | /Unidade 01/teste 02.py | 310 | 4.1875 | 4 | fruta = input("Escreva o nome de uma fruta: ")
verdura = input("Escreva o nome de uma verdura: ")
legume = input("Escreva o nome de uma legume: ")
x = 2
y = 3.5
z = 5
print("Aqui estão os nomes de uma fruta, uma verdura e um legume:")
print(fruta,":",x,",", verdura,":",y,"e", legume,":",z,".")
| false |
89a854f71e0e5eef0b9ff1f1f808c03eab5a0ad9 | zTaverna/Logica-de-Programacao | /Unidade 01/Aula 04 ex 02.py | 602 | 4.15625 | 4 | num1=int(input("Digite um número inteiro: "))
num2=int(input("Digite outro número inteiro: "))
num3=int(input("Digite um último número inteiro: "))
if num1<num2 and num2<num3:
a=num1
b=num2
c=num3
elif num1<num2 and num3<num2:
a=num1
b=num3
c=num2
elif num2<num1 and num1<num3:
a=num2
b=num1
c=num3
elif num2<num3 and num3<num1:
a=num2
b=num3
c=num1
elif num3<num1 and num1<num2:
a=num3
b=num1
c=num2
else:
a=num3
b=num2
c=num1
print("A ordem crescente dos valores é {}, {} e {}".format(a,b,c))
| false |
590c9d5b8dafcd35159a2a668d61d95fb9f54395 | manynames3/python-rei-calculator | /python-rei-calculator.py | 1,757 | 4.15625 | 4 | # Real Estate Investment return calculator by Aiden Rhaa
# Assumptions: Cash purchase & 8% selling cost.
# In v2, converted user input sections to while True, try, except. In order to prevent users from entering non-integer input.
print("Welcome to REI calculator\n")
# user input purchase price. user must enter an integer, other wise they will be re-asked.
while True:
try:
purchase_price = int(input("Purchase Price: $"))
break
except:
print("That's not a valid option!")
# user input holding period. user must enter an integer, other wise they will be re-asked.
while True:
try:
holding_period = int(input("Holding period in years: "))
break
except:
print("That's not a valid option!")
# user input appreication rate. user must enter an integer, other wise they will be re-asked.
while True:
try:
appreciation_rate = int(input("Expected Annual Appreciation %: "))
break
except:
print("That's not a valid option!")
# value of the property at the end of holding period
future_value = round(purchase_price * (1 + appreciation_rate/100) ** holding_period)
# selling cost at the end of holding period, 8%
selling_cost = round(future_value * 0.08)
# outcome of your real estate investment
print(f"\nIn {holding_period} years, your investment property will be worth ${future_value}. After 8% selling cost of ${selling_cost}, this investment will have netted you ${future_value - purchase_price} in profit!")
# year by year look at numbers
print("\nHere is annualized look at the numbers: ")
counter = 1
while counter <= holding_period:
gained_value = purchase_price * (appreciation_rate/100)
purchase_price += int(gained_value)
print(f"Year {counter}: ${purchase_price}")
counter += 1 | true |
601da77370a727f5abf2e2577d49d30688948513 | tekrondo/snake-island | /dictionaryPractice.py | 747 | 4.15625 | 4 | names = list()
nameOccurence = dict()
moreNames = True
while moreNames:
name = input('Enter the name, type done when done: ')
try:
name != int(name)
print('Please input a valid name!\n', 'Or \n')
numberOfOccurenceInDictionary = input('Look for a name: ')
# Search for a name in the dictionary and return how many times it appears
print(f'{numberOfOccurenceInDictionary} appears \
{nameOccurence.get(numberOfOccurenceInDictionary, 0)} \
times in the list')
except:
if name == 'done':
moreNames = False
print(nameOccurence)
else:
names.append(name.title())
for name in names:
nameOccurence[name] = names.count(name)
| true |
191cce665585111528b5f3a0d1addc4363a0d9a4 | jianning1/Python-Study | /ex13.py | 703 | 4.46875 | 4 | # Exercise 13 Parameters, Unpacking, Variables
from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv
# unpacks argv to hold all the arguments
# when running this script
# python3.6 ex13.py x y z
# take x as first, y as second, z as third
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
favoriate =input("Your favoriate variable is: ")
print(f"So, among {first}, {second}, and {third}, your favoriate is {favoriate}")
# Difference between argv and input()
# When to give inputs
# input() returns string, to convert to int, use int(input())
| true |
f6f73db24c143bcdefc05e246e2d346ee27c0c5e | Mils18/Lab | /Millen_2201797531_LambdaCalculator.py | 1,588 | 4.3125 | 4 | #Lambda Calculator Assignment
#Millen Dwiputra - 2201797531 - L1AC
num1 = int(input("input first number = ")) #A variable to input first number
print("Binary Operator") #Prints "Binary Operator"
operator = input("input with [+,-,*,/,^] = ")#shows operator available to be inputted
num2 = int(input("input second number = ")) #A variable to input second number
if operator == "+": #if the operator's "+"
x = lambda num1,num2 : num1 + num2 #A lambda function to sum first number with second number
print("RESULT = ",x(num1,num2)) #prints final result
elif operator == "-": #if the operator's "-"
x = lambda num1,num2 : num1 - num2 #A lambda function to substract first number with second number
print("RESULT",x(num1,num2)) #prints final result
elif operator == "*": #if the operator's "*"
x = lambda num1,num2 : num1 * num2 #A lambda function to multiply first and second number
print("RESULT",x(num1,num2)) #prints final result
elif operator == "/": #if the operator's "/"
x = lambda num1,num2 : num1 / num2 #A lambda function to divide first number with second number
print("RESULT",x(num1,num2)) #prints final result
elif operator == "^": #if the operator's "^"
x = lambda num1,num2 : num1 ** num2 #A lambda function to power first number with second number
print("RESULT",x(num1,num2)) #prints final result
| true |
412f1e22e2d2e12ed5a1254740c4b2cdfb23432a | nxg153030/Algorithms | /algorithms/sorting/radix_sort.py | 992 | 4.1875 | 4 | def counting_sort(A, place):
k = max(A)
C = [0] * (k + 1) # temp array
sorted_arr = [0] * len(A)
for j in range(len(A)):
C[((A[j] // place) % 10)] += 1 # C[i] now contains the no. of elements = i
for i in range(1, k + 1):
C[i] += C[i - 1] # C[i] now contains the no. of elements <= i
for j in range(len(A) - 1, -1, -1):
sorted_arr[C[(A[j] // place) % 10] - 1] = A[j]
C[(A[j] // place) % 10] -= 1
# copy sorted_arr contents to input array
for i in range(len(A)):
A[i] = sorted_arr[i]
def radix_sort(A, d):
"""
Radix sort sorts an array by sorting on the least significant digit first.
It makes use of a stable sort algorithm, in this case, counting sort to sort the array on the digit.
"""
place = 1
for _ in range(0, d):
counting_sort(A, place=place)
place *= 10
if __name__ == '__main__':
A = [329, 457, 657, 839, 436, 720, 355]
radix_sort(A, d=3)
print(A)
| true |
600ac737ecad1e9884daac70a316b796819cfd41 | Cabralcm/Python | /educative/1_fsp/p8_async/p8_1.py | 1,599 | 4.21875 | 4 | # Python Exercise
# Multiple Asynchronous Calls
# Change the previous program to schedule the execution of two calls to the sum function
import asyncio
async def get_sum(n1,n2):
print(f"Sum Number: {n1} + {n2}")
res = n1 + n2
await asyncio.sleep(res)
print(f"End Sum: {n1} + {n2}")
return res
# Create Event Loop
loop = asyncio.get_event_loop()
# Run async function and wait for completion
results = loop.run_until_complete(asyncio.gather(
get_sum(1,0),
get_sum(1,1),
get_sum(1,2)
))
print(results)
# Close the loop
loop.close()
# Official Solution
import asyncio
async def async_sum(n1,n2):
print(f"Input: {n1},{n2}")
res = n1 + n2
await asyncio.sleep(1)
print(f"Output: {res}")
return res
loop = asyncio.get_event_loop()
results = loop.run_until_complete(asyncio.gather(
async_sum(1,2),
async_sum(1,3),
async_sum(1,4)
))
print(results)
# Close the loop
loop.close()
'''
OUTPUT
Sum numbers 2 + 3
Sum numbers 3 + 4
Sum numbers 1 + 2
End Sum 2 + 3
End Sum 3 + 4
End Sum 1 + 2
[3, 5, 7]
'''
# Async outline
"""
import asyncio
async def sum_async(n1,n2):
await asyncio.sleep(1)
return
loop = asyncio.get_event_loop()
results = loop.run_until_complete(asyncio.gather(
sum(n1,n2),
sum(n1,n2),
sum(n1,n2)
))
loop.close()
"""
"""
import asyncio
async def sum(n1,n2):
print("Input")
await asyncio.sleep(1)
print("end")
return n1+n2
loop = asyncio.get_event_loop()
results = loop.run_until_complete(gather(
sum(1,1),
sum(1,2),
sum(1,3)
))
print(results)
loop.close()
""" | true |
73abe21e2b2cf8a0139ae2d101a1102599988513 | Cabralcm/Python | /educative/2_py/2_col/p7.py | 1,747 | 4.34375 | 4 | from collections import namedtuple
parts = namedtuple('Parts', 'id_num desc cost amount')
auto_parts = parts(id_num = '1234', desc= 'Ford Engine', cost = 1200.00, amount= 10)
print(auto_parts.id_num)
print(dir(auto_parts))
# Standard Tuple
auto_parts = ('1234', 'Ford Engine', 1200.00, 10)
print(auto_parts[2])
#1200.00
id_num, desc, cost, amount = auto_parts
print(id_num)
# using the named tuple approach, you can use Python's dir() method to inspect the tuiple and find out its properties!
# Convert Python dictionary int oan object
Parts = {'id_num':'1234', 'desc':'Ford Engine',
'cost':1200.00, 'amount':10}
# create our namedtuple class, and name it Parts.
# The second arugment is a LIST of the keys from our dictionary.
# The last piece is this strange piece of code, (**Parts)
# The Double Asterisk means that we are calling our class using keywords arugments, which in this case is our dictionary.
parts = namedtuple('Parts', Parts.keys())(**Parts)
print (parts)
#Parts(amount=10, cost=1200.0, id_num='1234', desc='Ford Engine')
# We could split the double asterisk part into two lines to make it cleaner
parts = namedtuple('Parts', Parts.keys())
print(parts)
auto_parts = parts(**Parts)
print(auto_parts)
# Doing the same thing as before, we create the class first, then call the class with our dictionary to create an object
# Namedtuple also accepts a verbose argument, and a rename argument.
# The verbose arugment is a flag that will print out class definition right before it's built if you set it to True.
# The rename argument is useful if you're creating your namedtuple from a database or some other system that your
# program doesn't control as it will automatically rename the properties for you!
| true |
59f8c3a44efd24491a1a092f16bdcb180acd9c46 | AdamBen7/PracticeRepo | /python2.7/Python UM Coursera/datetimenow().py | 764 | 4.59375 | 5 | #We can use a function called datetime.now() to
#retrieve the current date and time.
from datetime import datetime
print datetime.now()
#The first line imports the datetime library so that we can use it.
#The second line will print out the current date and time.
# Extracting Information
# Notice how the output looks like 2013-11-25 23:45:14.317454.
# ~What if you don't want the entire date and time?
from datetime import datetime
now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day
# You already have the first two lines.
# In the third line, we take the year (and only the year)
# from the variable now and store it in current_year.
# In the fourth and fifth lines,
# we store the month and day from now.
| true |
4e79b49d5d784841f6ec959ccad5fc1ff4fe5111 | AdamBen7/PracticeRepo | /python2.7/Python UM Coursera/Chapter5loopAVRGprogram.py | 378 | 4.15625 | 4 |
print 'Say "Done" when you have entered all inputs!'
count = 0
sum = 0
while True:
inpt = raw_input("Enter a number: ")
if inpt == "Done" or "done": break
try:
float(inpt)
except:
print "This isn't a number. Please place a numerical value!"
quit()
print inpt
print type(inpt)
count = count +1
sum = sum + float(inpt)
if count != 0:
Avg = sum/count
print Avg | true |
2dde7368966c14fb37a2516fbcfdd2b900f5f237 | sopoour/blockchain-python | /assignments/assignment_2.py | 855 | 4.4375 | 4 | # 1) Create a list of names and use a for loop to output the length of each name (len()).
list_names = ["Sophia", "Evelina", "Nicolas", "Alexander"]
check_names = False
for name in list_names:
# 1)
#print(name +":", len(name))
# 2) Add an if check inside the loop to only output names longer than 5 characters.
# 3) Add another if check to see whether a name includes a “n” or “N” character.
if len(name) > 5 and ("n" in name or "N" in name):
print(name + ":", len(name))
check_names = True
# 4) Use a while loop to empty the list of names (via pop())
while check_names:
print(list_names)
list_names.pop()
if len(list_names) < 1:
break
print("List is empty")
"""
better solution or a bit different:
while len(list_names) >= 1:
print(list_names)
list_names.pop()
print("List is empty")
""" | true |
e434358092fc974beab29c9da0593514e8c2eac1 | Ben-Lapuhapo/ICS3U-Unit-2-02-Python | /rectangle_calculator2.py | 527 | 4.34375 | 4 | #!/usr/bin/env python3
# Created by: Ben Lapuhapo
# Created on: September 14 2019
# This program calculates area and perimeter of a rectangle that the user gave
def main():
print("")
length = int(input("Please enter the rectangle's length: "))
print("")
width = int(input("Please enter the rectangle's width: "))
area = length*width
perimeter = 2*(length+width)
print("")
print("Area is {}mm^2".format(area))
print("Perimeter is {}mm".format(perimeter))
if __name__ == "__main__":
main()
| true |
0d2f56c1077b90c6a3104fe77a1b633fe6a06dcb | SophieEchoSolo/PythonHomework | /StudyGuides/datetime-examples.py | 846 | 4.46875 | 4 | import datetime
# This examples gets user inputs and then determines the difference between the two dates entered
year1 = int(input("Enter a year number: "))
month1 = int(input("Enter a month number: "))
date1 = int(input("Enter a day number: "))
year2 = int(input("Enter another year number: "))
month2 = int(input("Enter another month number: "))
date2 = int(input("Enter another day number: "))
date1 = datetime.date(year1, month1, date1)
date2 = datetime.date(year2, month2, date2)
diff = date1 - date2
print(str(diff.days) + " days between the dates you entered.")
# Shows the dates entered in different formats
print(date1.strftime("%d/%m/%Y"))
print(date1.strftime("%b %d, %Y"))
print(date1.strftime("%B %d, %Y"))
print(date1.strftime("%a %B %d, %Y"))
print(date1.strftime("%A %B %d, %Y"))
print(date1.strftime("%A, %B %d, %Y"))
| true |
6e013a7533f3af60a8f63db713f8d45b490218cc | XanderOlson/mega_project_list | /text/reverse_string.py | 338 | 4.46875 | 4 | """
Reverse a String
Created 6/15/2015
"""
def main():
#Prompt user for a string
input_string = raw_input("Please enter a string then hit 'Enter':\n")
print "\nReversing the string...\n" # Short status bar with spacing
print "Your reversed string:\n" + input_string[::-1] # Print reversed string
if __name__ == '__main__':
main() | true |
8b8e89705b8442c3268f6cb5318d39584251c5d8 | aslamsikder/Complete-Python-by-Aslam-Sikder | /Aslam_05_dictionaries.py | 655 | 4.46875 | 4 | """
Dictionary is one kind of data types that have two elements
separated by ':'colon. First one is 'Value' & Second is the 'key'.
To create Dictionary, we need to use Second Bracket & Colon [ : ]
"""
# Creating a Dictionary
names = {'Aslam' : 25,
'Tanjina': 15,
'Zakia': 2.5,
'Rakibul': 24}
print("My dictionaty consists of: ", names)
# Accessing from Dictionary
print("\nThe keys of the dictionary are: ", names.keys())
print("The values of the dictionary are: ", names.values(), '\n')
# Showing Specific Key's value
print("The age of Aslam is", names['Aslam'])
print("The age of Zakia is",names['Zakia']) | true |
45ed44673a3c46e0e5065af64a568f4c2e45a794 | aslamsikder/Complete-Python-by-Aslam-Sikder | /Aslam_07_conditinal_logic.py | 351 | 4.21875 | 4 | # If Else statement
print("Enter your marks: ")
number = int(input())
if (number>=1 and number<=100):
if (number<=100 and number>=80):
grade = 'A+'
elif (number<=80 or number>=70):
grade = 'A'
else:
grade = 'less than 70% marks!'
print("You got", grade)
else:
print("You have entered an invalid marks!") | true |
1b86c934f945839f07605a8e050797639f6bdfba | SayanNL1996/Git_Practice | /Condition.py | 252 | 4.25 | 4 | x=int(input('enter the first number '))
y=int(input('enter the second number '))
z=int(input('enter the third number '))
if x>y and x>z:
print('X is the largest')
elif y>x and y>z:
print('Y is the largest')
else:
print('Z is the largest') | false |
0337e09b3b8475c7986b8cd1f5b8e228b781e763 | TheRealChrisM/CVGS-Computer-Science | /Python/PascalTriangleCreator.py | 707 | 4.3125 | 4 | #Christopher Marotta
#Pascal's Triangle Creator
rowSize = 9
maxSize = 5
sideInput = -1
curSize = 1
#prompt user to input the desired size of Pascal's Triangle
while (sideInput > maxSize) or (sideInput <= 0):
sideInput = eval(input("How many rows would you like for this triangle to be? [1-5]: "))
#Print first row
print(format("1", "^9s"))
while curSize < sideInput:
if curSize == 1:
print(format("1 1", "^9s"))
curSize += 1
if curSize == 2:
print(format("1 2 1", "^9s"))
curSize += 1
if curSize == 3:
print(format("1 3 3 1", "^9s"))
curSize += 1
if curSize == 4:
print(format("1 4 6 4 1", "^9s"))
curSize += 1
| true |
91fc4e5211da72604e6dea867f4982803b980f75 | samuelfekete/Pythonometer | /pythonometer/questions/standard_library/built_in_functions.py | 2,251 | 4.53125 | 5 | """Questions about the built-it functions.
Docs: https://docs.python.org/3.6/library/functions.html
"""
import textwrap
from ..base import Question, WrongAnswer
class AbsoulteValue(Question):
"""Get the absolute value of a number.
https://docs.python.org/3.6/library/functions.html#abs
"""
def get_question_text(self):
return textwrap.dedent(
"""\
Get the absolute value of a number.
Assume you have a variable called `some_number`, which contains a number.
Write some code that evaluates to the absolute value of that number.
"""
)
def check_answer(self, answer):
test_numbers = [0, 1, -1, 0.0, 0.1, -0.1]
try:
if all(
abs(some_number) == eval(answer, {}, {'some_number': some_number})
for some_number in test_numbers
):
return True
else:
raise WrongAnswer('Answer is not correct for all cases.')
except Exception as e:
raise WrongAnswer(e)
def get_correct_answers(self):
return ['abs(some_number)']
def get_wrong_answers(self):
return ['-some_number']
class TrueForAll(Question):
"""Check if all items are true.
https://docs.python.org/3.6/library/functions.html#all
"""
def get_question_text(self):
return textwrap.dedent(
"""\
Check if all items are true.
Assume you have a collection called `items`.
Write some code that evaluates to True if every item in the collection if true.
"""
)
def check_answer(self, answer):
test_cases = [
[True, True, True],
[True, True, False],
]
try:
if all(
all(case) == eval(answer, {}, {'items': case})
for case in test_cases
):
return True
else:
raise WrongAnswer('Answer is not correct for all cases.')
except Exception as e:
raise WrongAnswer(e)
def get_correct_answers(self):
return ['all(items)']
def get_wrong_answers(self):
return ['True']
| true |
a1176f5f43f40b7be2509427d8fdcf61af3607bb | mgbo/My_Exercise | /2018_2019/____MIPT___/PythonCodes/zadaza_2.py | 781 | 4.25 | 4 |
'''
Задача 2. Взлом шифра
Вы знаете, что фраза зашифрована кодом цезаря с неизвестным сдвигом.
Попробуйте все возможные сдвиги и расшифруйте фразу.
Номер варианта дает преподаватель
'''
text = input()
text = text.lower()
oldalphabet = 'abcdefghijkmnopqrstuvwxyz'
def make_dekodirobaniye(oldalphabet, text, n):
de_code = ''
for i in text:
if i in oldalphabet:
de_code += oldalphabet[(oldalphabet.index(i)+ (25+n))%len(oldalphabet)]
else:
de_code += i
return de_code
n = 1
while n!= 0:
codetext = make_dekodirobaniye(oldalphabet, text, n)
print (codetext)
n = int(input("Введите сдвиг : "))
| false |
f79cb2be7d1a8b92452aae92bcac3e8f49897c73 | mgbo/My_Exercise | /Дистанционная_подготовка/Программирование_на_python/13_символы_строки/Simple_Infix.py | 1,570 | 4.28125 | 4 |
# Simple Infix Expression Evaluation Using A Stack
# The expression must be fully parenthesized
# (meaning 1+2+3 must be expressed as "((1+2)+3)")
# and must contain only positive numbers
# and aritmetic operators.
# FB - 20151107
def Infix(expr):
expr = list(expr)
stack = list()
num = ""
while len(expr) > 0:
# print ("LENGTH LIST ---> {}".format(len(expr)))
c = expr.pop(0)
if c in "0123456789.":
# print ('C ---> {}'.format(c))
num += c
else:
if num != "":
stack.append(num)
num = ""
if c in "+-*/":
stack.append(c)
elif c == ")":
num2 = stack.pop()
op = stack.pop()
num1 = stack.pop()
print (num1,num2,op)
if op == "+":
stack.append(str(float(num1) + float(num2)))
print ('ADD ---> {}'.format(stack))
elif op == "-":
stack.append(str(float(num1) - float(num2)))
print ('SUB ---> {}'.format(stack))
elif op == "*":
stack.append(str(float(num1) * float(num2)))
print ('MULTI ---> {}'.format(stack))
elif op == "/":
stack.append(str(float(num1) / float(num2)))
print ('DIV ---> {}'.format(stack))
return stack
expr = "(1+(2*3))-5"
# expr = input()
print (expr)
print (Infix(expr))
# print (eval(expr))
| true |
81d2fdf490bde11cdea914a129dc213f15c2bfa5 | alexfeitler/Programming2_Alex | /Notes/Turtle_Recursion.py | 2,386 | 4.125 | 4 |
def controlled(level, end_level):
print("Recursion level: ", level)
if level < end_level:
controlled(level + 1, end_level)
print("Level", level, "closed")
controlled(0, 10)
import turtle
my_turtle = turtle.Turtle()
my_turtle.speed(6)
my_turtle.width(3)
my_turtle.shape("turtle")
my_screen = turtle.Screen()
'''
my_turtle.goto(0, 0) # move to coordinates
my_turtle.goto(100, 0)
my_turtle.goto(100, 100)
my_turtle.pencolor("lightblue")
my_turtle.forward(100) # driving the turtle
my_turtle.left(90) # turning
my_turtle.forward(100)
my_turtle.right(45)
my_turtle.backward(50)
my_turtle.penup()
my_turtle.goto(0, 0)
my_turtle.pendown()
my_turtle.setheading(90) #turn to the heading (0 right, 90 up, 180 left)
# draw a shape
my_turtle.fillcolor("red")
my_turtle.pencolor("black")
my_turtle.begin_fill()
for i in range(8):
my_turtle.forward(50)
my_turtle.right(45)
my_turtle.end_fill()
distance = 200
for i in range(100):
my_turtle.forward(distance + i)
my_turtle.right(100)
'''
def rect_recursive(width, height, depth, line_width=1):
'''
draws rectangle to center of the screen
:param width:
:param height:
:return:
'''
if depth > 0:
my_turtle.pensize(line_width)
my_turtle.penup()
my_turtle.goto(-width / 2, height / 2)
my_turtle.pendown()
my_turtle.pencolor("darkblue")
my_turtle.setheading(0)
for i in range(2):
my_turtle.forward(width)
my_turtle.right(90)
my_turtle.forward(height)
my_turtle.right(90)
rect_recursive(width * 1.25, height * 1.25, depth - 1, line_width * 1.25)
rect_recursive(40, 23, 20)
def bracket_recursion(x, y, size, depth):
my_turtle.penup()
my_turtle.goto(x, y)
my_turtle.pendown()
my_turtle.setheading(90)
my_turtle.forward(size)
my_turtle.right(90)
my_turtle.forward(100) # make this constant
pos1 = my_turtle.pos()
my_turtle.penup()
my_turtle.goto(x, y)
my_turtle.pendown()
my_turtle.setheading(-90)
my_turtle.forward(size)
my_turtle.left(90)
my_turtle.forward(100)
pos2 = my_turtle.pos()
if depth > 0:
x, y = pos1
bracket_recursion(x, y, size * 0.5, depth - 1)
x, y = pos2
bracket_recursion(x, y, size * 0.5, depth - 1)
bracket_recursion(-250, 0, 150, 5)
my_screen.exitonclick()
| false |
ff4bc35e9d5259e2fba559e4af15cc876ec4f0ae | Bubliks/bmstu_Python | /sem_1/Lab_6 - Integral/Integral_2.py | 2,043 | 4.21875 | 4 | from math import *
print("Ввод исходных данных:")
a = float(input("Нижний предел интегрирования(a): "))
b = float(input("Верхний предел интегрирования(b): "))
h1 = int(input("Количество отрезков(n1): "))
h2 = int(input("Количество отрезков(n2): "))
if h1==0 or h2==0:
print("Ошибка ввода исходных данных")
else:
eps = float(input("Введите eps: "))
print("______________________________\nРезультат работы программы:")
def Funct(x):
#I=x*x
I=x+1
return(I)
def methodTrapec(n):
h=abs((b-a)/n)
a1=a+h
summa=0
while a1<b:
summa+=Funct(a1)
a1+=h
Ploshad = h*((Funct(a)+Funct(b))/2 + summa)
return(Ploshad)
def method38(n):
h=abs((b-a)/(3*n))
summa=0;k=3*n
for i in range(k):
x=a+h*i
if i%3==0:
summa+=2*Funct(x)
else:
summa+=3*Funct(x)
Ploshad = 3/8*h*(Funct(a)+Funct(b)+summa)
return(Ploshad)
print("______________________________________________________")
print("| Метод | n1 = ","{:10}".format(h1),\
"| n2 = ","{:10}".format(h2),"|")
print("______________________________________________________")
print("| Трапеция |","{:17.10}".format(methodTrapec(h1)),\
"|","{:17.10}".format(methodTrapec(h2)),"|")
print("______________________________________________________")
print("| 3/8 |","{:17.10}".format(method38(h1)),\
"|","{:17.10}".format(method38(h2)),"|")
print("______________________________________________________")
h3 = 1; Integral=methodTrapec(h3)
while abs(methodTrapec(2*h3)-methodTrapec(h3))>abs(eps):
Integral = methodTrapec(h3)
h3*=2
print("Значение интеграла (метод Трапеции) = ","{:5.10}".format(Integral)\
," Участков разбиения = ",h3)
| false |
e90249be9c38538470a45d3ff25bd13f4d57efbb | namkiseung/python_BasicProject | /python-package/daily_study/python/question_python(resolved)/chapter2_input_and_output(완결)/age_to_birth.py | 487 | 4.125 | 4 | # -*- coding: utf-8 -*-
import sys
def age_to_birth(age):
""" 나이를 인자로 입력받고, 출생년도를 화면에 출력하도록 해봅시다.
hint: - 연산 사용
!sample data: 23
!output: 1995
"""
now = 2018
value = now-(age-1)
print value, 'years'
# 여기에 작성
if __name__ == "__main__":
# 새로 작성, 주석 해제 등등 하면 됨(input 함수 사용)
age = input('age? :')
age_to_birth(age)
| false |
1891fff6420cf2b27ea86bf69c007d293fc9d91c | cassantiago/520-python | /Aula3/parametros.py | 1,701 | 4.125 | 4 | #!/usr/bin/python3
######################
##
#####################
# def retorna_pessoa(nome,idade=99):
# print(f'nome: {nome}\nidade: {idade}')
# retorna_pessoa(nome='Daniel', idade=19)
#############
##especificar tipo de parametro e retorno
#############
#Anotacoes de funcao
#print ('olá','mundo',',','prazer','sou','daniel')
############criando uma função que recebe multiplos valores
# def funcao_multi_valores(parametros_estaticos,*argumento_variavel):
# print(parametros_estaticos,'parametro estático')
# print(argumento_variavel)
#fazendo acesso aos parametros
#for argumento in argumento_variavel:
# print(argumento)
# funcao_multi_valores('valor estatico obrigatório',
# 'Daniel','andressa','joão','Ana',
# 'Paula','lucas','Leonardo','Pedro')
##Argumentos com palavras chave -kwargs
# def parametros_chave_valor(**dados):
# if dados['nome']=='daniel':
# print ('acesso negado')
# print(dados)
# #Execução - metodo 1
# print('metodo 1')
# parametros_chave_valor(nome='Daniel',sobrenome='Silva',
# idade=19,sexo='masculino')
# #execução - metodo 2
dados_requisicao = {'nome':'Daniel',
'sobrenome':'Silva',
'Profissão':'Operador de empilhadeira'}
#parametros_chave_valor(**dados_requisicao)
#decoradores de função
#uma funcao que modifica o valor da outra
#declara uma funcao com uma variavel funcao obrigatoria
def mudaCor(retorno_funcao):
def modificaAzul(retorno_funcao):
return f'\033[91m{retorno_funcao}\033[0m'
return modificaAzul
@mudaCor
def log(texto):
return texto
print(log('oi'))
3 | false |
01f438ab7ef9924f66c503bf2fdb3a556c97a582 | charlesmtz1/Python | /W3/018_Math.py | 620 | 4.15625 | 4 | #El modulo MATH permite realizar operaciones matematicas mas complejas. Se declara de la siguiente manera:
import math
#Algunas funciones matematicas se pueden utilizar sin importar el modulo, como son el valor absoluto y el redondeo.
x = 10.2
y = -8
print(round(x))
print(abs(y))
#Funciones como seno, coseno, tangente, etc, deben ser llamados del modulo math
print(math.cos(0.5))
print(math.tan(0.5))
print(math.sin(0.5))
#Se pueden combinar para realizar operaciones complejas con otras variables.
z = 10 * math.cos(0.5)
print(z)
#Aqui hay otras funciones del modulo MATH
print(math.floor(x))
print(math.ceil(x)) | false |
c740481f2b13dc829cbc1aef542e17bd0ca9bfd9 | charlesmtz1/Python | /W3/011_Diccionarios.py | 2,614 | 4.46875 | 4 | #Los diccionarios son colecciones de datos que no tienen un orden definido , pero pueden ser cambiados e indexados. Se declaran entre llaves y especificando el nombre del indice.
diccionario = {
"Marca" : "Ford",
"Modelo" : "Mustang",
"Año" : 1996
}
print(diccionario)
#Se puede acceder a los datos del diccionario haciendo referencia a su indice. Tambien se puede utilizar la funcion get()
x = diccionario["Modelo"]
print(x)
y = diccionario.get("Marca")
print(y)
#Se pueden cambiar los datos de un diccionario apuntando a su indice.
diccionario["Año"] = 1968
print(diccionario)
#Tambien se puede acceder al diccionario imprimiendo cada uno de sus elementos. Hay varias formas de hacerlo.
#Aqui solamente imprimira los indices del diccionario
for x in diccionario:
print(x)
#Aqui imprimira los valores de los elementos indexados
for x in diccionario:
print(diccionario[x])
#Aqui imprimira los valores de los elementos indexados utilizando la funcion values()
for x in diccionario.values():
print(x)
#items() permite imprimir tanto el indice como el valor almacenado. Es importante definir dos variables para este FOR.
for x, y in diccionario.items():
print(x, y)
#Se puede validar si existe algun indice dentro del diccionario.
if "Modelo" in diccionario:
print("Si hay modelo")
#Se puede conocer la longitud de un diccionario.
print(len(diccionario))
#Se pueden insertar datos adicionales junto con su indice en el diccionario.
diccionario["Color"] = "Negro"
print(diccionario)
#Se pueden remover elementos de un diccionario utilizando pop() y haciendo referencia al indice.
diccionario.pop("Color")
print(diccionario)
#Tambien se puede remover el ultimo dato insertado con la funcion popitem()
diccionario["Puertas"] = 4
print(diccionario)
diccionario.popitem()
print(diccionario)
#Se puede utilizar el comando del para borrar un indice en particular o el diccionario completo.
del diccionario["Año"]
print(diccionario)
diccionario.clear() #clear() limpia el diccionario sin eliminarlo.
print(diccionario)
del diccionario
#Para poder copiar un diccionario es necesario utilizar la funcion copy()
diccionario = {
"Marca" : "Ford",
"Modelo" : "Mustang",
"Año" : 1996
}
diccionario2 = diccionario.copy()
diccionario2["Modelo"] = "Figo"
print(diccionario)
print(diccionario2)
#Se puede utilizar el constructor dict() para generar nuevos diccionarios desde una variable, o bien para realizar una copia de las mismas
primedict = dict(marca= "Ford", modelo= "Mustang", año= 1996)
primedict2 = dict(primedict)
print(primedict)
print(primedict2)
| false |
e87424f60815104d2e6871f2d46031c14bfa0db7 | charlesmtz1/Python | /W3/008_Listas.py | 2,010 | 4.59375 | 5 | #Las listas son colecciones de datos que es ordenada y puede ser cambiado alguno de sus elementos. se declaran entre corchetes.
lista = ["Dia", "Umi", "Yoshiko"]
print(lista)
print(lista[1])
#Se puede modificar los elementos de una lista
lista[2] = "Cebollita"
print(lista)
#Se puede recorrer una lista con la instruccion FOR
for x in lista:
print(x)
#Se puede hacer una validacion de elementos dentro de una lista
if "Dia" in lista:
print("Si esta en la lista!")
#Se pueden utilizar funciones para cadenas en las listas
print(len(lista))
#Se pueden agregar elementos adicionales a la lista con la funcion append(). Append coloca el elemento nuevo en la ultima posicion
lista.append("Ruby")
print(lista)
#Con la funcion insert() podemos colocar el nuevo elemento en la posicion que definamos.
lista.insert(0, "Rei")
print(lista)
#Se pueden remover elementos de la lista con la funcion remove()
lista.remove("Ruby")
print(lista)
#Con la funcion pop() se elimina el ultimo elemento de la lista.
lista.pop()
print(lista)
#La instruccion del puede eliminar un elemento en la posicion que definamos. Tambien se puede borrar la lista completa.
del lista[2]
print(lista)
del lista
#La funcion clear() limpia la lista de registros, pero sin destruir la variable
lista = ["Dia", "Umi", "Yoshiko"]
print(lista)
lista.clear()
print(lista)
#Las listas tambien se pueden copiar, sin embargo no se puede realizar una asignacion de este tipo: lista1 = lista2
#Al hacer una asignacion de este tipo, lo que genera es solo una referencia, mas no una copia de la variable.
#Para realizar una copia de una lista a una nueva variable, se ocupa la funcion copy()
lista = ["Dia", "Umi", "Yoshiko"]
mylist = lista.copy()
print(mylist)
#Se puede utilizar el constructor list() para generar nuevas listas desde una variable, o bien para realizar una copia de las mismas
primelist = list(("Rei", "Dia", "Mizuki")) #INCLUYE DOBLES PARENTESIS!!!
primelist2 = list(primelist)
print(primelist)
print(primelist2)
| false |
3e5a6011a1e7d957e44a51b4b781e5f837daf00e | charlesmtz1/Python | /W3/010_Sets.py | 2,268 | 4.28125 | 4 | #Los sets son colecciones de datos que no tienen un orden definido ni un indice. se declaran entre llaves.
myset = {"Rei", "Dia", "Umi"}
print(myset) #Los elementos seran impresos de forma aleatoria, debido a que un set no cuenta con un orden definido.
#LOS SETS NO PUEDE SER ACCEDIDO A SUS ELEMENTOS DE FORMA DEFINIDA. Es decir, no se puede utilizar esta declaracion:
# print(myset[0])
#Debido a que los elementos de un set no tienen indice.
#Sin embargo, se puede acceder a los elementos de forma generica o se puede validar si un elemento se encuentra dentro de un set.
for x in myset:
print(x) #Los elementos seran impresos de forma aleatoria
if "Rei" in myset:
print("♥")
#LOS SETS NO PERMITEN AGREGAR ELEMENTOS DE FORMA INDEXADA. Estas instrucciones no estan permitidas:
# myset.append("Ruby")
# myset.insert(0, "Ruby")
#Sin embargo se pueden agregar elementos con la funcion add()
myset.add("Yoshiko")
print(myset)
#Tambien se puede incluir multiples elementos al set con la funcion update()
myset.update(["Ruby", "Haruna-Chan"]) #IMPORTANTE! La funcion update() lleva corchetes dentro de los parentesis para agregar los elementos al set.
print(myset)
#Se puede obtener la longitud de un set con la funcion len()
print(len(myset))
#Se pueden remover elementos de un set usando remove() o discard().
#remove() se recomienda usar cuando conocemos el elemento que queremos eliminar del set
#discard() se recomienda cuando no se tiene certeza que el elemento este dentro del set.
myset.remove("Ruby")
print(myset)
myset.discard("Shiho")
print(myset)
#Tambien se puede utilizar la funcion pop(), sin embargo pop() elimina el ultimo elemento del set, pero debido a que es aleatorio, no sabremos con certeza
#el elemento eliminado. Se puede conocer dicho elemento si se almacena en una variable durante su ejecucion.
pop = myset.pop()
print(pop)
print(myset)
#clear() deja vacio el set, mientras que el comando del lo elimina completamente.
myset.clear()
print(myset)
del myset
#Se puede utilizar el constructor set() para generar nuevos sets desde una variable, o bien para realizar una copia de las mismas
primeset = set(("Rei", "Dia", "Mizuki")) #INCLUYE DOBLES PARENTESIS!!!
primeset2 = set(primeset)
print(primeset)
print(primeset2)
| false |
cd1aac3386e78c28e4eb3610a5a7dc0a0adf5bdb | charlesmtz1/Python | /Alf/Ejercicio8.py | 523 | 4.1875 | 4 | #Ejercicio 8
#Escribir un programa que pida al usuario dos números enteros y muestre por pantalla la <n> entre <m> da un cociente <c> y un resto <r> donde <n> y <m> son
# los números introducidos por el usuario, y <c> y <r> son el cociente y el resto de la división entera respectivamente.
num_1 = int(input("Escribe un numero> "))
num_2 = int(input("Escribe otro numero> "))
cociente = num_1 // num_2
resto = num_1 % num_2
print(f"La division de {num_1} entre {num_2} da un cociente {cociente} y un resto {resto}")
| false |
495ef05e5197836a7ae5f8e2d7c33c34b627dcb0 | charlesmtz1/Python | /Ejercicios/Ejercicio2.py | 793 | 4.125 | 4 | #Ejercicio 2
#Definir una función max_de_tres(), que tome tres números como argumentos y devuelva el mayor de ellos.
def max_of_three(number_list):
max = 0
for number in number_list:
if number > max:
max = number
return max
print("----------------------------")
print("------Number Validator------")
print("----------------------------\n")
number_list = list()
sets = 1
while sets <= 3:
try:
number_list.append(int(input(f"Set number {sets}: ")))
except ValueError:
print("Invalid character!")
else:
sets += 1
print("\nVerifing...")
print(f"The biggest number is: {max_of_three(number_list)}")
print("\n----------------------------")
print("----------Finished----------")
print("----------------------------") | false |
ff05e1b37eca1d2ed7f0e7d7cf1b75aef6a3ea92 | charlesmtz1/Python | /W3/005_Casting.py | 1,036 | 4.59375 | 5 | #A partir de las funciones de tipo de variable, se pueden realizar conversiones, de acuerdo a las posibilidades de cada
#tipo de variable.
#Al hacer conversiones a enteros, se puede hacer con numeros directos en la funcion o por medio de variables.
#Si se quiere convertir una cadena a entero, es importante que la cadena solo incluya numeros, de lo contrario marcara error.
a = int(2)
b = int(3.5)
c = int("7")
print(a, b, c)
#Al hacer conversiones a flotantes, se puede hacer con numeros directos en la funcion o por medio de variables.
#Si se quiere convertir una cadena a flotante, es importante que la cadena solo incluya numeros junto a su decimal,
#de lo contrario marcara error.
d = float(4)
e = float(7.8)
f = float("10")
g = float("15.2")
print(d, e ,f, g)
#Al hacer conversiones a cadena, se puede hacer con numeros directos en la funcion o por medio de variables.
#Las cadenas no cuentan con restriccion de conversion.
h = str(1)
i = str(6.3)
j = str("9")
print(h, i ,j)
print(type(h))
print(type(i))
print(type(j))
| false |
4ea5a220d20686e2730e9a17f41a22d8588a9a94 | AMSYNC/Codecademy | /piglatin.py | 400 | 4.125 | 4 | def my_function():
print "Hello you! Let's play a game of Pig Latin!"
complete = 0
while complete != 1:
word = raw_input("Enter an English word: ")
if word.isalpha() == True:
word = word + word[0]
word_final = word[1:]
print(word_final)
complete = 1
else:
print("That is not a valid word!")
my_function() | true |
3142c11becde43e0167df2aefee19b043184c7c8 | kuralayenes/Examples | /Basic_Examples/Area_Triangle_Display.py | 239 | 4.15625 | 4 |
num1 = float(input("Enter number1 : "))
num2 = float(input("Enter number2 : "))
num3 = float(input("Enter number3 : "))
s = (num1+num2+num3)/2
area = (s*(s-num1)*(s-num2)*(s-num3))**0.5
print("The area of the triangle is %0.2f" %area) | false |
e4cceb851044d107d32d2837b5a58fbf409cbeb4 | marydCodes/jetbrains_dailyminis | /moveLeo.py | 490 | 4.25 | 4 | class Turtle:
def __init__(self, x, y):
# the initial coordinates of the turtle
self.x = x
self.y = y
def move_up(self, n):
self.y += n
def move_down(self, n):
self.y = 0 if n > self.y else self.y - n
def move_right(self, n):
self.x += n
def move_left(self, n):
self.x = 0 if n > self.x else self.x - n
leo = Turtle(1, 1)
leo.move_up(7)
leo.move_left(5)
leo.move_down(4)
leo.move_right(6)
print(leo.x, leo.y) | false |
294c77b7a4dc222a996d8300c1c099d67e752309 | DVLdevil/projectEuler | /problems1to20.py | 1,572 | 4.21875 | 4 |
def p1():
description = "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."
print(description)
sum = 0
# method 1
for i in range(1,1000):
if(i%3==0 or i%5==0):
sum += i
print("\nanswer is " + str(sum))
def p2():
description = "Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: \n\n\t1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\nBy considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."
print(description)
sum = 0
# method 1
n1 = 1
n2 = 2
max = 4000000
while(n2 < max):
if n2%2 ==0:
sum += n2
temp = n1 + n2
n1 = n2
n2 = temp
print("\nanswer is " + str(sum))
def isPalindrome(number):
front = str(number)[0:len(str(number))/2]
back = "".join(reversed(str(number)[len(str(number))/2:]))
print(front)
print(back)
def p4():
description = "A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. \nFind the largest palindrome made from the product of two 3-digit numbers."
n1 = n2 = 999
product = n1*n2
max = 1
if(isPalindrome(product) and product > max):
max = product
| true |
dc4a27538f2f5bc999d3accc9c268ce3be9776d4 | mitchellflax/lps_grading | /ps6/jenny_tm.py | 2,275 | 4.59375 | 5 | #this creates a class named Player
class Player(object):
#this creates a function called __init__ and it has the parameters self, player, age, and goals and you set the 1,2,and 3rd parameters to self
def __init__(self, player, age, goals):
self.player = player
self.age = age
self.goals = goals
#the getStats fucntion stores the information of the player like their name, age, and goals
def getStats(self):
summary = "Player: " + self.player + "\n"
summary = summary + "Age: " + self.age + "\n"
summary = summary + "Goals: " + self.goals + "\n"
return summary
#the getGoals function returns the goals the player has score
def getGoals(self):
return self.goals
#myPlayers is an empty list that the user can add players later on
myPlayers = []
#used to create a while statement later on
sport = "soccer"
#the while statement is used so that the user can see the options they can choose
while sport == "soccer":
print("What would you like to do? Enter the number of your choice and press enter.")
print("(0) Leave the program and delete the players")
print("(1) Add a player")
print("(2) Print all players")
print("(3) Print average number of goals for all payers")
#response is equal to raw_input to let the user decide what option they want to choose
response = int(raw_input())
#if the user chooses 1 it will ask the the player's info
if response == 0:
sport == "sitting"
if response == 1:
print("Enter your player's name and press enter")
playerName = raw_input()
print("Enter age of the player")
playerAge = raw_input()
print("How many goals have they scored this season?")
playerGoals = raw_input()
my_Player = Player(playerName, playerAge, playerGoals)
myPlayers.append(my_Player)
print("Player now added to the team!")
#this will run if the user chooses choice 2 and it will display the players by using the getStats method
elif response == 2:
print("Here's a list of the players")
for p in myPlayers:
print(p.getStats())
#this will print if the user chooses choice 3 and it will print the average number of goals each player made
elif response == 3:
count = 1
number = 1
for l in myPlayers:
count = count + int(l.getGoals())
number = number + 1
print(count / number)
| true |
69635e9ac7bb4992f96a760f4cfc9ca739e2f118 | Alexasto12/Projectos-Python-3.9 | /Preparo_Colacao.py | 546 | 4.15625 | 4 | print("Voy a la cocina")
print("Abro la nevera")
hay_leche= input("¿Hay leche? (S/N) ")
hay_Colacao=input("¿Hay Colacao(S/N)")
if hay_leche!= "S" or hay_Colacao!="S":
print("Voy al super a comprar ")
if hay_leche!= "S":
print("Compro leche")
print("Te sirves en un vaso")
if hay_Colacao!= "S":
print("Compro Colacao")
hay_Colacao="S"
if hay_leche== "S":
print ("Te sirves la leche en un vaso")
if hay_Colacao== "S":
print("Abres el Colacao y te pones 3 cucharadas")
| false |
bff6b66e1cf40896e87082c7be150589593c6cea | iLegendJo/GClegend | /cptr3_pe_ex12.py | 1,597 | 4.125 | 4 | '''
Write a program that asks the user to enter the number of packages purchased.
The program should then display the amount of the discount(if any) and the total
amount of the purchase after the discount.
'''
quantity = int(input(f"Please enter number of packages purchased: "))
retail_price = 99.00
total_retail_price = quantity * retail_price
if quantity >=10 and quantity <= 19:
discount = retail_price * .10 * quantity
total_discount = total_retail_price - discount
print(f"Your discount is 10% savings of {discount} totalPrice : {total_retail_price} purchase after the discount:{total_discount}")
elif quantity >=20 and quantity <=49:
discount = retail_price * .20 * quantity
total_discount = total_retail_price - discount
print(f"Your discount is 20% savings of {discount} totalPrice : {total_retail_price} purchase after the discount:{total_discount}")
elif quantity >= 50 and quantity <= 99:
discount = retail_price * .30 * quantity
total_discount = total_retail_price - discount
print(f"Your discount is 30% savings of {discount} totalPrice : {total_retail_price} purchase after the discount:{total_discount}")
elif quantity >= 100:
discount = retail_price * .40 * quantity
total_discount = total_retail_price - discount
print(f"Your discount is 40% savings of {discount} totalPrice : {total_retail_price} purchase after the discount:{total_discount}")
elif quantity <=10:
print(f" Your discount is 0% savings of {quantity} totalPrice : {total_retail_price} purchase therefore no discount:")
| true |
e8e230603c01f905f0e99dd7615316f67cba454d | iLegendJo/GClegend | /chp8_pe.ex5.py | 483 | 4.15625 | 4 |
telephone_characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
telephone_numbers = "22233344455566677778889999"
tele_numbers = input("Please enter a phone number: ").upper()
converted_numbers = ""
for phonenumber in tele_numbers:
if phonenumber.isalpha():
found = telephone_characters.find(phonenumber)
letter = telephone_numbers[found]
converted_numbers += letter
else:
converted_numbers += phonenumber
print(converted_numbers)
| true |
1772a0032f9cbd9abf61ff2cf6b76ba7a7694aa9 | iLegendJo/GClegend | /cptr3_pe_ex9.py | 1,353 | 4.15625 | 4 | ''' • PE - Exercise 9
Roulette Wheel Colors On a roulette wheel, the pockets are numbered from 0 to 36. The colors of the pockets are as follows:
Pocket 0 is green
For pockets 1 through 10, the odd-numbered pockets are red
and the even-numbered pockets are black.
For pockets 11 through 18, the odd-numbered pockets are
black and the even-numbered pockets are red.
For pockets 19 through 28, the odd-numbered pockets are red
and the even-numbered pockets are black.
For pockets 29 through 36, the odd-numbered pockets are
black and the even-numbered pockets are red.
'''
msg = "is invalid and outside the range of 0 through 36, please enter number between 0 through 36 "
roulette = { 0:"Green",1:"Red",2:"Black",3:"Red",4:"Black",5:"Red",
6:"Black",7:"Red",8:"Black",9:"Red",10:"Black",11:"Black",
12:"Red",13:"Black",14:"Red",15:"Black",16:"Red",17:"Black",
18:"Red",19:"Red",20:"Black",21:"Red", 22:"Black",23:"Red",
24:"Black",25:"Red",26:"Black",27:"Red",28:"Black",29:"Black",
30:"Red",31:"Black", 32:"Red",33:"Black",34:"Red",35:"Black",36:"Red"}
pocket = int(input(f"Please entera pocket number: "))
#roulette[pocket]
if pocket <= 36 and pocket >=0:
print(f"Pocket {pocket} is {roulette[pocket]} ")
else:
print(f"Pocket {pocket} is {msg} ") | true |
9da8fef19b44ab060f2b0a0948c5f9f1695abf96 | wuwutao/wwt_test01 | /class.py | 2,501 | 4.15625 | 4 | """
#版本一
class GirlFriend():
#因为每个人初始化她的女朋友的属性肯定是不一样的,自定义
def __init__(self):
self.sex="女"
self.high="170cm"
self.weight="55kg"
self.age="18"
def jineng(self,num):
print("身高为"+self.high+"体重为:"+self.weight+"女盆友要开始她的才艺了:")
if(num==1):
print("i can fly")
elif(num==2):
print("i can sing")
else:
print("i can sleep")
def chuyi(self):
print("i can eat too much")
def work(self):
print("i can take car")
#对自己女朋友的属于的初始化
zhangsan=GirlFriend()
zhangsan.work()
zhangsan.jineng(1)
#版本二
class GirlFriend():
#因为每个人初始化她的女朋友的属性肯定是不一样的,自定义
def __init__(self,sex,high,weight,age):
self.sex=sex
self.high=high
self.weight=weight
self.age=age
def jineng(self,num):
print("身高为"+self.high+"体重为:"+self.weight+"女盆友要开始她的才艺了:")
if(num==1):
print("i can fly")
elif(num==2):
print("i can sing")
else:
print("i can sleep")
def chuyi(self):
print("i can eat too much")
def work(self):
print("i can take car")
#对自己女朋友的属于的初始化,控制属性的变化
zhangsan=GirlFriend("男","170","75kg","48")
zhangsan.work()
zhangsan.jineng(1)
print(zhangsan.sex)
"""
#版本三
class GirlFriend():
#因为每个人初始化她的女朋友的属性肯定是不一样的,自定义
def __init__(self,sex,high,weight,age):
self.sex=sex
self.high=high
self.weight=weight
self.age=age
def jineng(self,num):
print("身高为"+self.high+"体重为:"+self.weight+"女盆友要开始她的才艺了:")
if(num==1):
print("i can fly")
elif(num==2):
print("i can sing")
else:
print("i can sleep")
def chuyi(self):
print("i can eat too much")
def work(self):
print("i can take car")
#继承:
#子类:Nvpengyou
#父类:GirlFriend
class Nvpengyou(GirlFriend):
def chuyi(self):
print("我的厨艺天下无敌。。。")
#object:祖宗类
#__init__ ,就是继承object类中的一个方法
zhansan = Nvpengyou("女","168cm","50kg","18")
zhansan.chuyi() | false |
7005fbd66af9e892aaa3f70ffc7f1dc70f378f13 | tufanggongcheng/MIT_OCW-6.0001-ProblemSet-Solutions | /ps4/ps4a.py | 2,127 | 4.375 | 4 | # Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
sequence_list = list(sequence)
if len(sequence) == 0:
print('empty sequence')
if len(sequence) == 1:
return sequence_list
if len(sequence_list) > 1:
sequence0 = ''.join(sequence_list[0])
sequence_leftover_list = sequence_list[1:len(sequence_list)]
sequence_leftover = ''.join(sequence_leftover_list)
last = get_permutations(sequence_leftover)
final_list = []
for i in range(len(last)):
list_new = []
for j in range(len(sequence)):
list_new.append (last[i][0:j] + sequence0 + last[i][j:len(last[i])])
final_list += list_new
return final_list
if __name__ == '__main__':
# #EXAMPLE
# example_input = 'abc'
# print('Input:', example_input)
# print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
# print('Actual Output:', get_permutations(example_input))
# # Put three example test cases here (for your sanity, limit your inputs
# to be three characters or fewer as you will have n! permutations for a
# sequence of length n)
example = {'a':['a'],'ab':['ab','ba'], 'abc':['abc', 'bac', 'bca', 'acb', 'cab', 'cba']}
for example_input in example.keys():
print('Input:', example_input)
print('Expected Output:', example[example_input])
print('Actual Output:', get_permutations(example_input))
| true |
a853a9fb1103bb2cadd987987ecf34980e1698c0 | Athenian-ComputerScience-Fall2020/guessing-game-21ccronk | /game1.py | 1,803 | 4.25 | 4 | # I got help from Megan on this one
import random
def guessing_game():
def justright():
print("You guessed " + str(y) + ". That is correct!")
def toolow():
print("You guessed " + str(y) + ". That is too low!")
def toohigh():
print("You guessed " + str(y) + ". That is too high!")
def outofrange():
print("You guessed " + str(y) + ". That is out of the range!")
print("Hello! Welcome to guessing game! You are about to try to guess a random generated number between your range of choice. What would you like your range to be?")
r = input("Enter the start of your range: ")
e = input("Enter the end of your range: ")
print("Your range is (" + r + ", " + e + ")")
gues = int(input("How many guesses would you like: "))
gues1 = gues - 1
x = random.randint(int(r),int(e))
try:
for count in range(0, gues):
y = (input("You have " + str(gues) + " tires to guess the correct number between " + r + " and " + e + " or type 'q' to quit: "))
if y == "q":
quit
else:
y = int(y)
if y == x:
justright()
break
elif y > x:
toohigh()
if y > int(e):
outofrange()
elif y < x:
toolow()
if y < (int(r)):
outofrange()
if count == gues1:
print("You are out of tries! " + "The correct number was " + str(x) + ". Thanks for playing!!!")
except:
print("Please enter a number")
while True:
guessing_game()
print("Do you want to play again? (yes/no) ")
play_again = input()
if play_again == 'no':
break | true |
44c055e52bd1f0dc97c964f3b5b07c3b41e6ff78 | salma71/interview_practice_1 | /code_challenge/palindrome_integer.py | 1,596 | 4.375 | 4 | '''
A palindromic string is one which reads the same forwards and backwards, e.g., "redivider".
In this problem, you are to write a program which determines if the decimal representation of an integer is a palindromic string.
For example, your program should return true for the inputs 0, 1", 7, 17, 727, 333, a: nd21.4744741.2,
and false for the inputs -'1, 12, 100, and 2147483647.
Write a Program that takes an integer and determines if that integer's representation as a decimal string is a palindrome.
'''
def palindrome_int(n):
'''
>>> palindrome_int(1)
True
>>> palindrome_int(727)
True
>>> palindrome_int(333)
True
>>> palindrome_int(100)
False
'''
# using the method we did before
# import reverse_digit
# while n > 0:
# if n == reverse_digit.reverse_digit(n):
# return 'true'
# else:
# return 'false'
# return 'false'
# using the log10 method
# get # of digits in n by taking the (log n) + 1
# leading = n mod 10
# tail = n/10^(n -1)
# if leading == tail -> true
# iterate and remove lead, tail from inner number
# else false
# complexity O(n), space O(1)
import math
num_digit = math.floor(math.log10(n)) + 1
tail = 10**(num_digit - 1)
# for i in range(num_digit // 2):
if n // tail != n % 10:
return False
# if they are equal -> go deeper
# remove lead
n //= 10
# remove tail
n %= 10**(num_digit - 1)
# decrement by two digits
tail //= 100
return True
| true |
78966ddbb780a600a7d46ab577322e3df4c8d7cb | Venki152/Python | /CarClassFile.py | 2,862 | 4.15625 | 4 | #class programs for OOPs
class Car(): # define Car super class
def __init__(self, efficiency):
self._efficiency = efficiency
self._fuel = 0 #class variables
self._fuelcheck = 0
path = "C:\\Users\\Venki\\Desktop\\Venkat\\Python\\Project 2\\"
f = open(path + 'FuelEffic.txt' , "r") #open the file in read mode
lines = f.readlines() #read lines
print("Miles per gallon:",lines[0].split()[3]) #print the miles in line
print("Tank Size (in gallons): ",lines[1][len(lines[1])-2:])
self._milage = int(lines[0].split()[3]) # assigns details to class variables
self._tankSize = int(lines[1][len(lines[1])-2:])
self._totaldistance = self._milage * self._tankSize
print("Maximum Distance %0.2f miles"%self._totaldistance) #max distance the car can travel with full tank
f.close #close the file
def addGas(self,gas):
self._fuelcheck=self._fuel + (gas) #temporary variable
if(self._fuelcheck>self._tankSize): #check if fuel to be added more than the tank size
#print("Tank full, will be adding", (self._fuel + gas- self._tankSize) )
self._addnew = gas - (self._fuelcheck- self._tankSize) #calculate gas that can be added
print("Tank would be full with", self._addnew, 'gallons')
self._fuel= (self._fuel + self._addnew) #new gas level
return self._addnew
else:
self._fuel=self._fuel + (gas) #add the gas to tank
return gas
#print("Total fuel there", self._fuel)
def drive(self,distance):
self._totaldistance = (self._milage*self._fuel) #updated distance based on updated gas level
if self._fuel == 0: #if tank empty return distance tavelled as zero
print("Tank empty")
return self._totaldistance
elif self._fuel >0:
if distance > self._totaldistance:
#print("Can drive only miles",self._totaldistance)
self._fuel = (self._totaldistance- self._totaldistance)/self._efficiency #updated fuel level
self._newdist = self._totaldistance
self._totaldistance = (self._milage*self._fuel) #new distance based on updated gas level
return self._newdist # return distance the car can travel
else:
self._fuel = (self._totaldistance-float(distance))/self._efficiency #updated fuel level
#print("New tank size", self._fuel)
self._totaldistance = (self._milage*self._fuel) #new distance based on updated gas level
#print(self._totaldistance)
return distance #distance can travelled
def getfuellevel(self):
return self._fuel #return gas level of car
| true |
c6e56cc97a212c65a0e06b822a8a8c4bd90ffe79 | victorlifan/python-scripts | /LPTHW/ex24.py | 1,467 | 4.125 | 4 | print("Let's parctice everything.")
print('You\'d need to know\' about escapes with \\ that do:')
print('\n newlines and \t tabs.')
poem = """
\tThe lovly world
with logic so frimly planted
cannot discern \nthe needs of love
nor comprehend passion form intuition
and requires an explanation
\n\t\twhere there is none.
"""
x = "-"
print(x*14)
print(poem)
print(x*14)
five = 10 - 2 + 3 - 6
print(f"This should be five: {five}")
# call function "secret_formula", add arguement "strated"
def secret_formula(started):
# equations
jelly_beans = started *500
jars = jelly_beans / 1000
crates = jars / 1000
# return values of jelly_beans, jars, crates
return jelly_beans, jars, crates
# assign value to variable "start_point"
start_point = 10000
# run function "secret_formula" with value 10000, assign return value to variable bean etc.
beans, jars, crates = secret_formula(start_point)
# remember that this is another way to format a string
print("With a starting point of : {}".format(start_point))
# it's just like with an f"" string
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
# assign value 1000 to variable "start_point"
start_point = start_point / 10
print("We can also do that this way:")
# assign function secret_formula to a valable"formula"
formula = secret_formula(start_point)
# this is an easy way to apply a list to a format starting
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
| true |
7118447f29f547b4ce46cf53ccf5ba9235e3d07b | victorlifan/python-scripts | /LPTHW/ex30.py | 901 | 4.40625 | 4 | people = 2
cars = 1
trucks = 1
# add "if" statement, add arguement cars > people
if cars > people:
# print meg if the arguement is true
print("We should take the cars.")
# "elif" statement
elif cars < people:
# print meg if arguement is true
print("We should not take the cars.")
# "else" statement
else:
# print msg if "elif" is not true
print("We can't decide.")
# add "if" statement, arguement "truck > cars"
if trucks > cars:
# print msg if arguement is true
print("That's too many trucks.")
# add "elif" statement, arguement "trucks < cars"
elif trucks < cars:
# print msg if arguement is true
print("Maybe we could take to trucks.")
# add "else" statement
else:
# print msg if "elif" is not true
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay gome then.")
| true |
d20d7d3c1de19153fa2d7a273cca863deb3e943f | vidyesh95/FactorialOfNumberPython | /main.py | 282 | 4.3125 | 4 | # Python program to find factorial of given number using recursive method.
def factorial(n):
if n == 1 or n == 0:
return 1
else:
return n * factorial(n - 1)
number = input("Enter the number : ")
print("Factorial of", number, "is", factorial(int(number)))
| true |
28635557fe0b476912b09904e4485e2e77cecef5 | learningCodings/learningPython | /conditions.py | 275 | 4.3125 | 4 | #conditions if elif else
print("Working Of 'if else'")
#If I want To Take input as number then I've to specify before input
n = float(input("Enter Number: "))
if n > 0:
print(f"{n} Is Positive")
elif n < 0:
print(f"{n} Is Negative")
else:
print(f"{n} Is Zero") | false |
6a91ff16dce205650540f613ee8fa9b0bf3ee195 | MattheusOliveiraBatista/Python3_Mundo01_CursoEmVideo | /ExerciciosPython/Ex005_Antecessor_E_Sucessor.py | 315 | 4.1875 | 4 | '''
Faça um programa que leia um número Inteiro e mostre na tela o seu sucessor e seu antecessor.
'''
numero = float(input('Digite um numero: '))
#Antecessor
ant = numero - 1
#Sucessor
suc = numero + 1
print('O antecessor e o sucessor de {} são {} e {}, respectivamente'.format(numero, ant,suc)) | false |
a7b3cd10c8afacf022de29988ab40fd384b5ff85 | MattheusOliveiraBatista/Python3_Mundo01_CursoEmVideo | /ExerciciosPython/Ex022_Analisador_De_Textos.py | 713 | 4.28125 | 4 | '''
Crie um programa que leia o nome completo de uma pessoa e mostre:
– O nome com todas as letras maiúsculas e minúsculas.
– Quantas letras ao todo (sem considerar espaços).
– Quantas letras tem o primeiro nome.
'''
texto = str(input('Digite seu nome completo: ')).strip()
print('Analisando seu nome...')
print('Seu nome em maiúsculas é {}'.format(texto.upper()))
print('Seu nome em minúsculas é {} '.format(texto.lower()))
print('Seu nome tem ao todo {} letras'.format(len(texto) - texto.count(' ')))
#print('Seu primeiro nome tem {} letras'.format(texto.find(' ')))
separa = texto.split()
print('Seu primeiro nome é {} e ele tem {} letras'.format(separa[0],len(separa[0])))
| false |
8d4dfe96240977f51abd900b7f1e7cd8646e8e2f | MattheusOliveiraBatista/Python3_Mundo01_CursoEmVideo | /ExerciciosPython/Ex016_Quebrando_Um_Numero.py | 347 | 4.125 | 4 | '''
Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção Inteira.
'''
import math
#from math import trunc
numero = float(input('Digite um numero não inteiro: '))
numeroInteiro = math.trunc(numero)
print('O valor digitado foi {} e a sua porção inteir é {}'.format(numero, numeroInteiro) ) | false |
07ceb7369282f5b4a27ed7a3cc14c5990411f614 | MattheusOliveiraBatista/Python3_Mundo01_CursoEmVideo | /AulasPython/Aula08_Utilizando_Módulos_01.py | 756 | 4.46875 | 4 | ''''
Nessa aula, vamos aprender como utilizar módulos em Python utilizando os comandos import e from/import no Python.
Veja como carregar bibliotecas de funções e utilizar vários recursos adicionais nos seus programas
utilizando
'''
import math
#Importando apenas a função de raiz quadrada e floor
#from math import sqrt, floor
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
print('A raiz quadrada de {} é igual a {}'.format(num,raiz))
#Arredondando para cima
print('\nArredondando para cima - ceil \nA raiz quadrada de {} é igual a {}'.format(num,math.ceil((raiz))))
#Arredondando para baixo
print('\nArredondando para baixo - floor \nA raiz quadrada de {} é igual a {}'.format(num,math.floor((raiz))))
| false |
9fe9c637910186faa403d183e1f8b7fb7973813a | furixturi/CTCI | /04 trees and graphs/4.6 successor.py | 762 | 4.15625 | 4 | # Successor:
# Write an algorithm to find the "next" node (i.e., in-order successor) of
# a given node in a binary search tree. You may assume that each node has
# a link to its parent.
def findMin(tree):
curr = tree
while curr.left is not None:
curr = curr.left
return curr
def findNext(tree):
curr = tree
if curr.right is not None:
nextNode = findMin(curr.right)
else:
if curr.parent is None:
nextNode = None
else:
if curr == curr.parent.left:
nextNode = curr.parent
else:
nextNode = None
curr = curr.parent
while curr.parent is not None:
curr = curr.parent
if curr == curr.parent.left:
nextNode = curr.parent
break
return nextNode | true |
d974a02cc468e8ed63c7dc00510a9ab159df1a75 | furixturi/CTCI | /04 trees and graphs/4.9 bstSequences.py | 1,131 | 4.15625 | 4 | # BST Sequences:
# A binary search tree was created by traversing through an array from left
# to right and inserting each element. Given a binary search tree with distinct
# elements, print all possible arrays that could have led to this tree.
# EXAMPLE
# Input:
# Output: {2, 1, 3}, {2, 3, 1}
def allSequences(tree):
result = []
if tree is None:
result.append([])
return result
prefix = [tree.data]
leftSequences = allSequences(tree.left)
rightSequences = allSequences(tree.right)
for seqL in leftSequences:
for seqR in rightSequences:
weaved = []
weave(seqL, seqR, weaved, prefix)
result = result + weaved
return result
def weave(first, second, results, prefix):
if not first or not second:
result = prefix[:]
result = result + first
result = result + second
results.append(result)
prefix.append(first.pop(0))
weave(first, second, results, prefix)
first.insert(0, prefix.pop())
prefix.append(second.pop(0))
weave(first, second, results, prefix)
second.insert(0, prefix.pop()) | true |
49bfaddc98cc0d01410feef18d0552d93c6df098 | furixturi/CTCI | /01 arrays and strings/1.6 stringCompression.py | 987 | 4.375 | 4 | # String Compression:
# Implement a method to perform basic string compression using the counts
# of repeated characters. For example, the string aabcccccaaa would become
# a2b1c5a3. If the "compressed" string would not become smaller than the
# original string, your method should return
# the original string. You can assume the string has only uppercase and
# lowercase letters (a - z).
def stringCompression(string: str) -> str:
result_list = []
curr = None
count = 0
for i,c in enumerate(string):
if c != curr:
if count > 0:
result_list.append(str(count))
curr = c
count = 1
result_list.append(c)
else:
count += 1
if i == len(string) -1:
result_list.append(str(count))
if len(result_list) >= len(string):
result = string
else:
result = ''.join(result_list)
return result
print(stringCompression('aabcccccaaa')) # 'a2b1c5a3'
print(stringCompression('')) # ''
print(stringCompression('abc')) # 'abc' | true |
910f3dac8f9cd5d28859c418fd0162560f2367ef | furixturi/CTCI | /04 trees and graphs/4.4 checkBalanced.py | 1,231 | 4.25 | 4 | # Check Balanced:
# Implement a function to check if a binary tree is balanced.
# For the purposes of this question, a balanced tree is defined to be a tree such
# that the heights of the two subtrees of any node never differ by more
# than one.
class BinaryTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def addHeight(tree):
if tree.left is None and tree.right is None:
tree.height = 1
else:
if tree.left is not None:
tree.left = addHeight(tree.left)
if tree.right is not None:
tree.right = addHeight(tree.right)
leftHeight = 0 if tree.left is None else tree.left.height
rightHeight = 0 if tree.right is None else tree.right.height
tree.height = max(leftHeight, rightHeight) + 1
return tree
def isBalanced(tree):
tree = addHeight(tree)
nodes = [tree]
while len(nodes) > 0:
node = nodes.pop(0)
if node.left:
nodes.append(node.left)
if node.right:
nodes.append(node.right)
leftHeight = 0 if node.left is None else node.left.height
rightHeight = 0 if node.right is None else node.right.height
if leftHeight - rightHeight < -1 or leftHeight - rightHeight > 1:
return False
return True
| true |
036ba257200d3361a4e05c79037a687c4afca9af | akshatmawasthi/python | /range.py | 320 | 4.125 | 4 | #Try the exercises below
#Create a list of one thousand numbers
#Get the largest and smallest number from that list
#Create two lists, an even and odd one.
thousand = range(0,1000)
print(thousand[0])
print(thousand[-1])
for x in thousand:
if x % 2 == 0:
print("Even", x)
else:
print("Odd", x)
| true |
db3ef9663de26eebc9fcb17c1c429694ac82d071 | akshatmawasthi/python | /sort.py | 550 | 4.375 | 4 | print("First Example - Sorting a list")
x = [3,6,21,1,5,98,4,23,1,6]
x.sort()
print(x)
print("Second Example - Sorting strings")
words = ["Be","Car","Always","Door","Eat" ]
words.sort()
print(words)
print("Third Example - Reverse Sort")
x = [3,6,21,1,5,98,4,23,1,6]
x.sort()
x = list(reversed(x))
print(x)
#Given a list with pairs, sort on the first element
#x = [ (3,6),(4,7),(5,9),(8,4),(3,1)]
#Now sort on the second element
y = [ (3,6),(4,7),(5,9),(8,4),(3,1)]
print(sorted(y, key = lambda x:x[0]))
print(sorted(y, key = lambda x:x[1]))
| true |
0e4f2f14077534f193c09522a9d46375d7116ca2 | TEAMLAB-Lecture/text-processing-wjdgns7712 | /text_processing.py | 391 | 4.125 | 4 | def normalize(input_string):
normalized_string = ' '.join(input_string.lower().split())
return normalized_string
def no_vowels(input_string):
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
no_vowel_string = input_string
for i in no_vowel_string:
if i in vowels:
no_vowel_string = no_vowel_string.replace(i, '')
return no_vowel_string | false |
910441b24c613d6ccea79af70e92735b88377027 | bjtugb/bjtupsu | /course.py | 729 | 4.25 | 4 | course = 'Python for Beginners'
print(course.upper())
print(course.lower())
print(course)
course = 'Python for Beginners'
print(course.find('P'))
course = 'Python for Beginners'
print(course.find('O'))
course = 'Python for Beginners'
print(course.find('Beginners'))
course = 'Python for Beginners'
print(course.replace('Beginners', 'Absolute beginners'))
course = 'Python for Beginners'
print(course.replace('beginners', 'Absolute beginners'))
course = 'Python for Beginners'
print(course.replace('P', 'J'))
course = 'Python for Beginners'
print('Python' in course)
print('python' in course)
course = 'Python for Beginners'
len()
course.upper()
course.lower()
course.title()
course.find()
course.replace()
'...' in course | false |
3c5f0e79f0ec0c587928ba26a191af8a8311efbd | HectorLI36/python_the_hard_parts | /super_usage.py | 745 | 4.40625 | 4 | #实例一:
class A(object):
def __init__(self):
print("class ---- A ----")
class B(A):
def __init__(self):
print("class ---- B ----")
super(B, self).__init__()
class C(A):
def __init__(self):
print("class ---- C ----")
# print(f'printing {i}')
super(C, self).__init__()
#
# class D(B, C):
# def __init__(self):
# print("class ---- D ----")
# super(D, self).__init__()
#
#
# #实例二: 更改一下类D的super函数:
# class D(B, C):
# def __init__(self):
# print("class ---- D ----")
# super(B, self).__init__()
class D(B, C):
def __init__(self):
print("class ---- D ----")
super(D, self).__init__()
d = D()
pass | false |
e14ecd523a80afb7291021e414b8d95d461751b4 | Caffeine-addict7410/Pythonwork | /Ex22.py | 852 | 4.15625 | 4 | print()#prints the given function
""#
()#
{}#
print(f"")#
#Everything after the octothrope python will ignore allowing the programmer make comments
+#
=#
-#
/#
%#represent modulus can also used for formatting a string
print(""" """)#Prints the given funtions but the """ allows it to be used on mutiple lines until closed
n/#Escape sequences
\t#Escape sequences
\\#Escape sequences
end=' ')#
from#
sys#
import#
argv#
input()#
open()#
exit#
def#
(*argv)#
return# returns a value to its caller
if # let you make decisons in your python code
\' #Escape sequences
\" #Escape sequences
\a#Escape sequences
\b#Escape sequences
\f#Escape sequences
\n#Escape sequences
\N{name}#Escape sequences
\r #Escape sequences
\t#Escape sequences
\uxxxx#Escape sequences
\Uxxxxxxxx#Escape sequences
\v#Escape sequences
\ooo#Escape sequences
\xhh#Escape sequences
| true |
2f7ad2f8e2dd6224507b4522d51159771810daac | Rosenguyen4992/rosenguyen-fundamentals-c4e19 | /Session02/homework/Session02_Assignment04.py | 422 | 4.21875 | 4 | print("Hello!")
height = float(input("Please input your height in cm here:"))
weight = float(input("Please input your weight in kg here:"))
bmi = weight/(height/100)**2
if bmi < 16:
print ("You are Severely underweight >__<")
elif bmi < 18.5:
print ("You are Underweight:(")
elif bmi < 25:
print ("You are normal :)")
elif bmi < 30:
print ("You are overweight :(")
else:
print ("You are obese >___<")
| false |
264c46ec0afcb24734382c70f8cc9b1f00965013 | nhmishaq/Python-Assignments | /python_platform_assignments/bike.py | 750 | 4.21875 | 4 | class Bike(object):
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print "bike costs " + str(self.price)
print "the maximum speed is " + str(self.max_speed)
print "the total miles is " + str(self.miles)
def ride(self):
self.miles += 10
print "they see me rolling......" + str(self.miles)
def reverse(self):
self.miles -= 5
print "woah woah woah, we going backwards mamma! " + str(self.miles)
bike_one = Bike(100, 20, 50)
bike_two = Bike(500, 30, 0)
bike_three = Bike(1000, 40, 100)
print bike_one.displayInfo()
print bike_one.ride()
print bike_one.reverse() | true |
1b6c765a05f91d06ddecab2f5e661fc7f720dcb9 | theSeaOfMiss/dataStructure | /array/matrixAdd.py | 450 | 4.15625 | 4 | # 将两个矩阵相加
from array.displayMatrix import display
matrix1 = [[1, 3, 5], [7, 9, 11], [13, 15, 17]] # 声明二维数组
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
M = 3 # 行数
N = 3 # 列数
matrix3 = [[None] * N for row in range(M)] # 声明一个空数组
for i in range(M):
for j in range(N):
matrix3[i][j] = matrix1[i][j] + matrix2[i][j]
print('矩阵一加矩阵二得:')
display(matrix3)
| false |
8788552148d7e1fe1c39b44ec9743b2fb8b61abe | tyagian/Algorithms-and-Data-Structure | /leetcode/Algorithms/Easy/905-sort_array-py-parity/sort-array-by-parity.py | 743 | 4.25 | 4 | """
https://leetcode.com/problems/sort-array-by-parity/
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
"""
new_array = []
def input_array(input_value):
if len(input_value) == 0:
print ("No element in array")
else:
try:
for each_ele in input_value:
if int(each_element)%2 == 0:
new_array.insert()
except as e:
A = input_array([3,1,2,4]) | true |
23906fb83fcc1fffc9f39ee31c640d8bb3ad72e8 | tyagian/Algorithms-and-Data-Structure | /basic_algos/search/1-binary_search.py | 1,231 | 4.21875 | 4 | """
Note: Binary search expect sorted list
Eg-1 Locate card position
url: https://jovian.ai/aakashns/python-binary-search
Add possible edge cases:
The number query occurs somewhere in the middle of the list cards.
query is the first element in cards.
query is the last element in cards.
The list cards contains just one element, which is query.
The list cards does not contain number query.
The list cards is empty.
The list cards contains repeating numbers.
The number query occurs at more than one position in cards.
(can you think of any more variations?)
"""
def locate_card(cards, query):
low, high = 0, len(cards) - 1
mid = (low+high) // 2
mid_number = cards[mid]
while low <= high:
if mid_number == query:
return mid
elif mid_number < query:
low = mid + 1
elif mid_number > query:
high = mid - 1
return -1
"""
def output(cards, query):
output = locate_card(cards, query)
return output
"""
"""
test = {
'input': {
'cards': [13, 11, 10, 7, 4, 3, 1, 0],
'query': 7
},
'output': 3
}
locate_card(**test['input']) == test['output']
"""
cards = [1,4,6,7,11,17,19]
query = 7
l = locate_card(cards, query)
print (l) | true |
5b52bd2ee82c0a5540bd01fb0586ef25e4cf7516 | ANASTANSIA/PythonRepo | /04.py | 1,517 | 4.1875 | 4 | """
program that lets the user play Rock-Paper-Scissors against the computer and prints the winner
"""
from random import randint
playOptions=["Rock","Paper","Scissors"]
playerScores=0
ComputerScores=0
tie=0
player=False
while player == False:
for i in range(5):
player=""
while player == "":
player=input("Rock,Paper,Scissors?")
if player == "":
print("Invalid choice")
Computer=playOptions[randint(0,2)]
if Computer == player:
tie=tie+1
elif player=="Rock" :
if Computer == "Paper":
ComputerScores=ComputerScores+1
else:
playerScores+=1
elif player == "Paper":
if Computer == "Scissors":
ComputerScores=ComputerScores+1
else:
playerScores=playerScores +1
elif player=="Scissors":
if Computer == "Rock":
ComputerScores=ComputerScores+1
else:
playerScores=playerScores +1
player = False
computer= playOptions[randint(0,2)]
#checking the scores
if ComputerScores > playerScores:
print("Computer wins by",ComputerScores)
elif ComputerScores < playerScores:
print( " You win by ",playerScores)
elif playerScores == ComputerScores:
print( "A tie")
print(ComputerScores)
print(playerScores)
| true |
961ca0d0e97d571c147d3cecb90eefa48e2f6b79 | cesarschool/cesar-school-fp-lista-de-exercicios-03-CaioCordeiro | /questoes/questao_2.py | 1,061 | 4.375 | 4 | ## QUESTÃO 2 ##
#
# Escreva um programa para calcular a frequencia das palavras de uma entrada.
# A saída deve mostrar a frequencia depois de ordenar a chave alfanumericamente.
# Suponha que a seguinte entrada seja fornecida ao programa:
# New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
#
# Então, a saída deve ser:
# 2:2
# 3.:1
# 3?:1
# New:1
# Python:5
# Read:1
# and:1
# between:1
# choosing:1
# or:2
# to:1
##
##
# A sua resposta da questão deve ser desenvolvida dentro da função main()!!!
# Deve-se substituir o comado print existente pelo código da solução.
# Para a correta execução do programa, a estrutura atual deve ser mantida,
# substituindo apenas o comando print(questão...) existente.
##
def main():
sentenca = input('')
words = sentenca.split()
result = []
for i in words:
result.append("{}:{}".format(i,words.count(i)))
result = list(set(result))
result = sorted(result)
for i in result:
print(i)
if __name__ == '__main__':
main()
| false |
b6c12e89517c5e7b493de439cbe79b4bbf16f9c3 | gauravgidwani/hello-world | /Python/factorial calc.py | 217 | 4.25 | 4 | def find_factorial(n):
m = abs(int(n))
total = 1
while m > 0:
total = int(total) * int(m)
m -= 1
print str(n) + "! is " + str(total)
find_factorial(raw_input("Enter a number to find its factorial: ")) | false |
f3218c1451bc9f162c3a16eb17ac4a8e17704348 | YaniLozanov/Software-University | /Python/PyCharm/02.Simple Calculations/04. Concatenate Data.py | 347 | 4.125 | 4 | # Write a Python program that reads from the console name, surname, age, and city and prints a message from
# type: "You are (firstName), (lastName), (age) years old person from (town);"
first_name = input()
last_name = input()
age = int(input())
town = input()
print(f"You are {first_name} {last_name}, a {age}-years old person from {town}.")
| true |
41d581be5a6a74ddb2969672ab6dbf468e63d134 | YaniLozanov/Software-University | /Python/PyCharm/02.Simple Calculations/07. 2D Rectangle Area.py | 561 | 4.21875 | 4 | # Problem:
# A rectangle is given with the coordinates of two of its opposite angles (x1, y1) - (x2, y2).
# Calculate its area and perimeter.
# The input is read from the console.
# The numbers x1, y1, x2 and y2 are given in one order.
# The output is output to the console and must contain two rows with one number each - face and perimeter.
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
side_x = abs(x1 - x2)
side_y = abs(y1 - y2)
area = side_x * side_y
perimeter = side_x * 2 + side_y * 2
print(area)
print(perimeter)
| true |
70d6951591b04bc116d352f69ff231bddd6eb41c | YaniLozanov/Software-University | /Python/PyCharm/02.Simple Calculations/10. Radians to Degrees.py | 366 | 4.40625 | 4 | # Problem:
# Write a program that reads an angle in radians (rad) and converts it into degrees (deg).
# Look for an appropriate formula online.
# The number π in Python programs is available through math.pi.
# Round the result to the nearest integer using round ().
import math
radians = float(input())
degrees = round((radians * 180) / math.pi)
print(degrees)
| true |
f3f354a8aa13fff9f2e08c454b38fbd5e9642886 | YaniLozanov/Software-University | /Python/PyCharm/03.Logical checks/13.Area of Figures.py | 1,301 | 4.25 | 4 | # Problem:
# Write a program that introduces the dimensions of a geometric figure and calculates its face.
# The figures are four types: a square, a rectangle, a circle, and a triangle.
# On the first line of the input reads the shape of the figure (square, rectangle, circle or triangle).
# If the figure is a square, the next line reads one number - the length of its country.
# If the figure is a rectangle, the next one two lines read two numbers - the lengths of his sides. If the figure is a circle, the next line reads one number
# - the radius of the circle.
# If the figure is a triangle, the next two lines read two numbers - the length of the
# its side and the length of the height to it. Score to round to 3 digits after the decimal point.
import math
figure = input()
if figure == "square":
side = float(input())
area = side ** 2
print(format(area,'.3f'))
elif figure == "rectangle":
side_a = float(input())
side_b = float(input())
area = side_a * side_b
print(format(area,'.3f'))
elif figure == "circle":
radius = float(input())
area = radius ** 2 * math.pi
print(format(area,'.3f'))
elif figure == "triangle":
side = float(input())
height = float(input())
area = (side * height) / 2
print(format(area,'.3f'))
| true |
aa07b87e6bde154d07d2b5b43e64cee70f0df412 | YaniLozanov/Software-University | /Python/PyCharm/04.Complex Conditional Statements/08. Trade Comissions.py | 1,854 | 4.125 | 4 | # Problem:
# The company gives the following commissions to its merchants according to the town in which the sales volume works:
#
# City 0 ≤ s ≤ 500 500 < s ≤ 1,000 1,000 < s ≤ 10,000 s > 10 000
# Sofia 5% 7% 8% 12%
# Varna 4.5% 7.5% 10% 13%
# Plovdiv 5.5% 8% 12% 14.5%
# Write a console program that reads a city name and sales volume (decimal number) and calculates and
# returns the amount of merchant commission according to the above table.
# Score to be rounded by 2 digits after the decimal point.
# In the case of an invalid city or sales volume (negative number) prints "error".
city = input()
sales = float(input())
commission = 0
commission_Percent = 0
if city == "Sofia":
if 0 <= sales <= 500:
commission_Percent = 0.05
elif 500 <= sales <= 1000:
commission_Percent = 0.07
elif 1000 <= sales <= 10000:
commission_Percent = 0.08
elif sales > 10000:
commission_Percent = 0.12
elif city == "Varna":
if 0 <= sales <= 500:
commission_Percent = 0.045
elif 500 <= sales <= 1000:
commission_Percent = 0.075
elif 1000 <= sales <= 10000:
commission_Percent = 0.10
elif sales > 10000:
commission_Percent = 0.13
else:
print("error")
elif city == "Plovdiv":
if 0 <= sales <= 500:
commission_Percent = 0.055
elif 500 <= sales <= 1000:
commission_Percent = 0.08
elif 1000 <= sales <= 10000:
commission_Percent = 0.12
elif sales > 10000:
commission_Percent = 0.145
else:
print("error")
else:
print("error")
commission = sales * commission_Percent
print(float("{0:.2f}".format(commission)))
| true |
cdec89918f2e6e36815ea00f083e4e2f70412ce0 | Bryan-Cee/algorithms | /python/stacks.py | 2,420 | 4.28125 | 4 | import unittest
# You want to be able to access the largest element in a stack.
class Stack(object):
def __init__(self):
"""Initialize an empty stack"""
self.items = []
def push(self, item):
"""Push a new item onto the stack"""
self.items.append(item)
def pop(self):
"""Remove and return the last item"""
# If the stack is empty, return None
# (it would also be reasonable to throw an exception)
if not self.items:
return None
return self.items.pop()
def peek(self):
"""Return the last item without removing it"""
if not self.items:
return None
return self.items[-1]
# Use your Stack class to implement a new class MaxStack
# with a method get_max() that returns the largest element in
# the stack. get_max() should not remove the item.
class MaxStack(Stack):
# Implement the push, pop, and get_max methods
def __init__(self):
super().__init__()
def get_max(self):
if len(self.items) == 1:
return self.items[0]
else:
return max(self.items)
# Tests
class Test(unittest.TestCase):
def test_stack_usage(self):
max_stack = MaxStack()
max_stack.push(5)
actual = max_stack.get_max()
expected = 5
self.assertEqual(actual, expected)
max_stack.push(4)
max_stack.push(7)
max_stack.push(7)
max_stack.push(8)
actual = max_stack.get_max()
expected = 8
self.assertEqual(actual, expected)
actual = max_stack.pop()
expected = 8
self.assertEqual(actual, expected)
actual = max_stack.get_max()
expected = 7
self.assertEqual(actual, expected)
actual = max_stack.pop()
expected = 7
self.assertEqual(actual, expected)
actual = max_stack.get_max()
expected = 7
self.assertEqual(actual, expected)
actual = max_stack.pop()
expected = 7
self.assertEqual(actual, expected)
actual = max_stack.get_max()
expected = 5
self.assertEqual(actual, expected)
actual = max_stack.pop()
expected = 4
self.assertEqual(actual, expected)
actual = max_stack.get_max()
expected = 5
self.assertEqual(actual, expected)
unittest.main(verbosity=2)
| true |
60614b76de128a007df8753abe441dde9d6e8289 | kingkong521/twork1 | /fizzbuzz.py | 422 | 4.15625 | 4 | def fizzbuzz(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(str(i))
def fizzbuzz_comprehension(n):
fizzbuzz = ["Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i) for i in range(1, n+1)]
print('\n fizzbuzz comprehension way\n',fizzbuzz)
if __name__ == "__main__":
fizzbuzz(115) | false |
8fd3f31b4e92042dd71d05d24341c13bffe30333 | elreplicante/python-koans | /koans/triangle.py | 1,272 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' if no sides are equal
#
# The tests for this method can be found in
# about_triangle_project.py
# and
# about_triangle_project_2.py
#
EQUILATERAL_SIDES = 1
ISOSCELES_SIDES = 2
SCALENE_SIDES = 3
MINIMUM_SIDE_SIZE = 0
RULES = {
EQUILATERAL_SIDES: 'equilateral',
ISOSCELES_SIDES: 'isosceles',
SCALENE_SIDES: 'scalene'
}
def triangle(a, b, c):
sides = check_sides_length(a, b, c)
check_sides_sum(a, b, c)
return unique(sides)
def unique(sides):
unique_sides = len(set(sides))
return RULES[unique_sides]
def check_sides_length(a, b, c):
sides = [a, b, c]
for side in sides:
if side <= MINIMUM_SIDE_SIZE:
raise TriangleError('A side must be a positive integer')
return sides
# Error class used in part 2. No need to change this code.
def check_sides_sum(a, b, c):
if ((a + b) < c or (a + c) < b or (b + c) < a):
raise TriangleError('Illegal sides sum')
class TriangleError(Exception):
pass
| true |
cb56c698e2f1d3e9d7365198f95b167cc077ea00 | cleysondiego/curso-de-python-dn | /semana_1/exercicios_aula_1/Exercicio04.py | 581 | 4.3125 | 4 | #Exercicio 04
#Faça um programa que pela 2 números inteiros e um número real. Calcule e mostre:
numero1 = int(input('Digite um número inteiro: '))
numero2 = int(input('Digite outro número inteiro: '))
numero3 = float(input('Digite um número real: '))
resultado01 = (numero1*2)*(numero2/2)
print(f'O produto do dobro do primeiro com metade do segundo é: {resultado01}')
resultado02 = (numero1*3)+numero3
print(f'A soma do triplo do primeiro com o terceiro é: {resultado02}')
resultado03 = (numero3**3)
print(f'O terceiro elevado ao cubo: {resultado03}')
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.