blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
49b29222ac52fcf5670757f52964880416488fef | sadatusa/PCC | /6_3.py | 1,107 | 4.625 | 5 | # 6-3. Glossary: A Python dictionary can be used to model an actual dictionary.
# However, to avoid confusion, let’s call it a glossary.
# • Think of five programming words you’ve learned about in the previous
# chapters. Use these words as the keys in your glossary, and store their
# meanings as values.
# • Print each word and its meaning as neatly formatted output. You might
# print the word followed by a colon and then its meaning, or print the word
# on one line and then print its meaning indented on a second line. Use the
# newline character (\n) to insert a blank line between each word-meaning
# pair in your output.
python_glossary={'list':'collection of items in a particular order','tuple':'immutable list is called a tuple','if':'examine the\
current state of a program','variable':'use to store values','string':'series of characters'}
print ('LIST :'+python_glossary['list'])
print ('TUPLE :'+python_glossary['tuple'])
print ('IF :'+python_glossary['if'])
print ('VARIABLE :'+python_glossary['variable'])
print ('STRING :'+python_glossary['string']) | true |
37c35241ccca6cdedfae1fbba8c0256b9d03aee2 | Godx204857/Alberto | /Ejerciciso 5 en python.py | 402 | 4.1875 | 4 | numero=1
while(numero <= 0 or potencia <= 0):
numero = int(input("Digite un numero entero positivo: "))
potencia =int(input("Digite una potencia: "))
if(numro <=0 or potencia <=0):
print("Error. Solo positivos.")
contador = numero
while(potencia>1):
potencia = 1
numero = numero*contador
print("El numero",numero,"elevado a",potencia,"es",resultado
| false |
12291c598cff65679883bdcbcea6cbf612e878a5 | ShuWaz/100-Days-of-Code-Python | /Day 10-Functions with outputs + Calculator/Day-10-Code/main.py | 481 | 4.40625 | 4 | # format string as title
def format_as_title(first_name, last_name):
"""Takes a first and last name and format it to have the first letter uppercase"""
if first_name == "" or last_name == "":
return "You didn't provide valid first name or last name"
format_first = first_name.title()
format_last = last_name.title()
return f"{format_first} {format_last}"
print(format_as_title(input("What is your first name?\n"), input("What is your last name?\n"))) | true |
7408e6a1c75f3825b637f9601906c87fcf0772fa | rahulkhanna2/PythonPrograms | /stupid.py | 618 | 4.21875 | 4 | ##FIND THE LONGEST SUBSTRING WITH ALPHABETICAL ORDER
##USES INBUILT DEBUGGING METHODS TO SHOW THE FUNCTION
s = "azcbobobegghaklabcdefghi"
start = 0
end = 0
temp_start = 0
for i in range(1, len(s)):
if s[i-1] > s[i]:
temp_start = i
print "Value of temp start is : ",temp_start
if i - temp_start > end - start:
start = temp_start
print "start is: ",start
end = i
print "end is: ",end
string = s[start:end+1]
print 'Longest substring in alphabetical order is:', string
print 'Length of longest substring is: ', len(string)
| true |
0fc3fde09c6c6948a8fd9b175cd806344a9819b8 | rahulkhanna2/PythonPrograms | /russian_peasant_algorithm.py | 887 | 4.15625 | 4 | # Simple Algorthim which takes two numbers and multiply it without math table
# Requirements: multiply smaller number by 2 and divide bigger number by 2
# Add the numbers
"""
24 X 16 = ?
12 32 # Not needed since first number is even
6 64
3 128 # Needed since first number is 3 (odd)
1 256
"""
import time
x = int(raw_input("Enter your first number: "))
y = int(raw_input("Enter your second number: "))
def russian(x,y):
total, table = 0, {}
if x % 2 != 0: table = {x: y} # if the first number is odd add y
while x > 0:
x, y = x / 2, y * 2
table[x] = y
for key, value in table.iteritems():
if key % 2 == 1: total += value
return total
def test_russian():
start_time = time.time()
print russian(x, y)
end_time = time.time()
print "Russian Peasant Algorithm took %f seconds" % (end_time - start_time)
test_russian()
| true |
f2b8c39c75c8f73d1c9d10829f190899e4e663f3 | ishantk/PythonNwk19 | /Session1D.py | 732 | 4.34375 | 4 | # Read data from User as input
# ipAddress = "192.168.20.1" # HardCode
# Dynamic Way of creating Storage Containers i.e. Data to be taken as input from User
ipAddress = input("Enter an IP address: ")
print(">> IPAddress is:", ipAddress)
print(">> type of IPAddress", type(ipAddress))
hours = input("Enter Hours: ")
print(">> Hours is:", hours)
print(">> type of Hours is:", type(hours))
# PS: with input function whatever we are reading is always text i.e. string
# with print function whatever we will print will always be text i.e. string
# We have option to convert textual data i.e. str in any other type as required by us
age = int(input("Enter Age: "))
print(">> age is:", age)
print(">> type of age is:", type(age))
| true |
f5e07e85774cdfeb04efaed37717b28617b2a819 | ishantk/PythonNwk19 | /Session6.py | 337 | 4.125 | 4 | num = 10 # Global Variable
def update():
global num # this will use global num in update function and will not re-create a new num for update function
# num = num % 3 # Local Variable : A new container num will be created in update function
num = 7
print(">> 1. num is:", num)
update()
print(">> 2. num is:", num)
| true |
bdd4c8802d93a6629950453a2ac50cef699b66af | ishantk/PythonNwk19 | /Session7c.py | 1,429 | 4.25 | 4 | """
Restaurant HAS-A FoodItem
1 to many Mapping
1 Restaurant Has Many FoodItems
"""
class FoodItem:
def __init__(self, name, price, rating):
self.name = name
self.price = price
self.rating = rating
def showFoodItem(self):
print("------------------------------------")
print(self.name, " | ", self.price, " | ", self.rating)
print("------------------------------------")
print()
class Restaurant:
def __init__(self, name, phone, address, rating, pricePerPerson, items):
self.restaurantName = name
self.phone = phone
self.address = address
self.rating = rating
self.pricePerPerson = pricePerPerson
self.items = items # 1 to many mapping (HAS-A Relation)
def showRestaurantDetails(self):
print("===", self.restaurantName, "====")
print(">>", self.address, " | ", self.phone, " | ", self.rating)
# Iterating in a List of FoodItem Objects
for item in self.items:
item.showFoodItem()
item1 = FoodItem("Poori Channa", 105, 4.5)
item2 = FoodItem("Dal Kachori", 87, 4.8)
item3 = FoodItem("Samosa", 18, 4.0)
# print(">> item1 is:",item1) # 0x102242e80
# List of Objects :)
items = [item1, item2, item3]
r1 = Restaurant("Gopal Sweets", "+91 99999 88888", "Redwood Shores", 4.5, 200, items)
# print(">> r1 is:", r1) # 0x102a22e80
r1.showRestaurantDetails()
| false |
f139285d32f1ca2797d7edd32e3611aa0c59ca0b | ishantk/PythonNwk19 | /Session4C.py | 615 | 4.375 | 4 | S1 = {1, 2, 3, 'a', 'b'}
S2 = {1, 'a', 'b'}
print(1 in S1)
print(S2.issubset(S1))
print(S1.issuperset(S2))
# Built in function union rather than | operator
S3 = S1.union(S2) # but what happens when we do Union Operation
print("S1 now is:", S1)
print("S2 now is:", S2)
print("S3 is:", S3)
# S1.difference(S2)
# S1.intersection(S2)
# S1.symmetric_difference(S2) # Explore them :)
# PS: No Indexing is happening in SETS
# print(S1[0]) error
# Set Supports Hashing and we cannot get a single element from Set
# We need to use enhanced for Loop to read the elements in set
for elm in S1:
print(elm, end=" ") | true |
fd1ceb64e4c7ec098b63808c7d6cf2e0a73e8930 | jiogenes/pythoncode | /basic/02_if_for/iftest2.py | 322 | 4.15625 | 4 | # 숫자를 입력받아서 짝수인지 홀수인지 판별한다
number = input("input number >>")
if number.isdecimal() == True:
number = int(number)
if number % 2 == 0:
print("your number is even number")
else:
print("your number is odd number")
else:
print("your input is not number") | false |
ca1ed9769ba69cbcfa1aa07bca0a6a379fb19e00 | jsandeman/self_taught | /string1.py | 2,092 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 28 04:50:15 2019
@author: jsandeman
String-manipulation exercises got The Self-Taught Programmer course
"""
### Excercise 1: print each character in the string "Camus"
###
for letter in "Camus":
print(letter)
### Exercise 2: Input 2 strings and insert them into the tenplate:
### "Yesterday I wrote a [response_one]. I sent it to [response_two].
###
what_written = input("What did you write? ")
to_whom = input("To whom did you send it? ")
print(f"Yesterday I wrote a {what_written}. I sent it to {to_whom}!")
### Exercise 3: Captialize the first letter in the string
### "aldous Huxley was born in 1894."
###
### The capitalize() method will capitalize the 'A' in Aldous, but will
### convert everything else to lower case, so we'll split the process up
### to prevent that.
###
sentence = "aldous Huxley was born in 1894."
words = sentence.split(' ')
words[0] = words[0].capitalize()
separator = ' '
new_sentence = separator.join(words)
print(new_sentence)
### Exercise 4: Split the sentence "Where now? Who now? When now?" into:
### "Where now?", "Who now?", "When now?". The built-in split()
### almost does the trick, but strips the delimiter string so the '?'
### characters need to be added back.
sentence = "Where now? Who now? When now?"
sep_sentences = sentence.split('? ')
sep_sentences[0] += '?'
sep_sentences[1] += '?'
print(sep_sentences)
### Exercise 4: Replace every instance of "s" in "A screaming comes across the sky." with a dollar sign.
###
sentence = "A screaming comes across the sky."
new_sentence = sentence.replace('s', '$')
print(new_sentence)
### Exercise 5: Use a method to find the first index of the character "m" in the string "Hemingway".
###
word = 'Hemingway'
index = word.find('m')
print(f'The index of the first occurrence of the character \'m\' is {index}')
### Exercise 7: Create the string "three three three" using concatenation, and then again using multiplication.
###
three = " ".join(["three", "three", "three"])
alt_three = "three " *3
print(three)
print(alt_three)
| true |
3eecb58a45be9b586a375f208129d22fc6420772 | liama482/String-Jumble | /stringjumble.py | 1,704 | 4.25 | 4 | """
stringjumble.py
Author: Liam A
Credit: http://stackoverflow.com/questions/931092/reverse-a-string-in-python, Wilson,
http://stackoverflow.com/questions/10610158/how-do-i-convert-string-characters-into-a-list,
http://stackoverflow.com/questions/6181763/converting-a-string-to-a-list-of-words
Assignment:
The purpose of this challenge is to gain proficiency with
manipulating lists.
Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:
* With all letters in reverse.
* With words in reverse order, but letters within each word in
the correct order.
* With all words in correct order, but letters reversed within
the words.
Use: There you go! Good Job!
, "'", ".", "!", "?", '"', ":", ";", "/", "[", "]", "(", ")"
Output of your program should look like this:
Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
txt=input("Please enter a string of text (the bigger the better): ")
txt2='"'+str(txt)+'"'
print('You entered '+txt2+'. Now jumble it:')
print(txt [::-1]) #prints the entire line backwords
import re
Text = re.sub(("[^\w]"), " ", txt).split()
wrds=int(len(Text))
for v in range(wrds,0,-1):
print(Text[v-1], end=' ') #prints words in reverse order but the letters in the correct order, within the word
print(' ')
for t in range(0,wrds):
print(Text[t][::-1], end=' ')
| true |
6c496b7ef26ff8e4ada33a4994ced803abb18567 | lupus-magnus/django_book | /resolutions/cap2/ex1.py | 397 | 4.125 | 4 | #Crie um programa que receba cinco numeros inteiros e os imprima na ordem inversa em que foram digitados.
num_1 = input('Coloque seu numero #1:\t')
num_2 = input('Coloque seu numero #2:\t')
num_3 = input('Coloque seu numero #3:\t')
num_4 = input('Coloque seu numero #4:\t')
num_5 = input('Coloque seu numero #5:\t')
my_list = [num_1, num_2, num_3, num_4, num_5]
my_list.reverse()
print(my_list) | false |
1bc5bb26e4fc8e961800c4adaaab1e292e5cc86f | simeri/Curso-Automate-boring-stuff | /p109 Metodos.py | 1,200 | 4.28125 | 4 | __author__='Sergio Imeri 160727'
# Metodos
# .index() indice en una lista
lista = ['perro', 'gato', 'raton']
print('Lista de animales', lista)
print('raton tiene el indice', lista.index('raton'))
# .append() para agregar al final de una lista
print('Agrego mono al final de la lista')
lista.append('mono')
print('Lista de animales', lista)
# .insert(indice, valor) inserta un valor en la posicion del indice, y corre el resto
print('Inserto pollo en el indice #2, el resto lo corre')
lista.insert(2, 'pollo')
print('Lista de animales', lista)
# .remove() elimina el valor que hace match
print('Elimino pollo de la lista')
lista.remove('pollo')
print('Lista de animales', lista)
# .sort() ordena la lista
print('Ordenemos la lista ascendente')
lista.sort()
print('Lista de animales', lista)
print('Ordenemos la lista descendente')
lista.sort(reverse=True)
print('Lista de animales', lista)
# string[indice]
print('Imprimiendo coco=Cocodrilo con indices')
coco='Cocodrilo'
print ('Primera letra indice=0', coco[0])
print ('Quinta letra indice=4', coco[4])
print ('2da 3ra y 4ta posicion', coco[1:4])
for i in coco:
print('Letras ', i)
| false |
c2620193dd503b0521e731409249758fb9a4399d | Johnspeanut/Computer_science_fundation_course | /Labs/Lab9/lab9.py | 2,468 | 4.25 | 4 | """ Student name:Qiong Peng
NUID: 001559637
CS5001 Section 4, Fall 2020
Instructor: Dr.Abi Evans and Andrew Jelani
Lab 9:
"""
import turtle
def draw_polygon(line_size, a_turtle, corner_angle, line_num, draw_color):
'''
Function -- draw_polygon
Draw polygon
Parameters:
line_size -- line size
a_turtle -- an instance of Turtle
corner_angle -- corner angle. 36 for five star
line_num -- number of lines
draw_color -- drawing color
Returns:
Nothing. Draws polygon
'''
a_turtle.pendown()
a_turtle.color(draw_color)
for i in range(line_num):
a_turtle.forward(line_size)
a_turtle.right(180 - corner_angle) # angle = 36 for each corner
a_turtle.penup()
def draw_special_star(line_size, a_turtle, increasing_size):
'''
Function -- draw_special_star
Draw a special star with each side decreasing size
Parameters:
line_size -- line size
a_turtle -- an instance of Turtle
increasing_size -- increasing magnitude each time
Returns:
Nothing. Draws the special star
'''
a_turtle.pendown()
a_turtle.setheading(90 - 18)
dic_color = {"0":"green", "1":"blue", "2":"brown", "3":"red", "4":"yellow"}
for i in range(5):
a_turtle.color(dic_color["{}".format(i)])
a_turtle.forward(line_size + i * increasing_size)
a_turtle.right(180 - 36) # angle = 36 for each corner
a_turtle.penup()
def draw_special_stars(line_size, a_turtle, increasing_size):
'''
Function -- draw_special_stars
Draw a serial of special stars with each side decreasing size
recursive function
Parameters:
line_size -- line size
a_turtle -- an instance of Turtle
increasing_size -- increasing size
Returns:
Nothing. Draws the special stars
'''
LAST_TRY_LINE = 300
if line_size >= LAST_TRY_LINE:
return draw_special_star(LAST_TRY_LINE, a_turtle, increasing_size)
else:
draw_special_star(line_size, a_turtle, increasing_size)
return draw_special_stars(line_size + increasing_size * 5, a_turtle, increasing_size)
def main():
pen = turtle.Turtle() # Create a variable of data type Turtle with label turt
pen.color('yellow') # Modify the color of the turtle you just made
draw_special_stars(100, pen, 10)
turtle.done() # Stops the window from closing.
if __name__ == "__main__":
main()
| true |
946ab1d9baa1044795f9ac4d39b21e376b411da0 | Johnspeanut/Computer_science_fundation_course | /Labs/Lab3/problem_3.py | 2,162 | 4.21875 | 4 | """ Student name:Qiong Peng
NUID: 001559637
CS5001 Section 4, Fall 2020
Instructor: Dr.Abi Evans and Andrew Jelani
Lab 3
Problem 3: Days until Friday
"""
def weekday_num(str_day):
'''
Function -- weekday_num
Calculates weekday number
Parameters:
stry_day -- any one in ['M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su'], String
data type.Must be upper case.
Returns:
The number of a weekday, integer data type. If input is
invalid, return "Not valid input"
'''
valid_day = str_day in ['M', 'TU', 'W', 'TH', 'F', 'SA', 'SU']
if not valid_day:
print("Not valid input")
else:
if str_day == "M":
return 1
elif str_day == "TU":
return 2
elif str_day == "W":
return 3
elif str_day == "TH":
return 4
elif str_day == "F":
return 5
elif str_day == "SA":
return 6
else:
return 7
def num_day_until(current_day, until_day):
'''
Function -- num_day_until
Calculates the number of days between current day and until day
Parameters:
current_day -- current day number, integer data type.
until_day -- The until day number, integer data type.
Returns:
How many days there are between current day and until day, integer
data type. If input is invalid(negative), return 0
'''
if current_day <= 0 or until_day <= 0:
return 0
else:
if current_day <= until_day:
return until_day - current_day
else:
return until_day + 7 - current_day
def main():
name = input("Enter your name: ")
print("Hello, " + name)
current_day = input("Enter the current day ('M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su')").upper()
UNTIL_DAY = "F"
current_day_num = weekday_num(current_day)
until_day_num = weekday_num(UNTIL_DAY)
number_of_days_until = num_day_until(current_day_num, until_day_num)
print("The current day is {}. The number of {} days until {}.".format(current_day, number_of_days_until, UNTIL_DAY))
if __name__ == "__main__":
main()
| true |
55f47b4834149c9ef3311c8954d80d28314e8527 | Johnspeanut/Computer_science_fundation_course | /Homeworks/HW3/sizefinder.py | 2,497 | 4.28125 | 4 | """ Student name:Qiong Peng
NUID: 001559637
CS5001 Section 4, Fall 2020
Instructor: Dr.Abi Evans and Andrew Jelani
Home work 3
Programming Component
Problem 1:sizefinder.py
Program description: the program helps users to find their size based on
chese measurement in inches by kid, woman, and man.
"""
def size_checker(chest, gender):
'''
Function -- size_checker
Calculates kid, man, or woman size.
Parameters:
chest -- Chest in inches. Integer data type.
gender -- String. "M" for man; "W" for woman; "K" for kid.
Returns:
The size that it falls in, a String data type. If there is no matching
size, return "not available".
'''
if gender == "K":
if chest >= 26 and chest < 28:
return "S"
elif chest >= 28 and chest < 30:
return "M"
elif chest >= 30 and chest < 32:
return "L"
elif chest >= 32 and chest < 34:
return "XL"
elif chest >= 34 and chest < 36:
return "XXL"
return "not available"
elif gender == "W":
if chest >= 30 and chest < 32:
return "S"
elif chest >= 32 and chest < 34:
return "M"
elif chest >= 34 and chest < 36:
return "L"
elif chest >= 36 and chest < 38:
return "XL"
elif chest >= 38 and chest < 40:
return "XXL"
elif chest >= 40 and chest < 42:
return "XXXL"
return "not available"
else:
if chest >= 34 and chest < 37:
return "S"
elif chest >= 37 and chest < 40:
return "M"
elif chest >= 40 and chest < 43:
return "L"
elif chest >= 43 and chest < 47:
return "XL"
elif chest >= 47 and chest < 50:
return "XXL"
elif chest >= 50 and chest < 53:
return "XXXL"
return "not available"
def main():
chest = float(input("Chest measurement in inches: "))
kids_size = size_checker(chest, "K")
womens_size = size_checker(chest, "W")
mens_size = size_checker(chest, "M")
if (kids_size == "not available" and womens_size == "not available" and
mens_size == "not available"):
print("Sorry, we don't carry your size")
else:
print("Your size choices:")
print("Kids size:", kids_size)
print("Womens size:", womens_size)
print("Mens size:", mens_size)
if __name__ == "__main__":
main()
| true |
d06f2435176f58184d59c6a571cb19cdda7b5619 | joshi95/cv_raman | /lecture-10/main.py | 1,376 | 4.25 | 4 | # We will make a program which will get the average marks of student.
# input will be an n which will denote no of students
# after that you will take input m which will tell the no of subjects
# after this you will take n students names and take their subject marks
# "no of students ?": 5
# "no of subjects ?": 2
# "give the inputs: "
# "sadaf"
# "give the marks in subjects":
# 10 20
# "Asif"
# "give the marks in subjects":
# 10 20
# "output":
# Sadaf: 103
# Asif: 102
# whenever you want to take space seperated values as input
def get_total_students_and_subjects():
print("Please enter the no of students: ", end="")
no_of_students = int(input())
print("Please enter the no of subjects: ", end="")
no_of_subjects = int(input())
return (no_of_students, no_of_subjects)
def get_average(scores):
sum_of_all_marks = 0
for score in scores:
sum_of_all_marks += score
return sum_of_all_marks // len(scores)
def main():
no_of_students, no_of_subjects = get_total_students_and_subjects()
score_dict = {}
for i in range(no_of_students):
print("Please enter student name: ", end="")
student_name = input()
print("Please enter the marks of", student_name)
scores = list(map(int, input().split(" ")))[:no_of_subjects]
score_dict[student_name] = get_average(scores)
main()
| true |
7461de4f271846f482946cd402e5fe036424348a | joshi95/cv_raman | /python-lectures/lecture - 3/if-else.py | 2,111 | 4.375 | 4 | # In an if condition we check the conditional
# operators
# marks = 70
# if (marks > 70):
# print("You got an A")
# elif (marks > 80):
# print("You got an B")
# elif (marks > 70):
# print("You got an C")
# else:
# print("none of the above statemeent gave true")
# print("you got an F")
# print("outside the if/else")
# marks = 53
# if (marks >= 50 and marks % 2 == 0):
# print("the no is greater than 50 & even")
# else:
# if marks == 51:
# print("the no is 51")
# print("the no is odd")
# elif is not necessary but if it is used it
# should be used after an if
# else is also not necessary
# else should also be used only after an if or
# elif
# In human words
# if if fails then if there is an elif
# condition
# then that is checked
# a = 100
# b = 50
# if a == 100 and b == 50:
# print(1)
# if a == 100:
# print(2)
# if b == 50:
# print(3)
# elif a == 100:
# print(4)
# else:
# print(10)
# print(5)
# else:
# print(6)
# print(7)
# a = 5
# b = 10
# if a + b > 15:
# print(1)
# elif a + b == 15:
# print(2)
# if a == 5:
# print(3)
# else:
# print(4)
# if b == 10:
# print(5)
# else:
# print(6)
# if a == 5 and b == 10:
# print(7)
# if a == 5 or b == 8:
# print(8)
# else:
# print(9)
# print(10)
# name = "rahul"
# age = 10
# if True:
# if age == 10:
# print(1)
# else:
# print(2)
# if age * 4 > 20:
# print(3)
# print(4)
# elif age * 2 >= 20:
# print(5)
# print(6)
# else:
# print(7)
# print(8)
# if age == 10:
# print(9)
# print(10)
# print(11)
# if False:
# print(0)
# else:
# if True or False:
# print(1)
# elif True and True:
# print(2)
# if False and False:
# print(3)
# print(4)
if 1 == 1:
print(0)
if 2 == 1 + 1:
print(1)
a = 5
if a % 2 == 0:
print(2)
else:
print(3)
print(4)
print(5)
print(6) | true |
badb31bc9a57b6912b8bc8a53d063c6cbca5fa0b | lo1ol/train-schedule | /schedule_maker.py | 2,801 | 4.125 | 4 | import random
import sqlite3
def make_database(name, db=None):
"""
Make database on storage
Record is id, train number, type, depart time, travel time
:param:name : int if want to get *number* random records
or str, that consist path to database file
:param:db: None, if set name with type int. Further get value of name
db, if want to get database store records in db
:return: -> name of created db
If name is number and db is None create number of random records and return ""./data/random_schedule{name}.db
If name is string and db is number, create number of random records and return name
If name is string and db is list of records, return database with with records (with keeping order) and return name
"""
if isinstance(name, int):
db = name
name = './data/random_schedule%s.db' % db
if not db:
raise RuntimeError('Expected number if records')
connection = sqlite3.connect(name)
cursor = connection.cursor()
try:
cursor.execute('DROP TABLE schedule;')
except sqlite3.OperationalError:
pass
cmd_make_table = """
CREATE TABLE schedule(
id INTEGER PRIMARY KEY,
train_number INTEGER,
type_of_train VARCHAR(9),
departure_time DATE,
travel_time TIME
)
"""
cursor.execute(cmd_make_table)
cmd_insert_field = """
INSERT INTO schedule (id, train_number, type_of_train, departure_time, travel_time)
VALUES (NULL, {train_number},"{type}", "{d_time}", "{t_time}")"""
# Make database with records
if isinstance(db, list):
for train in db:
cursor.execute(cmd_insert_field.format(**train.form()))
connection.commit()
connection.close()
return name
# Create random records and set in database
for i in range(db):
type = random.choice(['Express', 'Passenger'])
time = random.randint(0, 1439)
month = random.randint(1, 12)
day = random.randint(1,30)
d_time = "%02d-%02d %02d:%02d" % (month, day, time // 60, time % 60)
if type == 'Express':
n = random.randint(360, 540)
t_time = "%02d:%02d" % (n//60, n%60)
else:
n = random.randint(480, 720)
t_time = "%02d:%02d" % (n//60, n%60)
cursor.execute(cmd_insert_field.format(train_number=i, type=type, d_time=d_time, t_time=t_time))
connection.commit()
connection.close()
return name
if __name__ == '__main__':
name = input('Type name of database: ')
number = input("Type number of random records: ")
try:
make_database(name, int(number))
except ValueError:
print("Not an integer number!")
| true |
6b9be2c49907264e2e6bb00066cde6ee015494b8 | jachapin/python_jungle | /DaysToHoliday.py | 1,096 | 4.71875 | 5 | from datetime import date
# This program counts down the days until Christmas or New Year's. User selects which holiday.
def main():
print("Let's count down the days until your favorite holiday! Enter 1 for Christmas or 2 for New Year\'s")
holiday = input()
if holiday == "1":
daysTillChristmas()
else:
daysTillNewYear()
# Calculate days until Christmas.
def daysTillChristmas():
today = date.today()
print("The current date and time is", today)
christmasDay = date(today.year, 12, 25)
if christmasDay < today:
christmasDay = christmasDay.replace(year = today.year + 1)
daysUntilChristmas = christmasDay - today
print("It is", daysUntilChristmas.days, "days until Christmas!")
# Calculate the number of days until New Year's Day.
def daysTillNewYear():
today = date.today()
print("The current date and time is", today)
newYearsDay = date(today.year + 1, 1, 1)
daysUntilNewYears = newYearsDay - today
print("It is", daysUntilNewYears.days, "days until New Year's!")
if __name__ == "__main__":
main() | true |
dd427f95bf166a9a3332ea1144425c517ab83573 | Markieneter/Python-scripts | /Opdracht 6.9.py | 781 | 4.34375 | 4 | # 6. AVERAGE NUMBERS
#
# Assume that a file containing a series of integers is named
# 'numbers.txt' and exists on the computer's disk. Write a
# program that reads all of the numbers stored in the file
# and calculates their total.
def main():
try:
file = open("numbers.txt", "r")
num = file.readlines()
file.close()
except IOError:
print("IOError, something is wrong with your file")
get_avg(num)
def get_avg(num):
total = 0
try:
num = list(map(int, num))
except ValueError:
print("The values are not converted to a number!" )
for x in num:
total += x
print("The total amount is", total,"and the average is", total/len(num))
main()
| true |
5dc31615c5f60d333ef803bc453afb565eea472d | allamrajukrish/Python_Tutorial | /1_Basics/Basics.py | 1,539 | 4.28125 | 4 | print("Hello World!")
a=23
print (a)
# This is how we do single line comment, we use '#'' before the line.
'''
This is how we do multi line commenting, we use '''
''
import os
clear = lambda: os.system('cls')
clear()
import os
clear = lambda: os.system('clear')
clear()
myName = 'Krish'
idNum = 10123
varIsFlag = True
print(type(idNum)) #function "type" will tell us about the datatype of the object
print (type(myName))
print (type(varIsFlag))
type(14)
print(type(True))
print(type(999888777)) #Python2.7 will treat it like a longint
import keyword
print(keyword.kwlist)
#Basic Operators
#___________Addition____________
varAddition = 32+23
print(varAddition)
print(33+44+55+66)
print(1.1+2.2+3.3+4.4+5)
#____________Subtraction____________
varSubtraction = 23-32
print(varSubtraction)
print(12-3)
print(10-2.5)
#___________Multiplication___________
varMultiplication = 5*8
print(varMultiplication)
print(10*4)
print(2.2*4)
print(5**3) #Exponent
'''
here ** is used to multiply the same number with
given number of times. You can also read it like
5 to the power 3 or 5 cube
'''
#______________Division_________________
varDivision = 44/11
print(varDivision)
print(48/6)
print(5/2)
print(96/8.0)
print (44//11) # here // will round the division result
print (5.0 // 2) # here // will round the division result
varModular = 5%2 # which gives the reminder
print(varModular)
#Operator Precedence : Complex arithmetic operations
varResult = ((12+13)*3)/5+150-(5**3)
print("The Result is %d" %varResult)
| true |
db0a2e0080bed147358b5e82d60acc15ecb2d08b | maijlma/AoC2020 | /d15/d15.py | 811 | 4.21875 | 4 | #Day 15: Rambunctious Recitation
#asking user for input & processing it for use
def process_inputs():
csv = input("What is your puzzle input?\n")
list = csv.split(",")
for i in range(len(list)):
list[i] = int(list[i])
return list
def main():
list = process_inputs()
i = len(list) - 1
#reciting numbers
while len(list) < 2020:
number = list[-1]
#determining next when number hasn't been spoken before
if list.count(number) == 1:
next = 0
#finding next if number has already been spoken by using indexes
else:
number_i = list.index(number)
next = len(list) - (number_i + 1)
list[number_i] = -1
list.append((next))
print("The 2020th number spoken is:", list[-1])
main() | true |
04c5bbbfec4afa408422bd35b6e7e38ad5466782 | TryNeo/practica-python | /ejerccios/ejerccio-29.py | 752 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Escribir otra función repite_hola que reciba como parámetro un número entero n
y retorne la cadena formada por n concatenaciones de "Hola". Invocarla con distintos valores de n.
"""
def repite_hola(n):
"""
Esta funcion recibe como parametro:
n : int
que sera mandado en un rango para poder repetirlo con cantidades diferente dentro de un for
"""
#recibe como parametro n el for
for i in range(0,n):
print(f'Hola - {i}')
def main():
print("\tEjerccio 29")
print()
#declaramos un variable entero que recibira como parametro un numero entero
n = int(input("ingrese numero:"))
#llamamos a la funcion repite_hola()
iprime_hola = repite_hola(n)
if __name__ == '__main__':
main() | false |
e76b21a90ecf30865075b757179cb74ee3276b85 | TryNeo/practica-python | /ejerccios/ejerccio-6.py | 1,214 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Escribir un programa que le pida una palabra al usuario,
para luego imprimirla 1000 veces, con espacios intermedios.
"""
#declaramos la funcion
def intermedios(palabra):
#declaramos un contador
contador = 0
#declaramos un bucle que si el contador es menor que 1000, esto sera true caso contrario que el contador sea mayora sera false y se rompera el bucle
while contador < 1000:
#declaramos la variable resultado que llevara como parametro palabra la cual va a tener la funcion replace que remplazara los que no tienen y se les agregara un espacio
resultado = palabra.replace('',' ')
print(resultado)
#e incrementaremos el contador hasta que sea mayor a 1000
contador+=contador
return resultado # y retornamos
#definimos esta funcion que va ejecutar mayor parte del script
def main():
print("\tEjerccio 6")
print()
#declaramos la variable palabra, que recibiria por teclado una palabra que le envie el usuario
palabra = input("ingrese una palabra:")
print()
#declaramos la variable espacio que va instaciar la funcion intermedios que recibe como parametro la palabra
espacios = intermedios(palabra)
if __name__ == '__main__':
main() | false |
d0508be16e91906501a2170088a096d147837638 | TryNeo/practica-python | /ejerccios/ejercicio-99.py | 1,192 | 4.65625 | 5 | #!/bin/python3
"""
El tema de listas es sin duda uno de los temas preferidos entre los desarrolladores, es por ello que en esta ocasión tocará el turno que desarrolle un programa el cual cumpla con los siguientes requerimientos.
El programa debe ser capaz de crear dos listas a partir de lo que el usuario introduzca en consola (vía teclado).
La longitud de las listas estará dada por el usuario (Pueden ser de longitudes diferentes).
Las listas almacenará, única y exclusivamente, números enteros.
El programa debe mostrar en consola los elementos de ambas listas.
Ejemplo.
Ingresa la longitud de la primera lista: 3
Ingresa un número a la lista: 10
Ingresa un número a la lista: 20
Ingresa un número a la lista: 30
Ingresa la longitud de la segunda lista: 2
Ingresa un número a la lista: 5
Ingresa un número a la lista: 6
[10, 20, 30]
[5, 6]
"""
def main():
a = [int(input("Ingresa un número a la lista:"))for _ in range(int(input("ingrese la longitud de la primera lista:")))]
b = [int(input("Ingresa un número a la lista:"))for _ in range(int(input("ingrese la longitud de la segunda lista:")))]
print(a)
print(b)
if __name__ == "__main__":
main() | false |
bda9c308bffc6720d4a4c4d2f0ab2acd784672a9 | TryNeo/practica-python | /ejerccios/ejerccio-13.py | 504 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Mostrar en pantalla la cantidad de vocales que existe en una
frase dada por el usuario."""
def vocales(frase):
vocal = ['a','e','i','o','u']
lista = []
for i in frase:
if i in vocal:
lista.append(i)
return lista
def main():
print("\tEjerccio 13")
print()
frase = input("ingrese una frase:")
resultado = vocales(frase)
print("cantidad de vocales en su frase es de : ",len(resultado))
return resultado
if __name__ == '__main__':
main()
| false |
d9e1a2e4812dda4f637e9531d956147787ab108f | bmuha1/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 293 | 4.21875 | 4 | #!/usr/bin/python3
def uppercase(str):
change_case = 0
for letter in str:
if ord(letter) >= ord('a') and ord(letter) <= ord('z'):
change_case = 32
else:
change_case = 0
print('{:c}'.format(ord(letter) - change_case), end="")
print()
| true |
dd5d36c8a155c53759d962d3827d2be4da0e2003 | bmuha1/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 289 | 4.25 | 4 | #!/usr/bin/python3
"""
This is the "append write" module.
The append write module defines one function, append_write().
"""
def append_write(filename="", text=""):
"""Append a string at the end of a text file."""
with open(filename, 'a') as f:
return f.write(str(text))
| true |
43284c3a6f2a5ed2d83fc49f27e1f50eb9924948 | bmuha1/holbertonschool-higher_level_programming | /0x08-python-more_classes/101-nqueens.py | 2,232 | 4.21875 | 4 | #!/usr/bin/python3
from sys import argv
class Chessboard:
"""Represents a chessboard."""
def __init__(self, size):
"""Initialize the data."""
self.size = size
self.cols = []
def place_in_next_row(self, col):
"""Place in next row."""
self.cols.append(col)
def remove_in_current_row(self):
"""Remove in current row."""
return self.cols.pop()
def next_row_safe(self, col):
"""Check if current col in the next row is safe."""
row = len(self.cols)
for q_col in self.cols:
if col == q_col:
return False
for q_row, q_col in enumerate(self.cols):
if q_col - q_row == col - row:
return False
for q_row, q_col in enumerate(self.cols):
if self.size - q_col - q_row == self.size - col - row:
return False
return True
def display(self):
"""Display a valid solution."""
print('[', end='')
for row in range(self.size):
for col in range(self.size):
if col == self.cols[row]:
print('[{}, {}]'.format(row, col), end='')
if row < self.size - 1:
print(', ', end='')
print(']')
def solve(size):
"""Solve the N queens problem."""
board = Chessboard(size)
row = col = 0
while True:
while col < size:
if board.next_row_safe(col):
board.place_in_next_row(col)
row += 1
col = 0
break
else:
col += 1
if col == size or row == size:
if row == size:
board.display()
board.remove_in_current_row()
row -= 1
try:
prev_col = board.remove_in_current_row()
except IndexError:
break
row -= 1
col = 1 + prev_col
if len(argv) != 2:
print('Usage: nqueens N')
exit(1)
try:
queens = int(argv[1])
except ValueError:
print('N must be a number')
exit(1)
if queens < 4:
print('N must be at least 4')
exit(1)
solve(queens)
| true |
f176f087c12ec7055d155d30ee5478a722d6d686 | JohnALong/python101 | /planner/city.py | 671 | 4.125 | 4 | class City:
def __init__(self, name, established):
self.name = name
self.mayor = ""
self.established = established
self.buildings = list()
def add_building(self, new_building):
self.buildings.append(new_building)
def elect_mayor(self, mayor):
self.mayor = mayor
def about(self):
# date = self.date_constructed
print(f"{self.name}'s mayor is {self.mayor}, and was established in {self.established}.")
def city_buildings(self):
print(f"{self.name} is in Southeast Missouri, and has the following buildings:")
for building in self.buildings:
building.info() | false |
c88d3bc0e812323134b126c5bc54c9df2ec7b153 | domortiz/Triangle567 | /test_triangle.py | 1,646 | 4.125 | 4 | """this contains all unit tests"""
import unittest
from triangle import classify_triangle
# This code implements the unit test functionality
class TestTriangles(unittest.TestCase):
# define multiple sets of tests as functions with names that begin
"""runs all the test for the triangle """
def test_right(self):
"""test if thr=e triangle is a right triangle"""
self.assertEqual(classify_triangle(3, 4, 5), 'Right', '3,4,5 is a Right triangle')
self.assertEqual(classify_triangle(5, 3, 4), 'Right', '5,3,4 is a Right triangle')
def test_equilateral(self):
"""test if the triangle is equilateral"""
self.assertEqual(classify_triangle(1, 1, 1), 'Equilateral', '1,1,1 should be equilateral')
def test_scalene(self):
"""test if the triangle is scalene"""
self.assertEqual(classify_triangle(1, 2, 3), 'Scalene', '1,2,3 should be Scalene')
def tests_isosceles(self):
"""test if the triangle is isosceles"""
self.assertEqual(classify_triangle(1, 2, 2), 'Isosceles', '1,2,2 should be Isosceles')
# these are the new tests
def test_invalid(self):
"""test for invalid inputs"""
self.assertEqual(classify_triangle(0, 1, 2), 'InvalidInput', '0,1,2 is an invalid input')
self.assertEqual(classify_triangle(10, 10, 10.5), 'InvalidInput', '0,1,2 is an invalid input')
def test_not_triangle(self):
"""test for unreal triangles"""
self.assertEqual(classify_triangle(1, 10, 12), 'NotATriangle', '1,10,12 is not a triangle')
if __name__ == '__main__':
print('Running unit tests')
unittest.main()
| true |
570dd59d0a8d77a8700a3030969d927514c98fa1 | chinayangd/-----Python | /Python01/ex32.py | 1,325 | 4.40625 | 4 | # coding=utf-8
# 习题 32: 循环和列表
# ex32.py
# 创建列表
the_count=[1,2,3,4,5]
fruits=['apples','oranges','pears','apricots']
change=[1,'pennies',2,'dimes',3,'quarters']
# 使用for循环遍历the_count列表
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" %number
# 使用for循环遍历fruits列表
# same as above
for fruit in fruits:
print "A fruit of type: %s" %fruit
# 使用for循环遍历change列表
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I go %r" %i
# 创建一个空列表
# we can also build lists, first start with an empty one
elements=[]
# then use the range function to do 0 to 5 counts
# range也是一种类型(type),它是一个数字的序列,而且是不可变的,通常用在for循环中
for i in range(0,6):
print "Adding %d to the list." %i
# append is a function that lists understand
# append() 方法向列表elements的尾部添加一个新的元素
elements.append(i)
# 以上循环可替换为:elements = range(0, 6)
# 打印列表
# now we can print them out too
for i in elements:
print "Element was: %d" %i
print "---------------------"
for z in range(1,11,2):
print z
else:
print 'The for loop is over'
| false |
e283c2e084baa6cbb6e0925c2aec9963c1bc9572 | danielperecz/data-structures-algorithms-and-oop | /algorithms/searching/breadth_first_search.py | 632 | 4.125 | 4 | def bfs(graph, root):
visited = set(root)
queue = [root]
visited_order = []
while queue:
vertex = queue.pop(0)
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
visited_order.append(neighbour)
print(" -> ".join(visited_order))
if __name__ == "__main__":
graph_ = {
"A": ["B", "C"], # Node A connected to B & C
"B": ["D", "E"], # B connected to D & E
"C": ["F"],
"D": [],
"E": ["F"],
"F": []
}
bfs(graph_, "A")
| true |
447eba35b72a308dc52780619ef26932300baf80 | leokaka1/Python-practice | /Python_Basic_Learning/11.面向对象.py | 2,328 | 4.5625 | 5 | """
定义类
class 类名():
代码
....
"""
class Washer():
def wash(selfs):
print("我会洗衣服")
"""
创建对象
对象名 = 类名()
"""
#创建对象
haier1 = Washer()
print(haier1)
haier1.wash()
"""
类外面添加对象属性
对象名.属性名 = 值
"""
haier1.width =500
haier1.height = 800
"""
类外面获取对象的属性
对象名.属性名
"""
print(f"haier1洗衣机的宽度是{haier1.width}")
print(f"haier1洗衣机的高度是{haier1.height}")
"""
类里面获取对象的属性
self.属性名
"""
class Washer():
def print_info(self):
print(f"haier1洗衣机的宽度是{self.width}")
print(f"haier1洗衣机的高度是{self.height}")
haier2 = Washer()
haier2.width = 500
haier2.height = 800
haier2.print_info()
"""
魔法方法
"""
class Washer():
def __init__(self):
self.width = 500
self.height = 800
def print_info(self):
print(f"洗衣机的宽度是{self.width},高度是{self.height}")
haier3 = Washer()
haier3.print_info()
"""
带参数的init
"""
class Washer():
def __init__(self,width,height):
self.width = width
self.height = height
def print_info(self):
print(f"洗衣机的宽度是{self.width},高度是{self.height}")
haier4 = Washer(10,20)
haier4.print_info()
"""
__str__()
当使用print输出对象的时候,默认打印对象的内存地址,如果类定义了__str__方法,那么就会打印从这个方法中return的数据
"""
class Washer():
def __init__(self,width,height):
self.width = width
self.height = height
def __str__(self):
return "这是洗衣机的说明书"
def print_info(self):
print(f"洗衣机的宽度是{self.width},高度是{self.height}")
haier5 = Washer(10,20)
haier5.print_info()
print(haier5)
"""
__del__()
当删除对象时候,python解释器也会默认调用__del()方法
"""
class Washer():
def __init__(self,width,height):
self.width = width
self.height = height
def __str__(self):
return "这是洗衣机的说明书"
def __del__(self):
print(f"对象已经被删除")
def print_info(self):
print(f"洗衣机的宽度是{self.width},高度是{self.height}")
haier6 = Washer(10,20)
haier6.print_info()
del haier6
| false |
6582c5c08387677a1b2a00bb35f2580ca0ae4948 | notknowofdoing/starting-out | /word_finder/wfnd-knls/trash/knls-modules.py | 614 | 4.15625 | 4 | def extract_text(file):
from string import ascii_letters as letters
original_text = file.read().lower()
file.close()
text = ''
for i in original_text:
if i in letters:
text += i
else:
continue
return text
def get_file(prompt):
filename = input(f"Name of file containing {prompt}: ")
while True:
try:
file = open(filename,"r")
except:
filename = input("That file does not exist on the disk. Try again.\nEnter file name: ")
else:
break
return file
def dictionarize(input):
result = input.strip("\n").split(",")
return result
| true |
c3ae9bceadd94c05a3b4f3d12f4d9b6394d18ab8 | Varun-nair1997/ArmstrongLocator | /poissonDist.py | 1,839 | 4.25 | 4 | """
This program plots the poisson distribution when fed a lambda parameter for a random variable.
"""
__Author__ = "Varun Nair"
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import simps
from math import *
def poissonPreProcess(intervalLen, start):
"""
sets up the random variable and support for the PMF
:param intervalLen: length of the interval
:param start: start point for the graph
:return: returns xAxis for plot
"""
span = np.arange(start,start+intervalLen+1)
return span
def poissonDist(avg, k):
"""
Calculates poisson distribution PMF for a random variable with avg parameter
:param avg: lambda paramter for possion
:param k: random variable number
:return: pmf
"""
PMF = ((avg**k)*(np.exp(-1*avg))/(factorial(k)))
return(PMF)
def pmfPlotter(pmf, timeLine):
"""
creates plots of the poisson PMF
:param pmf: array of PMF values
:param timeLine: xAxis and support
:return: plotten poisson PMF
"""
plt.plot(timeLine, pmf)
plt.show()
def areaCalc(PMF):
"""
This function calculates the area under the curve described by the PMF of the distribution.
:param PMF: Probability mass function
:return: Area under the curve using the trapezoid method
"""
pmf = np.asarray(PMF)
area = np.trapz(pmf, dx=e-4)
area2 = simps(pmf, dx=0.0001)
print("area trap: ", area)
print("area simps: ", area2)
if __name__ == '__main__':
intLen = int(input("enter length of interval: "))
startPoint = int(input("enter start: "))
lambdaVal = float(input("enter lambda parameter: "))
xAxis = poissonPreProcess(intLen, startPoint)
pmfList = []
for i in xAxis:
pmfVal = poissonDist(lambdaVal, i)
pmfList.append(pmfVal)
pmfPlotter(pmfList, xAxis)
| true |
9660c84cdcfe667945be7c1d0208d67f972841ab | songcelia88/practice-problems | /smallest-difference.py | 615 | 4.15625 | 4 | def findSmallestDifference(A, B, lenA, lenB):
'''take in one number from list A
take in one number from list B
look at the absolute difference
return the smallest absolute difference
>>> findSmallestDifference([1, 3], [0], 2, 1)
1
#Part 2: restructure code to allow for a runtime less than O(n^2)
#Part 3: discuss the runtime of the restructured code
'''
# O(n^2) solution is to loop through each element in A and loop through each element in B for
# each element in A, find the difference and keep track of the min difference
# lower runtime: sort the lists? | true |
d2a7f56f802ddf28c92cdf1732ada4207a3777b9 | songcelia88/practice-problems | /riffle_check.py | 1,251 | 4.3125 | 4 | # check to see if a deck of cards is shuffled with a single riffle
# stack of cards is list of integers 1-52
# loop through the shuffled deck stack
# check first card in shuffled deck
# see if it matches the first card in half1 or half 2
# if it matches either
# pop shuffled deck card, pop the corresponding card in half1 or half2
# if it doesn't then, return False
# if it goes through the whole loop return True
# https://www.interviewcake.com/question/python/single-riffle-check?course=fc1§ion=array-and-string-manipulation
def riffle_check(shuffled_deck, half1, half2):
""" Determine if the shuffled deck is a riffle of half1 and half2
All inputs are lists of numbers
Output True if it is a riffle, False if not
"""
# keep index for shuffled deck, half1 and half2 for better runtime
half1_idx = 0
half2_idx = 0
half1_max_index = len(half1) - 1
half2_max_index = len(half2) - 1
for i in range(0,len(shuffled_deck)):
if half1_idx<=half1_max_index and shuffled_deck[i] == half1[half1_idx]:
half1_idx +=1
elif half2_idx<=half2_max_index and shuffled_deck[i] == half2[half2_idx]:
half2_idx +=1
else:
return False
return True | true |
b09d79c178addaa868d2f02cb4f1a01e11b177d4 | kirill432111/python | /les1/массивы/1 массивы.py | 485 | 4.1875 | 4 | def bubble_sort(list):
for i in range(len(list) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if list[j + 1] < list[j]:
list[j], list[j + 1] = list[j + 1], list[j]
no_swap = False
if no_swap:
return
list = input('Введите список цифр: ').split()
list = [int(x) for x in list]
bubble_sort(list)
print('Отсортированный список: ', end='')
print(list) | false |
ba5f15a6da930763a5d9c9ccf76af6c4fd6141d8 | sc076/Yonsei | /Programming/lab8/lab8_p4.py | 759 | 4.15625 | 4 | import stack
""" Ask the user to enter a series of braces and parentheses,
then indicate if they are properly nested
"""
char = input('Enter parentheses and/or braces: ')
sequence = stack.getStack()
#for every element in the received string checks the type and pushes/pops in/from the stack
for el in char:
if el == '(' or el == '{':
stack.push(sequence, el)
elif not stack.isEmpty(sequence):
if el == ')' and stack.top(sequence) == '(':
stack.pop(sequence)
elif el == '}' and stack.top(sequence) == '{':
stack.pop(sequence)
#Final check if the stack is empty
#If it's empty the string is proper
if stack.isEmpty(sequence):
print('Nested properly.')
else:
print('Not properly nested.')
| true |
ea75d61dbe114f19edb6927ead91cd5be28783eb | sc076/Yonsei | /Programming/lab9/lab9_p3.py | 303 | 4.28125 | 4 | def formatMonth(date):
""" Replace slashes with dashes in 'date' and returns the result.
Note: you only have to replace slashes with
dashes. For whatever string the function
receives.
"""
#Uses the function replace to replace the slashes
date.replace('/', '-')
return date
| true |
071a0d44db2a7073b56310a6255fa006a5f8809a | sc076/Yonsei | /Programming/lab3/hw/lab3_p4.py | 265 | 4.28125 | 4 | print('# Fahrenheit to Celsius conversion program\n')
print('fahren = float(input(\'Enter degrees Fahrenheit: \'))')
print('celsius = (fahren - 32) * 5 / 9')
print('print(fahren, \'degrees Fahreheit equals\',\n format(celsius, \'.1f\'), \'degrees Celsius\')')
| false |
0a32c2c03b7056d9ea4c638b1ae4ff65af80a594 | christopher-burke/warmups | /python/codingbat/src/array123.py | 1,119 | 4.40625 | 4 | #!/usr/bin/env python3
"""Array 1 2 3.
Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere.
array123([1, 1, 2, 3, 1]) → True
array123([1, 1, 2, 4, 1]) → False
array123([1, 1, 2, 1, 2, 3]) → True
source: https://codingbat.com/prob/p193604
"""
from functools import partial
def array_find(nums: list, target=None) -> bool:
"""Determine if target is in nums."""
for i in range(len(nums)):
if target == nums[i:i+3]:
return True
return False
array123 = partial(array_find, target=[1, 2, 3])
def main():
"""Test the array123 function."""
assert array123([1, 1, 2, 3, 1]) is True
assert array123([1, 1, 2, 4, 1]) is False
assert array123([1, 1, 2, 1, 2, 3]) is True
assert array123([1, 1, 2, 1, 2, 1]) is False
assert array123([1, 2, 3, 1, 2, 3]) is True
assert array123([1, 2, 3]) is True
assert array123([1, 1, 1]) is False
assert array123([1, 2]) is False
assert array123([1]) is False
assert array123([]) is False
print('Passed.')
if __name__ == "__main__":
main()
| true |
b49045bb2087d13bd75297e5beac87644e96ad03 | christopher-burke/warmups | /python/misc/pythagorean_triplet.py | 747 | 4.15625 | 4 | #!/usr/bin/env python3
"""Pythagorean Triplet.
Given an array of integers, write a function that returns
true if there is a triplet (a, b, c) that satisfies
a**2 + b**2 = c**2.
source: https://practice.geeksforgeeks.org/problems/pythagorean-triplet/0
"""
def main(A):
"""Pythagorean Triplet in Array A."""
squares = sorted([x**2 for x in A])
for x in reversed(squares):
for y in squares[0:
squares.index(x)]:
if x - y in squares[squares.index(y):
squares.index(x)]:
return True
return False
if __name__ == "__main__":
print(main(A=[3, 2, 4, 6, 5, ]))
print(main(A=[3, 2, 4, 6, ]))
print(main(A=[3, 1, 4, 6, 5, ]))
| true |
fc1b43122e830ca16c31827a8a2a923d22d28863 | christopher-burke/warmups | /python/misc/words_with_duplicate_letters.py | 2,207 | 4.1875 | 4 | #!/usr/bin/env python3
"""Words With Duplicate Letters.
Given a common phrase, return False if any individual word in the phrase
contains duplicate letters. Return True otherwise.
Source:
https://edabit.com/challenge/WS6hR6b9EZzuDTD26
"""
def no_duplicate_letters(phrase: str) -> bool:
"""Check if each word has distinct letters in phrase."""
words = phrase.split(' ')
for word in words:
if len(set(word)) == len(word):
continue
else:
return False
return True
def main():
"""Run sample no_duplicate_letters functions. Do not import."""
assert no_duplicate_letters("Easy does it.") is True
assert no_duplicate_letters("So far, so good.") is False
assert no_duplicate_letters("Better late than never.") is False
assert no_duplicate_letters("Beat around the bush.") is True
assert no_duplicate_letters(
"Give them the benefit of the doubt.") is False
assert no_duplicate_letters(
"Your guess is as good as mine.") is False
assert no_duplicate_letters("Make a long story short.") is True
assert no_duplicate_letters("Go back to the drawing board.") is True
assert no_duplicate_letters(
"Wrap your head around something.") is True
assert no_duplicate_letters("Get your act together.") is False
assert no_duplicate_letters("To make matters worse.") is False
assert no_duplicate_letters("No pain, no gain.") is True
assert no_duplicate_letters(
"We'll cross that bridge when we come to it.") is False
assert no_duplicate_letters("Call it a day.") is False
assert no_duplicate_letters("It's not rocket science.") is False
assert no_duplicate_letters("A blessing in disguise.") is False
assert no_duplicate_letters("Get out of hand.") is True
assert no_duplicate_letters("A dime a dozen.") is True
assert no_duplicate_letters(
"Time flies when you're having fun.") is True
assert no_duplicate_letters("The best of both worlds.") is True
assert no_duplicate_letters("Speak of the devil.") is True
assert no_duplicate_letters("You can say that again.") is False
print('Passed.')
if __name__ == "__main__":
main()
| true |
a9fa373f510367e08e106db3fa6acd7f1c7c08a0 | christopher-burke/warmups | /python/misc/return_a_string_as_an_integer.py | 540 | 4.46875 | 4 | #!/usr/bin/env python3
"""Return a String as an Integer.
Create a function that takes a string and returns it as an integer.
Source:
https://edabit.com/challenge/GPmoRCZKkyNtoJMcN
"""
def string_int(txt: str) -> int:
"""Convert string to int."""
return int(txt)
def main():
"""Run sample string_int functions. Do not import."""
assert string_int("6") == 6
assert string_int("2") == 2
assert string_int("10") == 10
assert string_int("666") == 666
print('Passed.')
if __name__ == "__main__":
main() | true |
1bf740243033258ec18b27df6361c8fda228b34a | christopher-burke/warmups | /python/misc/switcharoo.py | 1,247 | 4.375 | 4 | #!/usr/bin/env python3
"""Switcharoo.
Create a function that takes a string and returns a new string with its
first and last characters swapped, except under three conditions:
If the length of the string is less than two, return "Incompatible.".
If the argument is not a string, return "Incompatible.".
If the first and last characters are the same, return "Two's a pair.".
Source:
https://edabit.com/challenge/tnKZCAkdnZpiuDiWA
"""
def flip_end_chars(txt):
"""Flip the first and last characters if txt is a string."""
if isinstance(txt, str) and txt and len(txt) > 1:
first, last = txt[0], txt[-1]
if first == last:
return "Two's a pair."
return "{}{}{}".format(last, txt[1:-1], first)
return "Incompatible."
def main():
assert flip_end_chars("Cat, dog, and mouse.") == ".at, dog, and mouseC"
assert flip_end_chars("Anna, Banana") == "anna, BananA"
assert flip_end_chars("[]") == "]["
assert flip_end_chars("") == "Incompatible."
assert flip_end_chars([1, 2, 3]) == "Incompatible."
assert flip_end_chars("dfdkf49824fdfdfjhd") == "Two's a pair."
assert flip_end_chars("#343473847#") == "Two's a pair."
print('Passed.')
if __name__ == "__main__":
main()
| true |
a2f3b210cfd8911176851f1f39cb2f5a7e3cae51 | christopher-burke/warmups | /python/misc/does_the_dictionary_contain_a_given_key.py | 744 | 4.34375 | 4 | #!/usr/bin/env python3
"""Does the Dictionary Contain a Given Key.
Write a function that returns True if a dictionary contains the specified key,
and False otherwise.
Source:
https://edabit.com/challenge/zdo6JCL6Z5d2fT8JB
"""
def has_key(dictionary, key) -> bool:
"""Dictionary contain the key."""
return key in dictionary.keys()
def main():
"""Run sample functions. Do not import."""
assert has_key({"pot": 1, "tot": 2, "not": 3}, "not") is True
assert has_key({"craves": True, "midnight": True, "snack": True}, "morning") is False
assert has_key({"a": 44, "b": 45, "c": 46}, "d") is False
assert has_key({"a": "z", "b": "y", "c": "x"}, "c") is True
print('Passed.')
if __name__ == "__main__":
main() | true |
95ebf4d5d05f71c8d1313556aedd50d4b9368bc6 | christopher-burke/warmups | /python/misc/calculate_profit.py | 1,878 | 4.3125 | 4 | #!/usr/bin/env python3
"""Calculate the Profit.
You work for a manufacturer, and have been asked to calculate the total
profit made on the sales of a product. You are given a dictionary containing
the cost price per unit (in dollars), sell price per unit (in dollars),
and the starting inventory. Return the total profit made, rounded to the
nearest dollar. Assume all of the inventory has been sold.
Source:
https://edabit.com/challenge/YfoKQWNeYETb9PYpw
"""
from typing import Dict
def profit(info: Dict) -> int:
"""Calculate the profit from info."""
profit_ = (info['sell_price'] - info['cost_price']) * info['inventory']
return round(profit_)
def main():
"""Run sample profit functions. Do not import."""
assert profit({'cost_price': 32.67, 'sell_price': 45.00,
'inventory': 1200}) == 14796
assert profit({'cost_price': 0.1, 'sell_price': 0.18,
'inventory': 259800}) == 20784
assert profit({'cost_price': 185.00, 'sell_price': 299.99,
'inventory': 300}) == 34497
assert profit({'cost_price': 378.11, 'sell_price': 990.00,
'inventory': 99}) == 60577
assert profit({'cost_price': 4.67, 'sell_price': 5.00,
'inventory': 78000}) == 25740
assert profit({'cost_price': 19.87, 'sell_price': 110.00,
'inventory': 350}) == 31546
assert profit({'cost_price': 2.91, 'sell_price': 4.50,
'inventory': 6000}) == 9540
assert profit({'cost_price': 68.01, 'sell_price': 149.99,
'inventory': 500}) == 40990
assert profit({'cost_price': 1.45, 'sell_price': 8.50,
'inventory': 10000}) == 70500
assert profit({'cost_price': 10780, 'sell_price': 34999,
'inventory': 10}) == 242190
print('Passed.')
if __name__ == "__main__":
main()
| true |
0052f6ad48cf6af718adf0eb52d23125d7e6f750 | christopher-burke/warmups | /python/misc/reverse_words_in_a_given_string.py | 659 | 4.5625 | 5 | #!/usr/bin/env python3
"""Reverse words in a given string.
Given a String of length S, reverse the whole string without reversing the individual words in it.
Words are separated by dots.
source: https://practice.geeksforgeeks.org/problems/reverse-words-in-a-given-string/0
"""
def reverse_words_in_string(text):
"""Reverse the words in a string."""
reversed_words = reversed([word for word in text.split('.')])
return '.'.join(reversed_words)
if __name__ == "__main__":
test_cases = (
'i.like.this.program.very.much',
'pqr.mno',
)
for test_case in test_cases:
print(reverse_words_in_string(test_case))
| true |
e55ae4b4e9cd1caf66837810514ffb2b62ff4717 | christopher-burke/warmups | /python/misc/solving_exponential_equations_with_logarithms.py | 786 | 4.15625 | 4 | #!/usr/bin/env python3
"""Solving Exponential Equations With Logarithms.
Create a function that takes a number a and finds the missing exponent
x so that a when raised to the power of x is equal to b.
Source:
https://edabit.com/challenge/MhQbon8XzsG3wJHdP
"""
from math import log
def solve_for_exp(a, b):
"""Find the missing exponent.
a=base
b=result"""
return int(round(log(b, a)))
def main():
assert solve_for_exp(4, 1024) == 5
assert solve_for_exp(2, 1024) == 10
assert solve_for_exp(9, 3486784401) == 10
assert solve_for_exp(4, 4294967296) == 16
assert solve_for_exp(8, 134217728) == 9
assert solve_for_exp(19, 47045881) == 6
assert solve_for_exp(10, 100000000) == 8
print('Passed.')
if __name__ == "__main__":
main()
| true |
9d92c91aa06c90dd8c85e82c126db454d1ffe53a | christopher-burke/warmups | /python/misc/odd_up_even_down_n_times.py | 1,377 | 4.59375 | 5 | #!/usr/bin/env python3
"""Odd Up, Even Down - N Times.
Create a function that performs an even-odd transform to a list, n times.
Each even-odd transformation:
Adds two (+2) to each odd integer.
Subtracts two (-2) to each even integer.
Source:
https://edabit.com/challenge/ke4FSMdG2XYxbGQny
"""
from typing import List
def logic(number: int) -> int:
"""Perform logic for even-odd transformation.
Each even-odd transformation:
* Adds two (+2) to each odd integer.
* Subtracts two (-2) to each even integer.
"""
# Determine the modifier based on number being even or odd.
modifier = -2 if number % 2 == 0 else 2
return number + modifier
def odd_even_transform(lst: List, n: int) -> List:
"""Perform an even-odd transform to a list, n times.
Uses logic function to perform transformation.
"""
for _ in range(n):
lst = [logic(item) for item in lst]
return lst
def main():
"""Run sample odd_even_transform functions. Do not import."""
# Run assert statments to test odd_even_transform.
assert odd_even_transform([3, 4, 9], 3) == [9, -2, 15]
assert odd_even_transform([0, 0, 0], 10) == [-20, -20, -20]
assert odd_even_transform([1, 2, 3], 1) == [3, 0, 5]
assert odd_even_transform([55, 90, 830], 2) == [59, 86, 826]
print("Passed.")
if __name__ == "__main__":
main()
| true |
a1aa8ebbfdf4e672652d4aa84bb77576796b05d0 | christopher-burke/warmups | /python/codingbat/src/make_abba.py | 1,158 | 4.625 | 5 | #!/usr/bin/env python3
"""Make abba.
Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".
make_abba('Hi', 'Bye') → 'HiByeByeHi'
make_abba('Yo', 'Alice') → 'YoAliceAliceYo'
make_abba('What', 'Up') → 'WhatUpUpWhat'
source: https://codingbat.com/prob/p182144
"""
def make_abba(a, b):
"""Return the result of putting them together in the order abba.
Given two strings, a and b, return the
result of putting them together in the order abba.
e.g. "Hi" and "Bye" returns "HiByeByeHi".
"""
return f"{a}{b*2}{a}"
def main():
"""Test the make_abba function."""
assert make_abba('Yo', 'Alice') == 'YoAliceAliceYo'
assert make_abba('Hi', 'Bye') == 'HiByeByeHi'
assert make_abba('What', 'Up') == 'WhatUpUpWhat'
assert make_abba('aaa', 'bbb') == 'aaabbbbbbaaa'
assert make_abba('x', 'y') == 'xyyx'
assert make_abba('x', '') == 'xx'
assert make_abba('', 'y') == 'yy'
assert make_abba('Bo', 'Ya') == 'BoYaYaBo'
assert make_abba('Ya', 'Ya') == 'YaYaYaYa'
print('Passed.')
if __name__ == "__main__":
main()
| false |
c443a93bfeba9e5162d8b5af704b8effcf32f61b | christopher-burke/warmups | /python/projecteuler/src/multiples_of_3_and_5.py | 522 | 4.25 | 4 | #!/usr/bin/env python3
"""Multiples of 3 and 5.
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. (n < 1000)
problem source: https://projecteuler.net/problem=1
"""
def main():
"""Return the sum of all the multiples of 3 or 5 below 1000."""
return sum([i for i in range(2, 1000)
if i % 3 == 0 or i % 5 == 0])
if __name__ == "__main__":
print(main())
| true |
9c32a48f1ae0e465a172186b0171b6decaa6baa4 | christopher-burke/warmups | /python/misc/sort_array_012.py | 1,047 | 4.28125 | 4 | #!/usr/bin/env python3
"""Sort an array of 0s, 1s and 2s
Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order.
Input:
The first line contains an integer 'T' denoting the total number of test cases. Then T testcases follow. Each testcases contains two lines of input. The first line denotes the size of the array N. The second lines contains the elements of the array A separated by spaces.
Output:
For each testcase, print the sorted array.
Constraints:
1 <= T <= 500
1 <= N <= 106
0 <= Ai <= 2
Example:
Input :
2
5
0 2 1 2 0
3
0 1 0
Output:
0 0 1 2 2
0 0 1
"""
def sort_array_012(array):
"""Sort an array of 0s, 1s and 2s."""
# Dictionary of numbers encountered
data = {0: 0, 1: 0, 2: 0}
output = ''
for x in array:
data[x] = data[x] + 1
for key, value in data.items():
output += f'{key},' * value
return output.split(',')[:-1]
if __name__ == "__main__":
print(sort_array_012([0, 2, 1, 2, 0, ]))
print(sort_array_012([0, 1, 0, ]))
| true |
20c450a8b4e2a63b8636ce73e57f7d575592504a | christopher-burke/warmups | /python/misc/is_prime.py | 1,083 | 4.34375 | 4 | #!/usr/bin/env python3
"""Is the number Prime.
Source:
https://edabit.com/challenge/G7KG4kaABpeYu2RBR
"""
def divisors(n: int):
"""Return list of divisors.
Using list comprehension.
n : int
returns a list of divisor(s).
"""
return [divisor for divisor in range(1, n+1) if n % divisor == 0]
def prime(n: int):
"""Determine if a number is prime.
Prime numbers are divisible by 1 and itself.
n: int
returns True if prime and False if not prime.
"""
return [1, n] == divisors(n)
is_prime = prime
def main():
"""Run sample is_prime functions."""
assert is_prime(1) is False
assert is_prime(2) is True
assert is_prime(3) is True
assert is_prime(4) is False
assert is_prime(5) is True
assert is_prime(6) is False
assert is_prime(7) is True
assert is_prime(8) is False
assert is_prime(9) is False
assert is_prime(10) is False
assert is_prime(11) is True
assert is_prime(102) is False
assert is_prime(103) is True
print('Passed.')
if __name__ == "__main__":
main()
| true |
a8501171894896c80eff3b30e53bfe10f7f0c932 | christopher-burke/warmups | /python/codingbat/src/makes_10.py | 620 | 4.28125 | 4 | #!/usr/bin/env python3
"""Makes 10.
Given 2 ints, a and b, return True
if one if them is 10 or if their sum is 10.
"""
def makes10(a: int, b: int) -> bool:
"""Determine if the sum or if either a,b is 10."""
return (a + b == 10 or a == 10 or b == 10)
if __name__ == "__main__":
assert makes10(9, 10) is True
assert makes10(9, 9) is False
assert makes10(1, 9) is True
assert makes10(10, 1) is True
assert makes10(10, 10) is True
assert makes10(8, 2) is True
assert makes10(8, 3) is False
assert makes10(10, 42) is True
assert makes10(12, -2) is True
print('Passed')
| false |
25f1af7a852a3d45cb11ce48ec8c40e5a283e175 | christopher-burke/warmups | /python/misc/array_three_sum.py | 983 | 4.40625 | 4 | #!/usr/bin/env python3
"""Determine if the sum of three integers is equal to the given value.
Given an array of integers and a value, determine if there are any three
integers in the array whose sum equals the given value.
"""
def sum_three(array, target_sum):
"""Determine if three intergers equal to the target_sum."""
_array = sorted(array)
for index in range(len(_array)-2):
left_pointer = index + 1
right_pointer = len(_array) - 1
while (left_pointer < right_pointer):
_sum = sum([_array[index], _array[left_pointer],
_array[right_pointer]])
if(_sum == target_sum):
return True
elif (_sum < target_sum):
left_pointer += 1
else:
right_pointer -= 1
return False
if __name__ == "__main__":
print(sum_three(array=[7, 2, 9, 8, 1], target_sum=11))
print(sum_three(array=[1, 4, 33, 6, 10, 8], target_sum=22))
| true |
5eef1637696f3a2e30e80f3291980d4afb6ef4c8 | christopher-burke/warmups | /python/misc/multiple_of_one_hundred.py | 692 | 4.40625 | 4 | #!/usr/bin/env python3
"""Multiple of 100.
Create a function that takes an integer and returns
True if it's divisible by 100, otherwise return False.
Source:
https://edabit.com/challenge/NebFhjXTn8NEbhYXY
"""
def divisible(num):
"""Divisible by 100 is True, otherwise return False."""
return num % 100 == 0
def main():
"""Run sample divisible functions. Do not import."""
assert divisible(1) is False
assert divisible(100) is True
assert divisible(1000) is True
assert divisible(111000) is True
assert divisible(-1) is False
assert divisible(0) is True
assert divisible(-100) is True
print('Passed.')
if __name__ == "__main__":
main()
| true |
ce774311ce350ccce7d29bc94b594d182971a0f4 | christopher-burke/warmups | /python/misc/whos_the_oldest.py | 2,933 | 4.125 | 4 | #!/usr/bin/env python3
"""Find the oldest. Who's The Oldest?
Given a dictionary containing the names and ages of a group of people,
return the name of the oldest person.
Source:
https://edabit.com/challenge/3A6x5GjWmT4t8pssL"""
def oldest(people: dict) -> str:
"""Find the oldest person in people dict."""
oldest_age = max(people.values())
oldest_person = [person for person,
age in people.items()
if age == oldest_age][0]
return oldest_person
def main():
"""Run sample oldest functions. Do not import."""
assert oldest({'Charlotte': 53, 'Oliver': 15, 'Henry': 18,
'Gabriel': 46, 'Violet': 13}) == "Charlotte"
assert oldest({'Grayson': 50, 'Imogen': 63, 'Logan': 21,
'Daniel': 64, 'Rory': 19}) == "Daniel"
assert oldest({'Josh': 78, 'Adam': 63, 'Aria': 65,
'Grace': 51, 'Bella': 37}) == "Josh"
assert oldest({'Alex': 9, 'Jayden': 18, 'Julia': 43,
'Penelope': 32, 'Ella': 34}) == "Julia"
assert oldest({'Sam': 65, 'Joseph': 60, 'Mia': 41,
'Thomas': 31, 'Rebecca': 5}) == "Sam"
assert oldest({'Eden': 64, 'Archie': 18, 'Olivia': 32,
'Kai': 84, 'Harry': 14}) == "Kai"
assert oldest({'Anna': 67, 'Elijah': 10, 'Cole': 31,
'Andrew': 24, 'Elliot': 77}) == "Elliot"
assert oldest({'Innes': 77, 'Lilly': 11, 'Hallie': 41,
'Nina': 66, 'Ryan': 9}) == "Innes"
assert oldest({'Isla': 73, 'Elsie': 6, 'Frankie': 36,
'Robbie': 75, 'Kayla': 9}) == "Robbie"
assert oldest({'Jack': 64, 'Jacob': 33, 'Tommy': 17,
'Finn': 5, 'Isaac': 13}) == "Jack"
assert oldest({'Carson': 81, 'Charlie': 33, 'Riley': 28,
'Maria': 39, 'Sadie': 67}) == "Carson"
assert oldest({'Amy': 70, 'Owen': 11, 'Matilda': 64,
'Lexi': 37, 'Lena': 26}) == "Amy"
assert oldest({'Lola': 45, 'Tyler': 23, 'Hope': 4,
'Phoebe': 86, 'Freya': 44}) == "Phoebe"
assert oldest({'Hollie': 48, 'Harris': 24, 'Ava': 72,
'Alfie': 9, 'Louis': 47}) == "Ava"
assert oldest({'Erica': 32, 'Eve': 82, 'Harper': 74,
'Summer': 38, 'Ben': 72}) == "Eve"
assert oldest({'Michael': 63, 'Jessica': 65, 'Reuben': 25,
'Aiden': 82, 'Emily': 18}) == "Aiden"
assert oldest({'Brooke': 8, 'Lucy': 44, 'Cooper': 33,
'Ellie': 82, 'Millie': 7}) == "Ellie"
assert oldest({'Piper': 10, 'Quinn': 62, 'David': 20,
'John': 61, 'Noah': 17}) == "Quinn"
assert oldest({'Cara': 5, 'Max': 81, 'Lucas': 62,
'Sophie': 71, 'Amelia': 79}) == "Max"
assert oldest({'Leo': 29, 'Clara': 8, 'Florence': 69,
'Lewis': 38, 'James': 47}) == "Florence"
print('Passed.')
if __name__ == "__main__":
main()
| true |
123c2e9e78e6cfa5c6703203aa1dd95ecfc1121e | christopher-burke/warmups | /python/misc/max_of_all_subarrays_of_size_k.py | 659 | 4.125 | 4 | #!/usr/bin/env python3
"""Maximum of all subarrays of size k."""
from itertools import islice
def maximum_of_all_subarrays(array, k: int):
"""Find all the maximum values of all subarrays of size k."""
maximum_of_all = []
for i in range(len(array)):
subarray = list(islice(array, i, k+i))
if len(subarray) == k:
maximum_of_all.append(max(subarray))
else:
break
return tuple(maximum_of_all)
if __name__ == "__main__":
print(maximum_of_all_subarrays(array=(1, 2, 3, 1, 4, 5, 2, 3, 6,), k=3))
print(maximum_of_all_subarrays(
array=(8, 5, 10, 7, 9, 4, 15, 12, 90, 13,), k=4))
| false |
e3024d9e0f631933edc7a261262dfce6b7605230 | christopher-burke/warmups | /python/misc/divisible_by_five.py | 823 | 4.4375 | 4 | #!/usr/bin/env python3
"""Check if an Integer is Divisible By Five.
Create a function that returns True if an integer is divisible by 5,
and false otherwise.
Source:
https://edabit.com/challenge/49pyDP8dE3pJ2dYMW
"""
def divisible_by_five(n: int) -> bool:
"""Return True if an integer is divisible by 5, and false otherwise."""
if n % 5 > 0:
return False
return True
def main():
"""Run sample divisible_by_five functions. Do not import."""
assert divisible_by_five(7) is False
assert divisible_by_five(5) is True
assert divisible_by_five(15) is True
assert divisible_by_five(33) is False
assert divisible_by_five(-18) is False
assert divisible_by_five(999) is False
assert divisible_by_five(2) is False
print('Passed.')
if __name__ == "__main__":
main()
| true |
95ed5517405954ce075c1d693474d6a4c1609db0 | christopher-burke/warmups | /python/misc/baseball.py | 1,648 | 4.375 | 4 | #!/usr/bin/env python3
"""Baseball stat formulas.
Collection of baseball formulas used for statistical analysis.
"""
from fractions import Fraction
def innings(innings: str):
"""Convert the partial innings pitched (outs) to a fraction.
Baseball represents the thirds of innings in the following:
* 0.1 = 1 of the 3 outs made, meaning 1/3.
* 0.2 = 2 of the 3 outs made, meaning 2/3.
These fractions need to be converted properly in order to be processed.
"""
try:
innings, fraction = innings.split('.')
fraction = Fraction(int(fraction), 3)
return int(innings) + fraction
except ValueError:
return int(innings)
def era(innings_pitched: float, er: int, total_innings: int=9) -> float:
"""Calculate a baseball pitcher's ERA.
ERA = ('earned runs' / 'innings pitched') * 'total innings'
er = Earned Runs
"""
ERA = (er * total_innings) / innings(str(innings_pitched))
return round(float(ERA), 2)
def whip(innings_pitched: float, bb: int, h: int) -> float:
"""Calculate a baseball pitcher's WHIP.
WHIP = (BB + H) / IP
bb = Walks / Base on balls
h = hits
"""
WHIP = (bb + h) / innings(str(innings_pitched))
return round(float(WHIP), 2)
def main():
"""Run era and whip samples."""
print(era(innings_pitched=6.0, er=3))
print(era(innings_pitched=6.2, er=3))
print(era(innings_pitched=154.1, er=52))
print(whip(innings_pitched=202.1, bb=43, h=190))
print(whip(innings_pitched=140.0, bb=38, h=130))
print(whip(innings_pitched=154.1, bb=38, h=148))
if __name__ == "__main__":
main()
| true |
17a186f44b00655fbc89c67b8791b09e25cf9827 | christopher-burke/warmups | /python/misc/the_farm_problem.py | 647 | 4.15625 | 4 | #!/usr/bin/env python3
"""The Farm Problem.
You've got chickens (2 legs), cows (4 legs) and pigs (4 legs) on your farm.
Return the total number of legs on your farm.
Source:
https://edabit.com/challenge/QzXtDnSZL6y4ZcEvT
"""
def animals(chickens: int, cows: int, pigs: int) -> int:
"""Return the total number of legs on your farm."""
return sum([(chickens * 2), (cows * 4), (pigs * 4), ])
def main():
"""Run sample animals functions. Do not import."""
assert animals(5, 2, 8) == 50
assert animals(3, 4, 7) == 50
assert animals(1, 2, 3) == 22
assert animals(3, 5, 2) == 34
if __name__ == "__main__":
main()
| true |
3a5217423d3d179efde2a0003e4b44555ed8d791 | christopher-burke/warmups | /python/codingbat/src/hello_name.py | 997 | 4.25 | 4 | #!/usr/bin/env python3
"""Hello Name.
Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!".
hello_name('Bob') → 'Hello Bob!'
hello_name('Alice') → 'Hello Alice!'
hello_name('X') → 'Hello X!'
source: https://codingbat.com/prob/p115413
"""
def hello_name(name: str) -> str:
"""Return `Hello name!`.
:return:`Hello name!`
"""
return f'Hello {name}!'
def main():
"""Main tests for hello_name."""
assert hello_name('Bob') == 'Hello Bob!'
assert hello_name('Alice') == 'Hello Alice!'
assert hello_name('X') == 'Hello X!'
assert hello_name('Dolly') == 'Hello Dolly!'
assert hello_name('Alpha') == 'Hello Alpha!'
assert hello_name('Omega') == 'Hello Omega!'
assert hello_name('Goodbye') == 'Hello Goodbye!'
assert hello_name('ho ho ho') == 'Hello ho ho ho!'
assert hello_name('xyz!') == 'Hello xyz!!'
assert hello_name('Hello') == 'Hello Hello!'
print('Passed.')
if __name__ == "__main__":
main()
| false |
386f07bac648330b1cc983624a3b5dca2595cea6 | DdNn708/learnpython | /week1/on_the_lesson1/bot.py | 1,185 | 4.15625 | 4 | # dictionary = {}
#
# dictionary['first_name'] = "Sasha"
# dictionary['last_name'] = 'Ozerov'
# dictionary['age'] = 12
# dictionary['city'] = 'Moscow'
#
# for key, value in dictionary.items():
# print(f'{key} : {value}')
# dictionary = {}
#
# dictionary['Kat'] = 12
# dictionary['Vova'] = 14
# dictionary['Sara'] = 23
# dictionary['Karolina'] = 44
#
# for name, num in dictionary.items():
# print(name.lower() + ' likes number ' + str(num))
#
# dictionary = {}
#
# dictionary['Тикет'] = "Это такая штука, в которой пишем задание"
# dictionary['Дескрипшн'] = "Это описание к задаче"
#
# for k, v in dictionary.items():
# print(k + "\n" + v + "\n")
favorite_languages = {
'jen': 'python',
'paul': 'c',
'komi': 'php',
'ki': 'haskel',
'noi': '',
}
for name, language in favorite_languages.items():
if language:
print("Thx for your answer " + name.title() +
" Now we know that your favorite language is " + language.title())
else:
favorite_languages[name] = input("What's your favorite language " + name.title() + "? ")
print(favorite_languages)
| false |
a809430e2673317efe9edcfcb4ea3dd5e66893d4 | manamster/Chapter-2-Programs | /mileage.py | 806 | 4.40625 | 4 | #Hyder Rizvi and Calvin Comstock-Fisher
#9/24/20
#People We Helped: Nobody
#People that Helped us: Nobody
#Mileage Calculator
#Step 1. Ask what car the the user has?
Car = input("What type of car do you own? ")
#Step 2. Ask how many gallons it can hold
Gallons = float(input("How many gallons of gas can it hold? "))
#Step 3: Ask how far it can travel per mile
Mileage = float(input("How many miles per gallon can it travel? "))
#Step 4: Ask price per gallon
Cost = float(input("What is the cost of a gallon of gas? "))
#Step 5: Find price of full tank
Tank = Gallons*Cost
#Step 6: Find distance that it can travel on a full tank
Distance = Mileage*Gallons
#Step 7: Tell user the programs findings
print("The",Car,"can travel",Distance,"miles.")
print("{:}${:,.2f}{:}".format("A full tank would cost ",Tank,".")) | true |
e5cabbaaa683db8eeab8fbb4dd8ebdce6c33b79f | jahidul39306/100-Days-Of-Python | /Day 19/Turtle_Race/main.py | 1,010 | 4.3125 | 4 | from turtle import Turtle, Screen
import random
turtle_colors = ["red", "green", "blue", "yellow", "purple", "black"]
turtle_position = [-100, -60, -20, 20, 60, 100]
turtles_list = []
screen = Screen()
screen.setup(width=500, height=400)
user_input = screen.textinput(title="Make Your Bet", prompt="Which turtle will win the race? Enter a color: ")
for turtle_index in range(0, 6):
new_turtle = Turtle()
new_turtle.shape("turtle")
new_turtle.penup()
new_turtle.color(turtle_colors[turtle_index])
new_turtle.goto(-230, turtle_position[turtle_index])
turtles_list.append(new_turtle)
race_on = True
while race_on:
for turtle in turtles_list:
turtle.forward(random.randint(0, 10))
if turtle.xcor() > 222:
winner = turtle.pencolor()
race_on = False
break
if winner == user_input:
print(f"The winner is {winner}")
print("You won!!!")
else:
print(f"The winner is {winner}")
print("you lost")
screen.exitonclick()
| true |
325e1ae84d9aa9605a422e3a43df7d3cd28e4b39 | HananeKheirandish/Assignment-4 | /Number-Of-Words.py | 236 | 4.15625 | 4 | def num_of_words(s):
num = 0
for c in s:
if c == ' ':
num += 1
print("number of words in your sentence is: " , num + 1)
sentence = input("please enter your sentence: ")
num_of_words(sentence) | true |
a05163e2c05616f7ff25de3c39e7159a1d9c64ae | noreallyimfine/Sorting | /src/recursive_sorting/recursive_sorting.py | 1,792 | 4.15625 | 4 | def merge(arrA, arrB):
# Get length of end array
elements = len(arrA) + len(arrB)
# Create empty array to be filled
merged_arr = [0] * elements
# counter of index to insert at
cur_index = 0
# as long as both arrays still have elements
while len(arrA) > 0 and len(arrB) > 0:
# compare the first elements, and put the smaller in the merged array
if arrA[0] < arrB[0]:
merged_arr[cur_index] = arrA.pop(0)
cur_index += 1
else:
merged_arr[cur_index] = arrB.pop(0)
cur_index += 1
# when one array runs out of elements
# find the array thats not empty
# one at a time, insert into merged array
if len(arrA) == 0:
for num in arrB:
merged_arr[cur_index] = num
cur_index += 1
elif len(arrB) == 0:
for num in arrA:
merged_arr[cur_index] = num
cur_index += 1
return merged_arr
# TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort(arr):
# TO-DO
# base case, array len 0 or 1
if len(arr) < 2:
return arr
# split array in half
else:
mid = len(arr) // 2
first = arr[:mid]
second = arr[mid:]
# implement recursion to split until base case
first = merge_sort(first)
second = merge_sort(second)
# merge em back up
arr = merge(first, second)
return arr
# STRETCH: implement an in-place merge sort algorithm
def merge_in_place(arr, start, mid, end):
# TO-DO
return arr
def merge_sort_in_place(arr, l, r):
# TO-DO
return arr
# STRETCH: implement the Timsort function below
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
def timsort(arr):
return arr
| true |
92675c271abdfb6e7292cf2f95f161468148e62e | anectto/basicpythonprogramming | /ch17-graphical-user-interfaces/2-challenge.py | 2,899 | 4.15625 | 4 | # 17.2 - Challenge: Use GUI Elements to Help a User Modify Files
# Solution to challenge
# save part of a PDF based on a user-supplied page range using a GUI
import easygui as gui
from PyPDF2 import PdfFileReader, PdfFileWriter
# let the user choose an input file
input_file_path = gui.fileopenbox("", "Select a PDF to trim...", "*.pdf")
if input_file_path is None: # exit on "Cancel"
exit()
# get the page length of the input file
input_file = PdfFileReader(input_file_path)
total_pages = input_file.getNumPages()
# let the user choose a beginning page
page_start = gui.enterbox(
"Enter the number of the first page to use:", "Where to begin?"
)
if page_start is None: # exit on "Cancel"
exit()
# check for possible problems and try again:
# 1) input page number isn't a (non-negative) digit
# or 2) input page number is 0
# or 3) page number is greater than total number of pages
while (
not page_start.isdigit()
or page_start == "0"
or int(page_start) > total_pages
):
gui.msgbox("Please provide a valid page number.", "Whoops!")
page_start = gui.enterbox(
"Enter the number of the first page to use:", "Where to begin?"
)
if page_start is None: # exit on "Cancel"
exit()
# let the user choose an ending page
page_end = gui.enterbox(
"Enter the number of the last page to use:", "Where to end?"
)
if page_end is None: # exit on "Cancel"
exit()
# check for possible problems and try again:
# 1) input page number isn't a (non-negative) digit
# or 2) input page number is 0
# or 3) input page number is greater than total number of pages
# or 4) input page number for end is less than page number for beginning
while (
not page_end.isdigit()
or page_end == "0"
or int(page_end) > total_pages
or int(page_end) < int(page_start)
):
gui.msgbox("Please provide a valid page number.", "Whoops!")
page_end = gui.enterbox(
"Enter the number of the last page to use:", "Where to end?"
)
if page_end is None: # exit on "Cancel"
exit()
# let the user choose an output file name
output_file_path = gui.filesavebox("", "Save the trimmed PDF as...", "*.pdf")
while input_file_path == output_file_path: # cannot use same file as input
gui.msgbox(
"Cannot overwrite original file!", "Please choose another file..."
)
output_file_path = gui.filesavebox(
"", "Save the trimmed PDF as...", "*.pdf"
)
if output_file_path is None:
exit() # exit on "Cancel"
# read in file, write new file with trimmed page range and save the new file
output_PDF = PdfFileWriter()
# subtract 1 from supplied start page number to get correct index value
for page_num in range(int(page_start) - 1, int(page_end)):
page = input_file.getPage(page_num)
output_PDF.addPage(page)
with open(output_file_path, "wb") as output_file:
output_PDF.write(output_file)
| true |
71fb158ef6a4a34088997c8e5fd8582749ea9178 | RongShen99/Google-python-work-sample | /src/video_playlist.py | 696 | 4.125 | 4 | """A video playlist class."""
class Playlist:
"""A class used to represent a Playlist."""
def __init__(self, playlist_name):
self.name = playlist_name
self.videos = [] # list of video_ids
def add_video(self, video_id):
self.videos.append(video_id)
# return True on success, False otherwise
def remove_video(self, video_id):
try:
self.videos.remove(video_id)
return True
except ValueError:
print("Cannot remove video from "+self.name+": Video is not in playlist")
return False
def get_name(self):
return self.name
def get_videos(self):
return self.videos
| true |
3eb2cebdf9d6a7799b9742f531b361cb348fd167 | abhishek17feb/python | /Python Object and Data Structure Basics/String formatting.py | 1,732 | 4.28125 | 4 | # Injecting a varible into a String is called Interpolation. It is very different from String Concatination
#1. .format() method
#2. f-strings Formated String literals
#1. .format() method
#Syntax - 'My String goes {}'.format('HERE') -> So 'HERE' will be inserted in the placeholder {}. Multiple
#placeholders could also be used.
myName = 'Abhishek {}'
myFullName = myName.format('Roy')
print(myFullName) #Abhishek Roy
multiplePlaceholders = 'We want {} and {} to live a good life'
placeholderInsertedStr = multiplePlaceholders.format('Money','Honey')
print(placeholderInsertedStr) #We want Money and Honey to live a good life
# The placeholder holder could be give indexes and alias of the inserted String
myIndexPlaceholder = 'We could use {1}, to insert the {0}'
indexInserted = myIndexPlaceholder.format('STRING','INDEX')
print(indexInserted)
aliasPlaceholder = 'My little {dog} and {cat} are very naughty'
aliasInserted = aliasPlaceholder.format(dog = 'DOG',cat = 'CAT')
print(aliasInserted)
## Formatting a floating point
##Syntax -> {value:width.precisionf} -> Here width is the number of white spaces before the number gets inserted
## precision is the number of places after the decimal point
myFloatingNumber = 200.5689
print('My floating number {floating:1.2f}'.format(floating = myFloatingNumber)) #My floating number 200.57
print('My floating number {floating:1.1f}'.format(floating = myFloatingNumber)) #My floating number 200.6
#2. f-strings Formated String literals
#Syntax is name = 'ABHISHEK' -> f"Here is my String {name}" : Here is my String ABHISHEK
name = 'ABHISHEK'
fString = f"My name is {name}"
print(fString) #My name is ABHISHEK
#So instead of name.format(<text>) we could use place a 'f' before
| true |
3287c31855e793d00afea9f811938908f0ff3ebe | mocox/PY-Data-Structures | /binarySearch.py | 802 | 4.125 | 4 | ## Binary Searching, only works on sorted array
## Big O
## Best Average Worst
## O(1) (Log n) (log n)
## O(log n) almost equals O(1)
import math
def binary_search(arr, which):
start = 0
end = len(arr) - 1
middle = math.floor((start + end) / 2)
## loop through array
while arr[middle] != which and start <= end:
## print the varaiables
print(start, middle, end)
## check the logic and change start and end as appropriate
if which < arr[middle]:
end = middle - 1
else:
start = middle + 1
## get a new middle
middle = math.floor((start + end) / 2)
return middle if arr[middle] == which else -1
index = binary_search([2,3,5,6,9,13,15,28,30], 13)
print("index is :-> ", index) | true |
ee06ca03f422c2b9fe40d87de5e92c60a0a8a913 | PushkarrajPujari/Python_Basics | /me.pujari/Statements/basic_if_elif_statement.py | 664 | 4.25 | 4 | # Demonstrating if elsif with exam marks example
marks = eval(input("Enter your marks"))
if marks < 0 or marks > 100:
print("Invalid marks , Please enter valid marks")
elif 0 <= marks < 35:
print("Sorry , You Have failed")
elif 35 <= marks < 50:
print("You have cleared the exam with Passed Class")
elif 50 <= marks < 60:
print("You have cleared the exam with Second Class")
elif 60 <= marks < 75:
print("You have cleared the exam with First Class")
elif 75 <= marks < 90:
print("You have cleared the exam with distinction")
elif 90 <= marks <= 100:
print("You have cleared the exam with merit")
else:
print("Something wrong ....")
| true |
34039c720a78b42270d90da5240fd570ed674a7c | Kelkinkar/learnpy | /input.py | 564 | 4.25 | 4 | """we use input() funtion to get input from the user. Takes evrything to be a string and you have to use int()
function to use integers."""
name = input('What is your name? : ')
age = int(input('What is your age? : '))
if age <= 25:
print(f'hello {name}, you are age {age} hence you cannot access this service. Try to access gurukids and sing babyshark')
elif age >= 26 and age <= 30:
print(f'hello {name}, you are of age motherfucker.. enjoy while it lasts')
elif age >31:
print(f'hello {name}, you are too old to access this service, go make some kids ')
| true |
e2cae1340f5b503bb8394f693a2dba5c2b2e03ff | dannyangeleno/test | /DANGEL_DSC510/hello_world.py | 1,892 | 4.4375 | 4 | # DSC_510 Assignment
# Hello World Assignment
# Python 3.8
# Author : Danny Angel
greeting = 'Hello cruel world' # This section is defining phrases to be used later
initial_farewell = 'This is the end of my program'
final_farewell = 'Goodbye cruel world'
undead_cpu = 'I am not really dead or alive. I am a computer program.'
print('Hello there.') # Program says hi
print('What do people call you?') # Program asks your name
name = input() # Definition and prompt for answer
print('That is a funny name ' + name) # Program teases you
print('Are you alive or dead ' + name + '?') # Program asks another question
status = input() # Hopefully, you're alive but the program asks anyway
print(status + ' huh. Me too, in a sense') # Program acts relatable
if status == 'dead' or status == 'Dead' or status == 'DEAD': # Dead branch (includes different capitlizations)
print('Well, technically if you are typing you are not dead')
print(undead_cpu)
elif status == 'alive' or status == 'Alive' or status == 'ALIVE': # Living branch
print(undead_cpu)
else: # Zombie branch
print('So you are not dead and you are not alive, huh?')
print(undead_cpu)
print('I do not meet the classical definition of alive but I can do things if I am programmed to, like this:')
print(greeting) # Emo program says hi
print(initial_farewell)
print(final_farewell) # Emo program says bye
| true |
78671e6b4de6da672ecc339e40c3cc71bfec0dd6 | AaronWWK/Courses-Taken | /6.00.1x/Mid term/Problem_6.py | 1,215 | 4.25 | 4 | def deep_reverse(L):
""" assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
Lcopy = L[:]
L = []
for i in range(len(Lcopy),0,-1): ##一定要写步长
L.append(Lcopy[i-1]) ##把整体倒叙
#print(L)
Lcopy2 = L[:] ## 将L复制到Lcopy2
for item in Lcopy2:
if type(item) == list: ##判断item 是不是list 如果不是就结束
#print(item)
L.remove(L[0]) ## ()内是要移除的对象 因为L不是空的list,所以将原来在前面的几项移除,每次循环,都删除第一个
L.append(deep_reverse(item)) ##加上倒置之后的每一个小项
# Lcopy2 = L[:]
# L=[] ### 如果采用这种方式,当list中的项不是 list的时候, L会被换成空值,使得最终结果也是空值
# for item in Lcopy2:
# if type(item) == list:
# L.append(deep_reverse(item))
#print(L)
return L
L = [[1, 2], [3, 4], [5, 6, 7]]
L = deep_reverse(L)
#print(deep_reverse(L))
print(L)
| false |
3cab298c03cf535ebd6e5c95e2c0385bfe798256 | ecwolf/Programming | /Python/shreyamodi1999_Factorial.py | 359 | 4.375 | 4 | def factorial(n):
if n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
# Driver Code
num = int(input("Enter a number: "))
if num >= 0:
print("Factorial of",num,"is", factorial(num))
else:
print("Can not compute factorial of negative number") | true |
ae869e5037c31d8a507162149f7687fe1701d27c | ecwolf/Programming | /Python/havanoor_StrongNumber.py | 268 | 4.21875 | 4 | from math import factorial
val=(input("Enter the number"))
temp=(val)
check=0
for i in val:
check+=factorial(int(i))
if check==int(val):
print("The number is a strong number")
else:
print("No the number is not a strong number")
| true |
e68bff3b98ab88b60392ea48c5dddd5b751cde03 | sineczek/PythonSrednioZaawansowany | /Klasy/29_class_and_instance.py | 2,223 | 4.125 | 4 | class Car:
numberOfCars = 0 #zmienne na poziomie classy
listOfCars = []
def __init__(self, brand, model, isAirBagOK, isPaintingOK, isMechanicalOK):
self.brand = brand
self.model = model
self.isAirBagOK = isAirBagOK
self.isPaintingOK = isPaintingOK
self.isMechanicalOK = isMechanicalOK
Car.numberOfCars +=1
Car.listOfCars.append(self)
def IsDamged(self):
return (self.isAirBagOK and self.isPaintingOK and self.isMechanicalOK)
def GetInfo(self):
print("{} {}".format(self.brand, self.model).upper())
print('Air Bag - ok - {}'.format(self.isAirBagOK))
print('Painting - ok - {}'.format(self.isPaintingOK))
print('Mechanic - ok - {}'.format(self.isMechanicalOK))
print('-'*20)
print('Class level variables before creating instances: ', Car.numberOfCars, Car.listOfCars)
car_01 = Car('BMW', '320D (E91)', True, True, True) #instancje klasy
car_02 = Car('Tesla','Model S', True, False, True)
print('Class level variables after creating instances: ', Car.numberOfCars, Car.listOfCars)
print('ID of a class is: ', id(Car))
print('ID of instances are: ', id(car_01), id(car_02))
print('Check if object belongs to class using "isinstance": ', isinstance(car_01, Car)) #czy instancja powstała w oparciu o classę
print('Check if object belongs to class using "type": ', type(car_01) is Car) #czy instancja powstała w oparciu o classę
print('Check if object belongs to class using "__class__": ', car_01.__class__) #w oparciu o jaką classę powstała instancja
print('List of instances attributes with values using "vars": ', vars(car_01)) #pozwala zobaczyć jak zbudowany jest obiekt w formie słownika
print('List of class attributes with values using "vars": ', vars(Car)) #pozwala zobaczyć jak zbudowany jest classa w formie słownika
print('List of instances attributes with values using "dir": ', dir(car_01)) #kolejne metody dla instancji
print('List of class attributes with values using "dir": ', dir(Car)) #kolejne metody dla classy
print('Value taken from instance: ', car_01.numberOfCars, 'Value taken from class: ', Car.numberOfCars)
print('='*30)
| false |
3530322f5427b7cca787a98767603968848fb2fc | sineczek/PythonSrednioZaawansowany | /Klasy/26_classes_lab.py | 1,399 | 4.375 | 4 | '''Zmień go stosując następujące techniki:
zmień definicję zmiennych na słownik z właściwościami
zmień definicję funkcji, tak aby przyjmowała jeden parametr i nadal wyświetlała informacje przekazane parametrem
utwórz listę tortów i przechodząc przez nią wyświetl informacje zwracane przez funkcje show_cake_info'''
cake_01_taste = 'vanilia'
cake_01_glaze = 'chocolade'
cake_01_text = 'Happy Brithday'
cake_01_weight = 0.7
cake_02_taste = 'tee'
cake_02_glaze = 'lemon'
cake_02_text = 'Happy Python Coding'
cake_02_weight = 1.3
def show_cake_info(taste, glaze, text, weight):
print('{} cake with {} glaze with text "{}" of {} kg'.format(
taste, glaze, text, weight))
show_cake_info(cake_01_taste, cake_01_glaze, cake_01_text, cake_01_weight)
show_cake_info(cake_02_taste, cake_02_glaze, cake_02_text, cake_02_weight)
print ('='*30)
cake_01 = {'taste' : 'vanilia',
'glaze' : 'chocolade',
'text' : 'Happy Brithday',
'weight' : 0.7 }
cake_02 = {'taste' : 'tee',
'glaze' : 'lemon',
'text' : 'Happy Python Coding',
'weight' : 1.3 }
def show_cake_info(a_cake):
print('{} cake with {} glaze with text "{}" of {} kg'.format(
a_cake['taste'], a_cake['glaze'], a_cake['text'], a_cake['weight']))
cakes = [cake_01, cake_02]
for a_cake in cakes:
show_cake_info(a_cake)
| false |
77acb3ea1f2835bffe9c9e125c4f187f2eebd2b0 | pvperez1/lis161BridgingProgram | /01_week/exer9.py | 568 | 4.21875 | 4 | # Write another program that prompts
# for a list of numbers as the previous
# exercise and at the end prints out both
# the maximum and minimum of the numbers
# instead of the average.
sum = 0
count = 0
max = None
min = None
while True:
num = input("Enter number: ")
if num == "done":
break
try:
num = float(num)
except:
print("Invalid input")
continue
sum += num
count += 1
if max is None or max < num:
max = num
if min is None or min > num:
min = num
print(sum, count, max, min)
| true |
12d4e34628175d2920926c14a50c888986fc7d0c | AnthonyLzq/Python_course | /class_07/exceptions.py | 2,076 | 4.21875 | 4 | import math
# Error codes:
# 1 -> correct number
# 2 -> it's not a number
# 3 -> the number is less than 0 or 0
def positive_number(number):
if number <= 0:
return 3
else:
return 1
def validate_number(possible_number):
try:
possible_number = float(possible_number)
except ValueError:
return 2
else:
return positive_number(possible_number)
def validate_triangle(triangle):
# if math.fabs(triangle[0] - triangle[1]) < triangle[2] \
# and triangle[2] < triangle[0] + triangle[1]:
# if math.fabs(triangle[1] - triangle[2]) < triangle[0] \
# and triangle[0] < triangle[1] + triangle[2]:
# if math.fabs(triangle[0] - triangle[2]) < triangle[1] \
# and triangle[1] < triangle[0] + triangle[2]:
# return True
p = 0
for i in range(0, 3):
p += triangle[i]
p /= 2
if triangle[0] < p and triangle[1] < p and triangle[2] < p:
return True
return False
def heron():
triangle = [0]*3 # triangle = [0, 0, 0]
validator = ''
p = 0
aux = 0
while True:
for index in range(0, len(triangle)):
while True:
triangle[index] = input('Type a number: ')
validator = validate_number(triangle[index])
if validator == 1:
triangle[index] = float(triangle[index])
break
elif validator == 2:
print('The value you\'ve just typed is not an number')
else:
print('The number is negative or 0.')
result = validate_triangle(triangle)
if result:
for i in range(0, 3):
p += triangle[i]
p /= 2
aux = p
for i in range(0, 3):
p *= (aux - triangle[i])
return math.sqrt(p)
else:
print('It isn\'t a triangle.\nTry again: ')
print(f'The triangle\'s area is: {heron():.5f}u².') | true |
8f3eeadc38699a650a2ff2844a427a9d1bd7e748 | madhumati14/python | /Assignment1_8.py | 281 | 4.1875 | 4 | #Write a program which accept number from user and print that number of “*” on screen.
#Input : 5
#Output : * * * * *
def Display(no):
for i in range(no):
print("*",end=" ");
def main():
no=int (input("enter number"));
Display(no);
if __name__=="__main__":
main();
| true |
700040f5c93275c036478cdbf0c0c7c74375f6b9 | SYUMJOBA/PE-class-work | /MakeText.py | 483 | 4.4375 | 4 |
import turtle
t = turtle.Turtle()
#This should work as a library that lets me print text on the screen
#So the central function is printLetter, it takes a letter as argument, then it loops it through a gigantic if-elif-else. I know that it's efficient as me at school (poorly) but it will do the job and as now I can't think of a better way, I'll maybe restructure the code later.
def printLetter(letter, scale = 1):
if letter == "a" or letter == "A":
t.begin_fill() | true |
5abaa84bf4111ef8fc28390b7774b419a6e54d59 | KChaseTramel/palindromeDetector | /pdDetector.py | 651 | 4.34375 | 4 | ##Palindrome Detector
def detector(input):
string = (str(input)).lower()
string = string.replace(" ", "")
string = "".join(e for e in string if e.isalnum())
reversedString = "".join(reversed(string))
if string == reversedString:
return True, reversedString, string
else:
return False, reversedString, string
results, revString, string = detector(raw_input("Test if your statement is a palidrome.\n"))
if results:
print "This is a palindrome; " + "%s is the reverse of %s." % (revString, string)
else:
print "This is not a palindrome; " + "%s is not the reverse of %s." % (revString, string) | true |
249619b9fbe2ad71b45b4f46c929b091a161c715 | CarlosRanderson/tarefa-aula-02 | /questao-02.py | 210 | 4.15625 | 4 | # 2.Faça um algoritmo que peça um valor e mostre na tela se o valor é positivo ou negativo.
valor = int(input("Digite um valor: "))
if valor <0:
print("Valor negativo")
else:
print("Valor positivo") | false |
3a2d77a1fe5ea92dee80de0eb08695592c7a6ae7 | laxmanlax/Programming-Practice | /Leetcode/151_reverse_words_in_a_string.py | 221 | 4.3125 | 4 | #!/usr/bin/env python
"""
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
"""
def reverseWords(self, s):
return " ".join(s.split()[::-1])
| true |
13e4afedc221be26e89d2500e3f432b97e28c78b | laxmanlax/Programming-Practice | /CodeEval/hard/string_permutations.py | 808 | 4.15625 | 4 | #!/usr/bin/env python
# Challenge description:
# Write a program which prints all the permutations of a string in alphabetical
# order. We consider that digits < upper case letters < lower case letters. The
# sorting should be performed in ascending order.
import sys
import fileinput
def permute_handler(a_str):
gen = getPermutations(a_str[:-1])
permutations = []
for combination in gen:
permutations.append(combination)
permutations.sort()
print ','.join(permutations)
def getPermutations(string):
if len(string) == 1:
yield string
else:
for i in xrange(len(string)):
for perm in getPermutations(string[:i] + string[i+1:]):
yield string[i] + perm
for line in fileinput.input():
permute_handler(line)
| true |
fd5173575e4786a668854c26393089f8276f916b | laxmanlax/Programming-Practice | /InterviewCake/27_reverse_words_inplace.py | 761 | 4.1875 | 4 | #!/usr/bin/env python
import string
def reverse_chars(s_lst, l, r):
while l < r:
s_lst[l], s_lst[r] = s_lst[r], s_lst[l]
l, r = l + 1, r - 1
return s_lst
def reverse_words(sentence):
sentence = list(sentence)
space = set(string.whitespace)
# Reverse all chars.
reverse_chars(sentence, 0, len(sentence) - 1)
l = 0
# (Re-)reverse chars in words.
# Go one further to ensure we reverse the last word too.
for i in xrange(len(sentence) + 1):
if i == len(sentence) or sentence[i] in space:
reverse_chars(sentence, l, i - 1)
l = i + 1
return ''.join(sentence)
assert reverse_words('Jack climbed the beanstalk') == 'beanstalk the climbed Jack'
print 'Test passed!'
| true |
a3d080813bdd7569b0dfeb75254237fecc4a7d9e | namitachaudhari119/My-learning | /Python/exception_eg.py | 1,236 | 4.1875 | 4 | #Program with no exception
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
# Program with exception
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
# Program for finally
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
#Program with argument exception
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz");
#User defined exceptions
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
def demo():
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
| true |
abb023adf3d5d21b1f845948bba102e6b490734d | danpinheiro97/indices-bioestatistica | /pythonProject/aula20.py | 668 | 4.59375 | 5 | # Funções
# O que é uma função? print(), int(), float(), len()
# O python possui essas funções de fábrica, mas você pode criar suas próprias funções
# Ao utilizar o método def(nome da função desejada):
# *especificar o que a função faz, exemplo: print('-'*30)
#Ao criar a função utilizando def, para chamar o que essa função faz, basta apenas digitar o nome que
# você deu para a função seguido de ().
# Exemplo:
def linha():
print('-'*30)
linha()
linha()
linha()
linha()
linha()
def mensagem(msg):
print('-'*30)
print(msg)
print('-'*30)
mensagem('Aluno')
mensagem('Professor')
mensagem('Hello World!')
| false |
62d5cbaa40bd678d1952cee5b096a953824aa382 | danpinheiro97/indices-bioestatistica | /pythonProject/Aula 17.py | 1,064 | 4.3125 | 4 | #Aula listas
#Listas ao contrário de tuplas são mutáveis
#Para iniciar uma lista usar []
#Métodos em listas:
#lista = ['Sorvete', 'Maça', 'Banana', 'Categoria']
#Substituir = lista[posição] = valor
#Adicionar = lista.append('valor') - dessa forma ele adiciona no fim da lista
#Adicionar = lista.insert(posição, 'valor') - dessa forma ele adiciona na posição definida
#deletar = lista.pop(posição) or () - o pop sozinho elimina o ultimo valor, mas pode definir uma posição ()
#deletar = lista.remove(valor)]
#Classificar = list.sort() - Organiza a lista
#Classificar ao contrário = list.sort(reverse=True)
#Contar elementos = len(listas)
#usando os métodos com if
#if 'valor' in lista:
#lista.remove('valor')
#Comando list() inicia uma lista a partir de sua entrada.
# valores = list(range(4,11))
num = [1,3,5,7,0,9,8,2]
print(num)
num[2] = 4
print(num)
num.append(56)
print(num)
num.insert(5, 'banana')
print(num)
num.pop()
print(num)
num.remove('banana')
print(num)
num.sort()
print(num)
num.sort(reverse=True)
print(num)
print(len(num)) | false |
204333cbe5c689f0579fb68dd7c26a0436337282 | Abhay2807/Python | /02Operators_use.py.py | 689 | 4.28125 | 4 | a=3
b=4
#Arithmetic operators
print("The value of 3+4 is:",3+4)
print("The value of 3-4 is:",3-4)
print("The value of 3*4 is:",3*4)
print("The value of 3/4 is:",3/4)
#Assignment operators
a=25
print(a)
a-=25
print(a)
a+=3
print(a)
a*=5
print(a)
a/=5
print(a)
#Comparison operators
c=(16>=16)
d=(16>15)
e=(16<15)
f=(16==16)
g=(16!=16)
i=(16>=3)
print(c)
print(d)
print(e)
print(f)
print(g)
print(i)
#Logical Operators
bool1=True
bool2=False
print("The value bool1 and bool2 is:",bool1 and bool2)
print("The value bool1 and bool2 is:",bool1 or bool2)
print("The value bool1 and bool2 is:", not bool1)
print("The value bool1 and bool2 is:", not bool2)
| true |
cbe1edfd5ceabc5b7cd4529fe9d7492db3bdb635 | WHJR-G12-Github/Solution_C7_SAA2 | /solution_c7_saa2.py | 235 | 4.25 | 4 | # Creating a list
num = [2,4,6,8,10]
# Printing the list before insertion
print("Before Insertion:",num)
# Inserting an element '20' at position '3'
num.insert(3,20)
# Printing the list after insertion
print("After Insertion:",num)
| true |
2edc0f29af63c187dc665b4e1fb6f6421c8c3fd5 | cmirza/FullStackDay-PdxCodeGuild | /01 - Python/lab31-atm_v1.py | 1,350 | 4.15625 | 4 | '''
Lab 31 - ATM
'''
# ATM class
class ATM:
# Set __init__ function and set balance to zero
def __init__(self):
self.balance = 0
# Set check_balance function to return balance of account
def check_balance(self):
return self.balance
# Set deposit function which adds deposit amount to balance and set balance as sum, then returns balance
def deposit(self, amount):
self.balance += amount
return self.balance
# Set check withdrawal function which checks if the balance minus the amount to withdraw is greater than zero.
# If it is, return true, otherwise return false.
def check_withdrawal(self, amount):
return amount > self.balance
# Set withdraw function which first uses check_withdrawal to see if balance will be greater than zero. If true,
# it subtracts the amount from balance and sets the new sum as balance. Otherwise it returns an error.
def withdraw(self, amount):
if self.check_withdrawal(amount) is True:
self.balance -= amount
return self.balance
else:
return "Withdrawal exceeds balance."
# Set calc_interest function, multiplies balance by .1 and sets result as interest, then returns interest
def calc_interest(self):
interest = self.balance * .1
return interest
| true |
f675fcde6c955bd335d5c2bd636b2da274a3fa6c | cmirza/FullStackDay-PdxCodeGuild | /01 - Python/lab14-practice_prob06.py | 246 | 4.15625 | 4 | '''
Lab 14 - Practice Problems
Problem 6: Print out the powers of 2 from 2^0 to 2^20.
'''
for i in range(20): # run loop 20 times
power = 2 ** i # calculate the power of 2 to the power of the iterator
print(power) # output each power
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.