blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ee3615b1612d3340005a8b07a6e93bc130153591 | JanJochemProgramming/basic_track_answers | /week3/session/dicts.py | 338 | 4.25 | 4 | capitals = {"The Netherlands": "Amsterdam", "France": "Paris"}
capitals["Japan"] = "Tokyo"
for country in reversed(sorted(capitals)):
print(country, capitals[country])
fruit_basket = {"Apple": 3}
fruit_to_add = input("Which fruit to add? ")
fruit_basket[fruit_to_add] = fruit_basket.get(fruit_to_add, 0) + 1
print(fruit_basket)
| true |
b3911866de644fab92a2c061c2a8a7d4535d3820 | JanJochemProgramming/basic_track_answers | /week1/exercises/exercise_1_7_1-5.py | 724 | 4.5 | 4 | # I don't expect you to put in all the extra print statement
# they are there to help follow my train of though
print(9 * "*", " + ", 9 * "*")
print(3 + 5)
print("Hello " + "world!")
print(9 * "*", " - ", 9 * "*")
print(5 - 3)
print(9 * "*", " * ", 9 * "*")
print(3 * 5)
print(3 * "Hallo")
print(9 * "*", " / ", 9 * "*")
print(5 / 3)
print(9 * "*", " // ", 8 * "*")
print(5 // 3)
print(6 // 3)
print(7 // 3)
# this give the integer division
print(9 * "*", " % ", 9 * "*")
print(5 % 3)
print(6 % 3)
print(7 % 3)
# this gives the remainder after integer division
print(9 * "*", " ** ", 8 * "*")
print(2 ** 2)
print(2 ** 3)
print(2 ** 4)
print(3 ** 2)
# this is "to the power"
# exercise 2
print("This is a string" + 5)
| false |
8ec7c46f57e44354f3479ea02e8e0cf34aaec352 | oreqizer/pv248 | /04/book_export.py | 1,691 | 4.1875 | 4 | # In the second exercise, we will take the database created in the
# previous exercise (‹books.dat›) and generate the original JSON.
# You may want to use a join or two.
# First write a function which will produce a ‹list› of ‹dict›'s
# that represent the books, starting from an open sqlite connection.
import sqlite3
import json
from book_import import opendb
query_books = """
--begin-sql
SELECT b.name
FROM book AS b
--end-sql
"""
query_authors = """
--begin-sql
SELECT a.name
FROM book AS b
INNER JOIN book_author_list AS l ON l.book_id = b.id
INNER JOIN author AS a ON l.author_id = a.id
WHERE b.name = ?
--end-sql
"""
def read_books(conn):
cur = conn.cursor()
res = []
cur.execute(query_books)
books = cur.fetchall()
for b in books:
cur.execute(query_authors, b)
authors = cur.fetchall()
res.append({
"name": b[0],
"authors": [name for (name,) in authors],
})
conn.commit()
return res
# Now write a driver that takes two filenames. It should open the
# database (do you need the foreign keys pragma this time? why yes
# or why not? what are the cons of leaving it out?), read the books,
# convert the list to JSON and store it in the output file.
def export_books(file_in, file_out):
conn = opendb(file_in)
res = json.dumps(read_books(conn), indent=" ")
open(file_out, "w").write(res)
def test_main():
export_books('books.dat', 'books_2.json')
with open('books.json', 'r') as f1:
js1 = json.load(f1)
with open('books_2.json', 'r') as f2:
js2 = json.load(f2)
assert js1 == js2
if __name__ == "__main__":
test_main()
| true |
a0151ddb3bc4c2d393abbd431826393e46063b89 | zachacaria/DiscreteMath-II | /q2.py | 1,356 | 4.15625 | 4 | import itertools
import random
def random_permutation(iterable, r):
"Random selection from itertools.permutations(iterable, r)"
pool = tuple(iterable)
r = len(pool) if r is None else r
return tuple(random.sample(pool, r))
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# This code is contributed by Mohit Kumra
#permut = itertools.permutations(random_permutation(range(1,101), 5))
#permut = itertools.permutations.random_permutation(range(100),3)
#permut = itertools.permutations([1,2,3,4,5,6],3)
#count_permut = []
#for i in permut:
#count_permut.append(i)
#print all permutations
#print count_permut.index(i)+1, i
#print the total number of permutations
#print'number of permutations', len(count_permut)
permut = itertools.permutations(random_permutation(range(1,101), 100))
# Driver code to test above
#count_permut = []
count_permut = []
insertionSort(count_permut)
print ("Sorted array is:")
for i in range(len(count_permut)):
print ("%d" %count_permut[i])
#for i in range(len(arr)):
#print ("%d" %arr[i])
| true |
49a02e54c4e4d95e4fb06ef8a85ecc4c0534c2f7 | Ianashh/Python-Testes | /Curso em vídeo/Ex060.py | 665 | 4.34375 | 4 | # Obs.: usar # nas linhas do "for" (Passo 2.1) ou nas linhas do "while" (Passo 2.2) para anular um ou outro programa e obter o resultado correto.
# Passo 1: Criar variáveis
n = int(input('Digite um número para descobrir seu fatorial: '))
cont = n
esc = n
# Passo 2.1: Usar o "for" para o fatorial
for n in range(n,1,-1) :
cont = cont*(n-1)
# Passo 3: Print do resultado
print(f'O número escolhido foi o {esc} e seu valor fatorial é {cont}')
# Passo 2.2: Usar o "while" para o fatorial
while esc != 1:
esc -= 1
cont = cont * esc
# Passo 3: Print do resultado
print(f'O número escolhido foi o {n} e seu valor fatorial é {cont}')
| false |
115b477fb7b86d34e9df784d43bfe29b2dcbf06a | tanyastropheus/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 364 | 4.28125 | 4 | #!/usr/bin/python3
def number_of_lines(filename=""):
"""count the number of lines in a text file
Args:
filename (str): file to be counted
Returns:
line_num (int): number of lines in the file.
"""
line_num = 0
with open(filename, encoding="UTF8") as f:
for line in f:
line_num += 1
return line_num
| true |
b892044a6357a29a857857ffb37c5b438a9ef785 | AYamaui/Practice | /sort/insertion_sort.py | 414 | 4.21875 | 4 |
# Complexity: O(n^2) for swaps / O(n^2) for comparisons
def insertion_sort(array):
for i in range(1, len(array)):
j = i
while j >= 1 and array[j-1] > array[j]:
aux = array[j-1]
array[j-1] = array[j]
array[j] = aux
j -= 1
return array
if __name__ == '__main__':
array = [5, 2, 4, 6, 1, 3]
insertion_sort(array)
print(array)
| false |
fafd561f1c3020231747a3480278bcf91c457a82 | AYamaui/Practice | /exercises/cyclic_rotation.py | 1,998 | 4.3125 | 4 | """
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
Write a function:
def solution(A, K)
that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given
A = [3, 8, 9, 7, 6]
K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given
A = [0, 0, 0]
K = 1
the function should return [0, 0, 0]
Given
A = [1, 2, 3, 4]
K = 4
the function should return [1, 2, 3, 4]
Assume that:
N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
"""
def solution(A, K):
N = len(A)
final_array = [0]*N
for i in range(N):
new_index = i + K - N*((i + K )// N)
final_array[new_index] = A[i]
return final_array
if __name__ == '__main__':
A = [3, 8, 9, 7, 6]
K = 3
print(solution(A, K))
A = [0, 0, 0]
K = 1
print(solution(A, K))
A = [1, 2, 3, 4]
K = 4
print(solution(A, K))
A = [2]
K = 10
print(solution(A, K))
A = [8, 11, 4, 20, 1]
K = 12
print(solution(A, K))
A = [8, 11, 4, 20, 1]
K = 11
print(solution(A, K))
A = [8, 11, 4, 20]
K = 12
print(solution(A, K))
A = [8, 11, 4, 20]
K = 11
print(solution(A, K))
A = [2, 3]
K = 5
print(solution(A, K))
| true |
5f404ca2db9ce87abe64ba7fd1dd111b1ceeb022 | matt969696/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/100-matrix_mul.py | 1,965 | 4.25 | 4 | #!/usr/bin/python3
"""
2-matrix_mul module - Contains simple function matrix_mul
"""
def matrix_mul(m_a, m_b):
"""
Multiplies 2 matrices
Return the new matrix
The 2 matrix must be non null list of list
The 2 matrix must be multiable
All elements of the 2 matrix must be integers or floats
"""
if type(m_a) is not list:
raise TypeError("m_a must be a list")
if type(m_b) is not list:
raise TypeError("m_b must be a list")
for line in m_a:
if type(line) is not list:
raise TypeError("m_a must be a list of lists")
for line in m_b:
if type(line) is not list:
raise TypeError("m_b must be a list of lists")
if len(m_a) == 0 or len(m_a[0]) == 0:
raise ValueError("m_a can't be empty")
if len(m_b) == 0 or len(m_b[0]) == 0:
raise ValueError("m_b can't be empty")
for line in m_a:
for a in line:
if type(a) is not int and type(a) is not float:
raise TypeError("m_a should contain only integers or floats")
for line in m_b:
for a in line:
if type(a) is not int and type(a) is not float:
raise TypeError("m_b should contain only integers or floats")
for line in m_a:
if len(line) != len(m_a[0]):
raise TypeError("each row of m_a must be of the same size")
for line in m_b:
if len(line) != len(m_b[0]):
raise TypeError("each row of m_b must be of the same size")
linea = len(m_a)
cola = len(m_a[0])
lineb = len(m_b)
colb = len(m_b[0])
if cola != lineb:
raise ValueError("m_a and m_b can't be multiplied")
outmat = []
for i in range(linea):
totline = []
for j in range(colb):
tot = 0
for k in range(cola):
tot += m_a[i][k] * m_b[k][j]
totline.append(tot)
outmat.append(totline)
return(outmat)
| true |
6aef4c2a49e81fe1fe83dacb7e246acee51ab11c | Floozutter/silly | /python/montyhallsim.py | 2,038 | 4.15625 | 4 | """
A loose simulation of the Monty Hall problem in Python.
"""
from random import randrange, sample
from typing import Tuple
Prize = bool
GOAT = False
CAR = True
def make_doors(doorcount: int, car_index: int) -> Tuple[Prize]:
"""Returns a representation of the doors in the Monty Hall Problem."""
return tuple(CAR if i == car_index else GOAT for i in range(doorcount))
def play(doorcount: int, switch: bool) -> Prize:
"""Runs a trial of the Monty Hall problem and returns the Prize."""
# Make the doors with a randomly generated index for the winning door.
doors = make_doors(doorcount, randrange(doorcount))
# Randomly generate the player's first choice.
firstchoice = randrange(doorcount)
# Generate every revealable door.
# A door is revealable if it contains a goat and is not the first choice.
revealable = tuple(
i for i, prize in enumerate(doors) if (
i != firstchoice and prize == GOAT
)
)
# Reveal doors so that one door remains apart from the first choice.
revealed = sample(revealable, doorcount - 2)
# Get the index of the final remaining door.
otherchoice = next(iter(
set(range(doorcount)) - set(revealed) - {firstchoice}
))
# Choose between the player's first choice and the other choice.
finalchoice = otherchoice if switch else firstchoice
# Return the Prize corresponding to the final choice.
return doors[finalchoice]
def test(doorcount: int, switch: bool, trials: int) -> bool:
"""Returns a win rate for the Monty Hall problem with repeated trials."""
wins = sum(int(play(doorcount, switch) == CAR) for _ in range(trials))
return wins/trials
if __name__ == "__main__":
trials = 10000
# Test always switching with 3 doors.
print(f"{3:>3} Doors | Always Switch: ", end="")
print(f"{test(3, True, trials):%}")
# Test always switching with 100 doors.
print(f"{100:>3} Doors | Always Switch: ", end="")
print(f"{test(100, True, trials):%}")
| true |
c7e11b86d21975a2afda2485194161106cadf3b3 | ariquintal/StructuredProgramming2A | /unit1/activity_04.py | 338 | 4.1875 | 4 | print("Start Program")
##### DECLARE VARIABLES ######
num1 = 0
num2 = 0
result_add = 0
result_m = 0
num1 = int(input("Enter number1\n"))
num2 = int(input("Enter number2\n"))
result_add = num1 + num2
result_m = num1 * num2
print("This is the add", result_add)
print("This is the multiplication", result_m)
print ("Program Ending...") | true |
df10e17b0e13a965b32fda8db67bcaba3743938a | candacewilliams/Intro-to-Computer-Science | /kind_of_a_big_deal.py | 403 | 4.125 | 4 | minutes = float(input('Minutes: '))
num_hours = float(minutes / 60)
num_hours = int(num_hours)
#print(num_hours)
num_minutes = float(minutes % 60)
whole_minutes = int(num_minutes)
#print(num_minutes)
num_seconds = minutes - int(minutes)
num_seconds = num_seconds * 60
num_seconds = round(num_seconds)
print(num_hours , 'hours,' , whole_minutes , 'minutes,' , num_seconds , 'seconds')
| false |
c5239b303a99370ab99df458f758eaef7af3cbac | candacewilliams/Intro-to-Computer-Science | /day_of_year.py | 840 | 4.25 | 4 | month = input('Insert Month: ')
day = int(input('Insert Day: '))
def GetDayOfYear(month,day):
if month == 'January':
print(day)
if month == 'February':
print(day + 31)
if month == 'March':
print(day +(31 + 28))
if month == 'April':
print(day + ((31*2) + 28))
if month == 'May':
print(day + ((31*2) + 30 + 28))
if month == 'June':
print(day + ((31*3) + 30 + 28))
if month == 'July':
print(day + ((31*3) + (30*2) + 28))
if month == 'September':
print(day +(31*4) + (30*2) + 28)
if month == 'October':
print(day + (31*5) + (30*3) + 28)
if month == 'November':
print(day + (31*6) + (30*3) + 28)
if month == 'December':
print(day + (31*6) + (30*4) + 28)
GetDayOfYear(month, day)
| false |
b9c3c868e064818e27304573dec01cc97a4c3ab1 | candacewilliams/Intro-to-Computer-Science | /moon_earths_moon.py | 299 | 4.15625 | 4 | first_name = input('What is your first name?')
last_name = input('What is your last name?')
weight = float(input('What is your weight?'))
moon_weight = str(weight* .17)
print('My name is ' + last_name + '. ' + first_name + last_name + '. And I weigh ' + moon_weight + ' pounds on the moon.')
| true |
3b3e87f7f11e3287516bf4fec945004c1e608a91 | candacewilliams/Intro-to-Computer-Science | /math.py | 537 | 4.21875 | 4 | val_1 = input('First Number: ')
val_1 = float(val_1)
val_2 = input('Second Number: ')
val_2 = float(val_2)
sum_val = val_1 + val_2
print('The sum of ' , val_1 , ' and ' , val_2 , ' is ' , sum_val)
minus_val = val_1 - val_2
print('The difference of ' , val_1 , ' and ' , val_2 , ' is ' , minus_val)
product_val = val_1 * val_2
print('The product of ' , val_1 , ' and ' , val_2 , ' is ' , product_val)
quotient_val = val_1 / val_2
print('The quotient of ' , val_1 , ' and ' , val_2 , ' is ' , quotient_val)
| false |
4b62f2f35aa1a6b85155351a1793559a1113ee69 | Jailsonmc/projects-python | /Geral/ConverterB10Bn.py | 372 | 4.125 | 4 | print("Digite o número a ser convertido para base 10:")
valor = int(input())
print("Digite a base:")
baseN = int(input())
continuar = True
aux = valor
while continuar:
quociente = int(aux / baseN)
resto = int(aux % baseN)
print(str(resto),end="")
aux = quociente
if quociente < baseN:
continuar = False
print(str(quociente),end="")
| false |
dba9eac804e3cc991ee8c2baeb17f180d2876414 | jdvpl/Python | /7 funciones/7variablelocalesgloabales.py | 732 | 4.25 | 4 | """
variables locales:se defines dentro de la funcion y no se puede usar fuera de ella
solo estan disponibles dentro
a no ser que hagamos un retunr
variables globales: son las que se declaran fuera de una funcion
y estan disponibles dentro y fuera de ellas
"""
frase="jiren es un marica y no pudo vencer a kakaroto" #variable global
print(frase)
def hola():
frase="hola mundo"
print("dentro de la funcion")
print(frase)
year=2000
print(year) #solo es accesible dentro de la funcion
global website #hace que la variable sea global para reutilizarla por fuera de la funcion
website='jdvpl.com'
print(f"Dentro, {website}")
return year
# print(website)
print(hola())
print(f"Fuera {website}") | false |
06f79676ec85258798bd5fd5c7520ca9c040080d | jdvpl/Python | /9 sets-diccionarios/2diccionarios.py | 1,236 | 4.1875 | 4 | """
es un tipo de dato que almacena un conjunto de datos
formato clave > valor
es lo mismo que un array con en json
"""
# persona={
# "nombre":"Juan",
# "apellidos":"Suarez",
# "web":"jdvpl.com"
# }
# print(type(persona)) #tipo de dato
# print(persona) #imprime todo
# print(f" la Web: {persona['web']}") #saca los datos segun el indice
# combinan lista con diccionario
contacto=[
{
"nombre":"Juan Daniel",
"Telefono":"3209188638",
"direccion":"cr 69 #64a-19"
},
{
"nombre":"Kakaroto",
"direccion":"universo 7"
},
{
"nombre":"saitama",
"telefono":"0000000"
}
]
print(type(contacto))
print(contacto)
print(contacto[0]["nombre"])
# modificando datos de la clave
contacto[0]["nombre"]="Natsu"
print(contacto)
print(contacto[0]["nombre"])
# recorriendo los datos con un for
for i in contacto:
# print(i) #imprime todos los datos del diccionario
print(f"\nNombre: {i['nombre']}")
try: #sino no tiene algo dentro del diccionario colocamos un try
print(f"Direccion: {i['direccion']}")
except:
print("")
# print(f"Nombre: {i['nombre']} : No tiene Direccion ")
print("-----------------------------------") | false |
33dfb3e016da6665ab1e7ef47a89344f5a1c70ad | jdvpl/Python | /4 condicionales/elif.py | 1,669 | 4.125 | 4 | # print(f"########################## elif ####################")
# dia=int(input("Introduce el dia de la semana "))
# if dia==1:
# print(f"es lunes")
# elif dia==2:
# print(f"es martes")
# elif dia==3:
# print(f"es miercoles")
# elif dia==4:
# print(f"es jueves")
# elif dia==5:
# print(f"es viernes")
# elif dia==6:
# print(f"es jueves")
# elif dia==7:
# print(f"es domingo")
# else:
# print(f"opcion incorrecta")
#operadores logicos
#and =y
#or o
#! negacion
#not no
# print(f"########################## elif ####################")
# edad=int(input("Introduce la edad "))
# edad_minima=18
# edad_maxima=65
# if edad>=edad_minima and edad<=edad_maxima:
# print(f"esta en edad de trabajar")
# else:
# print("no esta en edad de trabajar")
#mas ejemplos con condicionales
# print(f"########################## condicional con or ####################")
# pais=input("Introduce el pais ")
# if pais=="colombia" or pais=="españa" or pais=="mexico":
# print(f"{pais} es un pais de habla hispana")
# else:
# print(f"no es un pais de habla hispana")
# print(f"########################## condicionales con not ####################")
# pais=input("Introduce el pais ")
# if not (pais=="colombia" or pais=="españa" or pais=="mexico"):
# print(f"{pais} No es un pais de habla hispana")
# else:
# print(f"{pais} es un pais de habla hispana")
print(f"########################## condicionales con !=####################")
pais=input("Introduce el pais ")
if (pais!="colombia" and pais!="españa" and pais!="mexico"):
print(f"{pais} No es un pais de habla hispana")
else:
print(f"{pais} es un pais de habla hispana") | false |
ed89b53b3082f608adb2f612cf856d87d1f51c78 | SandySingh/Code-for-fun | /name_without_vowels.py | 359 | 4.5 | 4 | print "Enter a name"
name = raw_input()
#Defining all vowels in a list
vowels = ['a', 'e', 'i', 'o', 'u']
name_without_vowels = ''
#Removing the vowels or rather forming a name with only consonants
for i in name:
if i in vowels:
continue
name_without_vowels += i
print "The name without vowels is:"
print name_without_vowels
| true |
8fbcb251349fe18342d92c4d91433b7ab6ca9d53 | gsaikarthik/python-assignment7 | /assignment7_sum_and_average_of_n_numbers.py | 330 | 4.21875 | 4 | print("Input some integers to calculate their sum and average. Input 0 to exit.")
count = 0
sum = 0.0
number = 1
while number != 0:
number = int(input(""))
sum = sum + number
count += 1
if count == 0:
print("Input some numbers")
else:
print("Average and Sum of the above numbers are: ", sum / (count-1), sum) | true |
4731e40b41f073544f2edf67fb02b6d93396cd7b | hbomb222/ICTPRG-Python | /week3q4 new.py | 819 | 4.40625 | 4 | username = input("enter username ") # ask user for username
user_dict = {"bob":"password1234", "fred":"happypass122", "lock":"passwithlock144"} # create dictionary of username password pairs
if (username == "bob" or username == "fred" or username == "lock"): # check if the entered username matches any of the known values
password = (input("enter password ")) # ask user for password
check_password = user_dict[username] # retrive the saved password from the dictionary for the entered username
if (password == check_password): # check if the entered password is the same as the saved password
print ("access granted") # print if username and password match
else: # if the passwords do not match, jump to this code
print ("access denied") # print if username matches but password does not match | true |
5e3d41c1d7e1d49566416dced623ae593b58c079 | nickwerner-hub/WhirlwindTourOfPython | /Scripting/03_RangeFunctionExample.py | 270 | 4.34375 | 4 | #RangeFunctionExample.py
# This example demonstrates the range function for generating
# a sequence of values that can be used in a for loop.
pi = 3.1415
for r in range(0,100,20):
area = (r ** 2) * pi
print "The area of a circle with radius ", r, "is ", area | true |
313925e1c6edb9d16bc921aff0c8897ee1d2bdf5 | nickwerner-hub/WhirlwindTourOfPython | /Scripting/07_WriteDataExample.py | 1,620 | 4.34375 | 4 | #WriteDataExample.py
# This script demonstrates how a file object is used to both write to a new text file and
# append to an existing text file.In it we will read the contents of the EnoNearDurham.txt
# file and write selected data records to the output file.
# First, create some variables. "dataFileName" will point to the EnoNearDurham.txt file,
# and "outputFileName" will that will contain the name of the file we will create.
dataFileName = "S://Scripting2//EnoNearDurham.txt"
outputFileName = "S://Scripting2//SelectedNWISRecords.txt"
# Next, open the data file and read its contents into a list object. This is similar
# to the previous tutorial, but here we read the entire contents into a single list
dataFileObj = open(dataFileName, 'r') ## Opens the data file as read only
lineList = dataFileObj.readlines() ## Creates a list of lines from the data file
dataFileObj.close() ## We have our list, so we can close the file
print len(lineList), " lines read in" ## This is a quick statement to show how many lines were read
# Here, we create a file object in 'w' or write mode. This step creates a new file at
# the location specified. IF A FILE EXISTS ALREADY THIS WILL OVERWRITE IT!
newFileObj = open(outputFileName,'w')
# Next, we loop through the lines in the dataList. If it's a comment, we'll skip it.
# Otherwise, we'll split the items in the line into a list.
for dataLine in lineList:
# If the line is a comment, skip further processing and go to the next line
if dataLine[:4] <> "USGS":
continue
newFileObj.write(dataLine)
newFileObj.close() | true |
1fc51bc3ec116ee0663399bffae6825020d33801 | abdbaddude/codeval | /python/jolly_jumper.py3 | 2,166 | 4.1875 | 4 | #!/usr/bin/env python3
"""
JOLLY JUMPERS
CHALLENGE DESCRIPTION:
Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the
differences between successive elements take on all possible values 1 through n - 1.
eg.
1 4 2 3
is a jolly jumper, because the absolute differences are 3, 2, and 1, respectively.
The definition implies that any sequence of a single integer is a jolly jumper.
Write a program to determine whether each of a number of sequences is a jolly jumper.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename.
Each line in this file is one test case.
Each test case will contain an integer n < 3000
followed by n integers representing the sequence. The integers are space delimited.
OUTPUT SAMPLE:
For each line of input generate a line of output saying 'Jolly' or 'Not jolly'.
"""
"""
@params List of n sequence such that 0 < n < 3000
e.g x = [1,4,2,3]
"""
def is_jolly_jumpers(seq):
n = seq.pop(0) #first number in list is number of integers
if ( n == 1 and len(seq) == 1) : return True #The definition implies that any sequence of a single integer is a jolly jumper
else:
if ((n == len(seq)) and (1 < n and n<3000) ): #condition must be fulfilled
_,*tail = seq #pythonic way of removing/ignoring values
len_tail = len(tail)
c=[ abs(seq[i] - tail[i]) for i in range(len_tail)]
#Decided against using sorted and used sum instead as sorted will bring in algorithm overhead of Big O = N
#hence used sum for test
sum_test = (sum(c)==sum(list(range(len_tail+1))))
possible_values_test = True if (min(c) == 1 and (n-max(c)) == 1) else False #Ensure possible values 1 .. n-1
return possible_values_test and sum_test
else:
return False
import sys
test_cases = open(sys.argv[1], 'r')
tests=test_cases.readlines()
for test in tests:
if test.strip(): #only nonempty lines are only considered
s_list = test.strip().split(" ") #convert each line to a string list.
i_list = [int(i) for i in s_list ] #convert string list to int
print ('Jolly' if is_jolly_jumpers(i_list) else 'Not jolly' )
| true |
87c2fcfcaa140e8971926f8da3098c5abe781271 | Nadeem-Doc/210CT-Labsheet | /Labsheet 5 - Task 2.py | 1,542 | 4.21875 | 4 | class Node():
def __init__(self, value):
self.value=value
self.next=None # node pointing to next
self.prev=None # node pointing to prev
class List():
def __init__(self):
self.head=None
self.tail=None
def insert(self,n,x):
#Not actually perfect: how do we prepend to an existing list?
if n!=None:
x.next = n.next
n.next = x
x.prev = n
if x.next != None:
x.next.prev = x
if self.head == None:
self.head = self.tail = x #assigns the value of x to the head and tail
x.prev = x.next = None
elif self.tail == n:
self.tail = x #reassigns the tail to the current node
def display(self):
values=[]
n=self.head
while n!=None:
values.append(str(n.value))
n=n.next
print ("List: ", ",".join(values))
def lisrem(self,n):
if n.prev != None:
n.prev.next = n.next
else:
l.head = n.next
if n.next != None:
n.next.prev = n.prev
else:
l.tail = n.prev
if __name__ == '__main__':
l=List()
n = Node(6)
n1 = Node(2)
n2 = Node(3)
n3 = Node(4)
l.insert(None, n)
l.insert(l.head,n1)
l.insert(l.head,n2)
l.insert(l.head,n3)
l.lisrem(n)
l.display()
| true |
f0664f2b9a826598dc873e8c27d53b6623f67b5b | Vanagand/Data-Structures | /queue/queue.py | 1,520 | 4.21875 | 4 | #>>> Check <PASS>
"""
A queue is a data structure whose primary purpose is to store and
return elements in First In First Out order.
1. Implement the Queue class using an array as the underlying storage structure.
Make sure the Queue tests pass.
2. Re-implement the Queue class, this time using the linked list implementation
as the underlying storage structure.
Make sure the Queue tests pass.
3. What is the difference between using an array vs. a linked list when
implementing a Queue?
Stretch: What if you could only use instances of your Stack class to implement the Queue?
What would that look like? How many Stacks would you need? Try it!
"""
from sys import path
path.append("../")
from singly_linked_list.singly_linked_list import singleLinkedList
class Queue: #<<<
def __init__(self):
self._stack = 0
self._storage = singleLinkedList()
def __len__(self):
return self._stack
def enqueue(self, value):
self._storage.add_to_tail(value)
self._stack += 1
def dequeue(self):
if self.__len__() > 0:
self._stack -= 1
return self._storage.remove_head()
if self.__len__() <= 0:
return
if __name__ == "__main__":
pass
# import pkgutil
# search_path = ['.'] # set to None to see all modules importable from sys.path
# all_modules = [x[1] for x in pkgutil.iter_modules(path=search_path)]
# print(all_modules) | true |
6f1fbad0e294f9d9c800c84b72e915938b7a1c33 | javicercasi/um-programacion-i-2020 | /58004-Cercasi-Javier/tp1/Orientado a Objetos/Ejercicio2OPP.py | 1,471 | 4.5625 | 5 | '''La pizzería Bella Napoli ofrece pizzas vegetarianas y no vegetarianas a
sus clientes. Los ingredientes para cada tipo de pizza aparecen a continuación.
* Ingredientes vegetarianos: Pimiento y tofu.
* Ingredientes no vegetarianos: Peperoni, Jamón y Salmón.
Escribir un programa que pregunte al usuario si quiere una pizza vegetariana
o no, y en función de su respuesta le muestre un menú con los ingredientes
disponibles para que elija. Solo se puede eligir un ingrediente además de la
mozzarella y el tomate que están en todas la pizzas. Al final se debe mostrar
por pantalla si la pizza elegida es vegetariana o no y todos los
ingredientes que lleva.'''
class Pizza():
def __init__(self):
self.tipo = ''
def ingreso(self):
self.tipo = input('''Que pizza desea?Vegetariana/Comun\n''').title()
print("\nIngrese un ingrediente de los de la lista:\n")
return(self.tipo)
def ingredientes(self):
if not self.tipo:
print("\nNo ingreso los campos obligatorios")
if self.tipo == "Vegetariana":
print("-Pimiento\n-Tofu\n")
elif self.tipo == "Comun":
print("\n-Peperoni\n-Jamón\n-Salmón")
else:
print("Vuelva a intentarlo")
return(input())
def pantalla(self):
print("\nSe Preparara pizza "+self.ingreso(),
" con ", self.ingredientes())
if __name__ == "__main__":
P = Pizza()
P.pantalla()
| false |
43029ca4a4a757e2c1aa177b9addca9c7c3157f0 | Amrut-17/python_programs | /Selection_Sort.py | 620 | 4.15625 | 4 | def selection_sort(n):
for i in range (n):
min = i
for j in range(i+1 , n):
if (a[j] < a[min]):
min = j
temp = a[i]
a[i] = a[min]
a[min] = temp
print('\nAFTER sorting')
for i in range(n):
print (a[i], end = " ")
import numpy
n = int (input("ENTER SIZE OF ARRAY "))
a = numpy.ndarray(shape = (n) , dtype = int)
print ('ENTER ARRAY ELEMENTS ONE BY ONE ')
for i in range (n):
a[i] = int (input())
print ('BEFORE sorting')
for i in range(n):
print (a[i], end = ' ')
selection_sort(n) | false |
de5f1ae3bae6d0744cd18ded1ec0631d48fbb559 | TanvirKaur17/Greedy-4 | /shortestwayToFormString.py | 912 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 08:30:10 2019
@author: tanvirkaur
implemented on spyder
Time Complexity = O(m*n)
Space Complexity = O(1)
we maintain two pointers one for source and one for target
Then we compare the first element of source with the target
If we iterate through the entire source we again reset the pointer
untill we visit the entire target
We maintain the curr pointer to check whether we have found the ith element
of target in source or not.
"""
def shortestWay(source, target):
if source == target:
return 1
result = 0
s = len(source)
t = len(target)
i = 0
while (i<t):
j =0
curr = i
while(j<s):
if (i <t and source[j] == target[i]):
i += 1
j +=1
if curr == i:
return -1
result += 1
return result
| true |
0f8df2bb7f0ca56f34737d85faa3aeb5d4c8a300 | emmanuelagubata/Wheel-of-Fortune | /student_starter/main.py | 1,188 | 4.15625 | 4 | # Rules
print('Guess one letter at a time. If you want to buy a vowel, you must have at least $500, otherwise, you cannot buy a vowel. If you think you know the word or phrase, type \'guess\' to guess the word or phrase. You will earn each letter at a set amount and vowels will not cost anything.')
from random import randint
# needed for your test cases so your random outputs would match ours
random.seed(3)
# List of letters to remove after each guess
# List of all vowels
# Categories and words
# Pick a random category
# Get a random word or phrase from the category
# Fill up list with blanks for characters in word
# Function to print Word
def printWord(word):
# Keep guessing until word is guessed correctly
while True:
while True:
# Pick a random amount from amounts
# If the user wants to guess phrase or word
# If the user guesses letter they've already guessed
# If guess is a vowel, subtract $500 from total per vowel
# If the user cannot buy vowel
# If everything else is False, remove letter from alphabet and replace char in Word with letter in word
# If word or phrase is fully guessed, end game
| true |
355df5e645f38513d4581c5f3f08ed41568c59e2 | zaincbs/PYTECH | /reverseOfString.py | 375 | 4.375 | 4 | #!/usr/bin/env python
"""
Define a function reverse, that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".
"""
def reverse(s):
k= ""
for i in range (len(s)-1, -1, -1):
k = k + s[i]
return k
def main():
v = reverse("This is testing")
print v
if __name__ == "__main__":
main()
| true |
af771a30f93a4382dacfb04e423ad01dd96b3160 | zaincbs/PYTECH | /filter_long_words_using_filter.py | 561 | 4.25 | 4 | #!/usr/bin/env python
"""
Using the higher order function filter(), define a function
filter_long_words() that takes a list of words and an
integer n and returns the list of words that are longer
than n.
"""
def filter_long_words(l,n):
return filter(lambda word: len(word) > n, l)
def main():
list_with_len_of_word =filter_long_words(['happy','God','Abdul', 'Samad', 'needs', 'a', 'job'],3)
print list_with_len_of_word
if __name__ == "__main__":
main()
"""
H$ ./filter_long_words_using_filter.py
['happy', 'Abdul', 'Samad', 'needs']
"""
| true |
528bb5e90b48a7b741e96c7df0ffe0905534df39 | zaincbs/PYTECH | /readlines.py | 1,420 | 4.125 | 4 | #!/usr/bin/env python
"""
I am making a function that prints file in reverse order and then reverses
the order of the words
"""
import sys
def readFile(filename):
rorder = ''
opposed = ''
finale= ''
inline = ''
#reading file line by line
#with open(filename) as f:
# lines = f.readlines()
#print lines
f = open(filename,'r')
lines = f.readlines()
print lines
print('')
print ('1')
for i in range(0,1,len(f.readlines())-1):
inline = inline + lines[i]
print inline
print ('')
print ('2')
#printing file in reverse order
for rev in range(len(lines)-1,-1,-1):
rorder = rorder + lines[rev]
print rorder
#print '.'.join(reversed(rorder.split('.')))
print ('3')
#printing words in reverse order
for words_rorder in range(len(rorder)-1,-1,-1):
finale = finale + rorder[words_rorder]
print finale
print ('4')
print('')
print finale.rstrip()
def main():
argList= sys.argv
filename_to_be_read = argList[1]
v = readFile(filename_to_be_read)
# print v
if __name__ == "__main__":
main()
"""
$ cat abc.txt
abc zed
I am funny
stop teasing me, please
Where am I?
Who am I
?
blah blah blah
$ ./readlines.py abc.txt
dez cba
ynnuf ma I
esaelp ,em gnisaet pots
?I ma erehW
I ma ohW
?
halb halb halb
"""
| true |
cddf97c1866cda863176a775e141a2ce53cbcbff | zaincbs/PYTECH | /palindrome_recog.py | 2,595 | 4.3125 | 4 | #!/usr/bin/env python
"""
Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, capitalization, and spacing are usually ignored.
"""
from reverseOfString import reverse
def palindrome_recognizer(s):
for i in s:
if i == ',':
s = s.replace(i, "")
if i == " ":
s = s.replace(i, "")
if i == "'":
s = s.replace(i, "")
if i == "?":
s = s.replace(i, "")
if i == ".":
s = s.replace(i, "")
if i == '!':
s = s.replace(i, "")
v=s.lower()
print v
#if v == reverse(v):
for i in range(0, len(s)-1):
if v[i] == s[len(v)-1-i]:
return v," is a palindrome phrase"
else:
return v," is not a palindrome phrase"
def main():
b =palindrome_recognizer("Step on no pets")
print b
c =palindrome_recognizer("Go hang a salami I'm a lasagna hog.")
print c
d =palindrome_recognizer("Was it a rat I saw?")
print d
e =palindrome_recognizer("Step on no pets")
print e
f =palindrome_recognizer("Sit on a potato pan, Otis")
print f
g =palindrome_recognizer("Lisa Bonet ate no basil")
print g
h =palindrome_recognizer("Satan, oscillate my metallic sonatas")
print h
i=palindrome_recognizer("I roamed under it as a tired nude Maori")
print i
j=palindrome_recognizer("Rise to vote sir")
print j
k= palindrome_recognizer("Dammit, I'm mad!")
print k
if __name__ == "__main__":
main()
"""
$ ./palindrome_recog.py
steponnopets
('Steponnopets', ' is a palindrome phrase')
gohangasalamiimalasagnahog
('GohangasalamiImalasagnahog', ' is a palindrome phrase')
wasitaratisaw
('WasitaratIsaw', ' is a palindrome phrase')
steponnopets
('Steponnopets', ' is a palindrome phrase')
sitonapotatopanotis
('SitonapotatopanOtis', ' is a palindrome phrase')
lisabonetatenobasil
('LisaBonetatenobasil', ' is a palindrome phrase')
satanoscillatemymetallicsonatas
('Satanoscillatemymetallicsonatas', ' is a palindrome phrase')
iroamedunderitasatirednudemaori
('IroamedunderitasatirednudeMaori', ' is a palindrome phrase')
risetovotesir
('Risetovotesir', ' is a palindrome phrase')
dammitimmad
('DammitImmad', ' is a palindrome phrase')
"""
| false |
597368b52b65f2cf0b6a61a78ec076f6ff925432 | AlanFermat/leetcode | /linkedList/707 designList.py | 2,691 | 4.53125 | 5 | """
Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement these functions in your linked list class:
get(index) : Get the value of the index-th node in the linked list. If the index is invalid, return -1.
addAtHead(val) : Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
addAtTail(val) : Append a node of value val to the last element of the linked list.
addAtIndex(index, val) : Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
deleteAtIndex(index) : Delete the index-th node in the linked list, if the index is valid.
"""
from ListNode import *
class MyLinkedList(object):
"""docstring for myLinkedList"""
def __init__(self):
self.size = 0
self.head = None
def get(self, index):
if index >= self.size:
return -1
temp = self.head
while index:
temp = temp.next
index -= 1
return temp.val
def addAtHead(self, val):
new = ListNode(val)
new.next = self.head
self.head = new
self.size += 1
def addAtTail(self, val):
temp = self.head
while temp.next:
temp = temp.next
temp.next = ListNode(val)
self.size += 1
def addAtIndex(self, index, val):
count = 0
temp = self.head
if self.size >= index:
if index == 0:
self.addAtHead(val)
elif index == self.size:
self.addAtTail(val)
# locate that position
else:
while count < index-1:
temp = temp.next
count += 1
# swap the value
new = ListNode(val)
new.next = temp.next
temp.next = new
self.size += 1
def deleteAtIndex(self, index):
temp = self.head
if index == 0:
self.head = self.head.next
self.size -= 1
else:
if self.size > index:
while index-1:
temp = temp.next
index -= 1
if temp.next:
temp.next = temp.next.next
self.size -= 1
g = MyLinkedList()
g.addAtHead(0)
g.addAtIndex(1,9)
g.addAtIndex(1,5)
g.addAtTail(7)
g.addAtHead(1)
g.addAtIndex(5,8)
show(g.head)
g.addAtIndex(5,2)
g.addAtIndex(3,0)
g.addAtTail(1)
g.addAtTail(0)
show(g.head)
g.deleteAtIndex(6)
show(g.head)
| true |
dcde21722a7a1ffac43bede4f9ebefefeca4a668 | AlanFermat/leetcode | /PYTHONNOTE/arg.py | 632 | 4.28125 | 4 | # *args is used to send a non-keyworded variable length argument list to the function
def test_var_args(f_arg, *argv):
print("first normal arg:", f_arg)
for arg in argv:
print("another arg through *argv:", arg)
test_var_args('yasoob', 'python', 'eggs', 'test')
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} = {1}".format(key, value))
greet_me(name = 'alan', val = '20')
def test_args_kwargs(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test_args_kwargs(**kwargs)
args = ('two',3,5)
test_args_kwargs(*args)
| false |
8f967f1220a5b1dbf211c5360d99c479fb522383 | tskillian/Programming-Challenges | /N-divisible digits.py | 939 | 4.21875 | 4 | #Write a program that takes two integers, N and M,
#and find the largest integer composed of N-digits
#that is evenly divisible by M. N will always be 1
#or greater, with M being 2 or greater. Note that
#some combinations of N and M will not have a solution.
#Example: if you are given an N of 3 and M of 2, the
#largest integer with 3-digits is 999, but the
#largest 3-digit number that is evenly divisible by
#2 is 998, since 998 Modulo 2 is 0. Another example
#is where N is 2 and M is 101. Since the largest
#2-digit integer is 99, and no integers between 1
#and 99 are divisible by 101, there is no solution.
digits_factor = raw_input("Enter digits and factor: ")
[digits, factor] = digits_factor.split()
minimum = 1
while len(str(minimum)) < int(digits):
minimum *= 10
answer = (minimum * 10) - 1
while answer >= minimum:
if answer % int(factor) == 0:
print answer
break
answer -= 1
| true |
d02456321853b7ea2b7a0bd80678647c6c0d8c21 | karakazeviewview/PythonTraining | /20210201/listlesson.py | 453 | 4.125 | 4 | list1=[] #からのリスト
list2=list() #からのリスト
list1.append(3)
print(list1)
list1.append(5)
print(list1[0])
list2.append(10)
list2.append(20)
print(list2)
list3=list1+list2
print(list3)
list4=list3*3
print(list4)
print(len(list4)) #12
print(sum(list4)) #合計114
del list4[0]
print(list4)
list4.remove(5) #見つけた最初の要素
print(list4)
list5=list4[3:8] #3以上8未満
print(list5)
print(list5-[-1]) #最後の要素
| false |
ea96f8e8e0c7a7e1bde8a01c47098036d10799f2 | usmanmalik6364/PythonTextAnalysisFundamentals | /ReadWriteTextFiles.py | 1,111 | 4.5 | 4 | # python has a built in function called open which can be used to open files.
myfile = open('test.txt')
content = myfile.read() # this function will read the file.
# resets the cursor back to beginning of text file so we can read it again.
myfile.seek(0)
print(content)
content = myfile.readlines()
myfile.seek(0)
for line in content:
print(line)
myfile.close() # always close the file after you've read.
# w+ is the mode which allows us to read and write.
# w and w+ should be used with caution as it overwrites the underlying file completely.
myfile = open('test.txt', 'w+')
myfile.write("The new Text")
content = myfile.read()
print(content)
myfile.close()
# APPEND TO A FILE
# a+ allows us to append to a file and if file does not exists, a+ will create a new file.
myfile = open('test.txt', 'a+')
myfile.write('MY FIRST LINE IS A+ OPENING')
myfile.close()
myfile = open('test.txt')
content = myfile.read()
print(content)
myfile.close()
# with is a context manager which automatically closes the file for us.
with open('test.txt', 'r') as mynewfile:
myvariable = mynewfile.readlines()
| true |
26d1023d423f31e9ddaccfcedaae9c82896dbe89 | viniciusvilarads/codigos-p1 | /Lista 3 - FIP/Lista 3 - Ex008.py | 816 | 4.3125 | 4 | """
Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 3 Estrutura de Decisão
Patos - PB | 2020
8 - Faça um programa que pergunte o preço de três produtos e informe qual
produto você deve comprar, sabendo que a decisão é sempre pelo mais barato.
"""
prod1 = float(input("Informe o preço do produto 1: "))
prod2 = float(input("Informe o preço do produto 2: "))
prod3 = float(input("Informe o preço do produto 3: "))
menor = 0
if (prod1 > prod2 >= prod3):
menor = prod3
elif (prod1 > prod3 >= prod2):
menor = prod2
elif (prod2 > prod1 >= prod3):
menor = prod3
elif (prod2 > prod3 >= prod1):
menor = prod1
elif (prod3 > prod1 >= prod2):
menor = prod2
elif (prod3 > prod2 >= prod1):
menor = prod1
else:
print("Preços iguais!")
print("Melhor produto custa: R${:.2f}".format(menor))
| false |
7f2ab64632cbed0280942876ddbee9e92827375b | viniciusvilarads/codigos-p1 | /Lista 4 - FIP/Lista 4 - Ex003.py | 649 | 4.1875 | 4 | """
Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 4 Estrutura de Decisão
Patos - PB | 2020
3 - Faça um Programa que leia um número e exiba o dia correspondente da semana.
(1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor
inválido.
"""
numero = int(input("Informe um número inteiro: "))
if numero == 1:
print("Domingo")
elif numero == 2:
print("Segunda-feira")
elif numero == 3:
print("Terça-feira")
elif numero == 4:
print("Quarta-feira")
elif numero == 5:
print("Quinta-feira")
elif numero == 6:
print("Sexta-feira")
elif numero == 7:
print("Sábado")
else:
print("Valor inválido")
| false |
9d2b79e92b1441856c645e3a34eb9a062dd6a5cd | marcinlaskowski/szkolenieZDDATA | /Zadania2/obiektowo_zad4.py | 2,153 | 4.40625 | 4 | """
Stwórz klasę Pojazd z atrybutami: kolor, cena. Klasę Samochód i Rower, obie dziedziczące po klasie Pojazd.
Stwórz kilka obiektów klasy Samochód i Rower. Stwórz listę pojazdy, w której znajdą się stworzone obiekty.
Wśród wszystkich pojazdów znajdź najdroższy pojazd, wypisz średnią cenę samochodu.
"""
class Vehicle:
def __init__(self, color, price):
self.color = color
self.price = price
def __str__(self):
return f"{self.color} - {self.price}"
class Car(Vehicle):
pass
class Bicycle(Vehicle):
pass
if __name__ == "__main__":
car1 = Car("szary", 20000)
car2 = Car("czerwony", 30000)
car3 = Car("zielony", 15000)
bicycle1 = Bicycle("niebieski", 1000)
bicycle2 = Bicycle("żółty", 2000)
vehicles = [car1, car2, car3, bicycle1, bicycle2]
max_price = 0
max_price_vehicle = None
for vehicle in vehicles:
print(vehicle.price, vehicle.color)
if vehicle.price > max_price:
max_price = vehicle.price
max_price_vehicle = vehicle
print("Najdroższy pojazd", max_price_vehicle.color, max_price_vehicle.price)
print(f"Najdroższy pojazd - {max_price_vehicle.color} {max_price_vehicle.price}")
print("Najdroższy pojazd", max_price_vehicle)
# Wypisz średnią cenę samochodu.
car_price_sum = 0
car_numbers = 0
for vehicle in vehicles:
print(vehicle)
print(type(vehicle))
print(isinstance(vehicle, Vehicle))
print(isinstance(vehicle, Car))
print(isinstance(vehicle, Bicycle))
if isinstance(vehicle, Car):
car_price_sum = car_price_sum + vehicle.price
car_numbers += 1
print(f"Średnia: {round(car_price_sum / car_numbers, 2)}")
# 2
# Przykład Piotra:
# sum([item.price for item in vehicles if isinstance(item, Car)]) / len([item for item in vehicles if isinstance(item, Car)])
car_prices = [vehicle.price for vehicle in vehicles if isinstance(vehicle, Car)]
print(car_prices)
print(sum(car_prices) / len(car_prices))
print(round(sum(car_prices) / len(car_prices), 2))
| false |
745672e96a8d12e6f20f7d696c675c90f06761eb | lvraikkonen/GoodCode | /leetcode/232_implement_queue_using_stacks.py | 1,989 | 4.40625 | 4 | # Stack implementation by list
class MyStack:
"""
栈的说明
栈是一个线性的数据结构
栈遵循LIFO的原则,Last In First Out , 即后进先出
栈顶为top,栈底为base
"""
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
# s = MyStack()
# print s.isEmpty()
# s.push(1)
# s.push(2)
# print s.peek()
# print s.pop()
# print s.size()
# implement queue using python deque
from collections import deque
class MyQueue1(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = deque()
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
tmp_stack = deque()
for i in range(len(self.stack)):
tmp_stack.append(self.stack.pop())
self.stack.append(x)
for i in range(len(tmp_stack)):
self.stack.append(tmp_stack.pop())
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
return self.stack.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
return self.stack[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return len(self.stack) == 0
if __name__ == "__main__":
# Your MyQueue object will be instantiated and called as such:
obj = MyQueue1()
obj.push(0)
obj.push(1)
obj.push(2)
param_2 = obj.pop()
param_3 = obj.peek()
param_4 = obj.empty() | false |
ce51c27893b378bd6abb314ad4926e17637c6228 | SmischenkoB/campus_2018_python | /Dmytro_Shalimov/1/9.py | 2,110 | 4.3125 | 4 | <<<<<<< HEAD
print("Convert a 24-hour time to a 12-hour time.")
print("Time must be validated.")
user_input = input("Enter time: ")
formatted_time = str()
if len(user_input) != 5:
print("not valid time")
hours = user_input[:2]
minutes = user_input[3:]
if hours.isnumeric() and minutes.isnumeric():
hours_in_int = int(hours)
minutes_in_int = int(minutes)
if (hours_in_int < 0 or hours_in_int > 23) or (minutes_in_int < 0 or minutes_in_int > 59):
print("not valid time")
else:
if hours_in_int > 12:
formatted_time = '{:02d}:{:02d} pm'.format(hours_in_int - 12, minutes_in_int)
elif hours_in_int == 12:
formatted_time = '12:{:02d} pm'.format(minutes_in_int)
elif hours_in_int == 0:
formatted_time = '12:{:02d} am'.format(minutes_in_int)
else:
formatted_time = '{:02d}:{:02d} am'.format(hours_in_int, minutes_in_int)
print(formatted_time)
else:
print("not valid time")
=======
print("Convert a 24-hour time to a 12-hour time.")
print("Time must be validated.")
user_input = input("Enter time: ")
formatted_time = str()
if len(user_input) != 5:
print("not valid time")
hours = user_input[:2]
minutes = user_input[3:]
if hours.isnumeric() and minutes.isnumeric():
hours_in_int = int(hours)
minutes_in_int = int(minutes)
if (hours_in_int < 0 or hours_in_int > 23) or (minutes_in_int < 0 or minutes_in_int > 59):
print("not valid time")
else:
if hours_in_int > 12:
formatted_time = '{:02d}:{:02d} pm'.format(hours_in_int - 12, minutes_in_int)
elif hours_in_int == 12:
formatted_time = '12:{:02d} pm'.format(minutes_in_int)
elif hours_in_int == 0:
formatted_time = '12:{:02d} am'.format(minutes_in_int)
else:
formatted_time = '{:02d}:{:02d} am'.format(hours_in_int, minutes_in_int)
print(formatted_time)
else:
print("not valid time")
>>>>>>> 715fd0763b415a13fb28a483f258a5eadc1ec931
| true |
425c4137611ae13aee9d24a486040bc9e565edd8 | SmischenkoB/campus_2018_python | /Dmytro_Skorobohatskyi/batch_3/verify_brackets.py | 1,004 | 4.3125 | 4 | def verify_brackets(string):
""" Function verify closing of brackets, parentheses, braces.
Args:
string(str): a string containing brackets [], braces {},
parentheses (), or any combination thereof
Returns:
bool: Return True if all brackets are closed, otherwise - False.
"""
opening = ['(', '{', '[']
closing = [')', '}', ']']
corresponding = dict(zip(closing, opening))
is_brackets_closed = True
stack = []
for i, el in enumerate(string):
if el in opening:
stack.append(el)
elif el in closing:
if (len(stack)):
last_element = stack.pop()
if last_element != corresponding[el]:
is_brackets_closed = False
break
else:
is_brackets_closed = False
break
if len(stack):
is_brackets_closed = False
return is_brackets_closed
| true |
92cbac43042872e865e36942ce164e1d5fdb0d40 | SmischenkoB/campus_2018_python | /Kyrylo_Yeremenko/2/task7.py | 2,517 | 4.21875 | 4 | """
This script solves task 2.7 from Coding Campus 2018 Python course
(Run length encoding)
"""
def write_char_to_list(last_character, character_count):
"""
Convenience function to form character and count pairs for RLE encode
:param last_character: Character occurred on previous iteration
:param character_count: Count of mentioned character
:return: List to append to encode return string
"""
return_list = []
if character_count > 1:
return_list += [str(character_count), last_character]
else:
return_list += last_character
return return_list
def rle_encode(string):
"""
Encodes string using Run-Length encoding
:param string: Input raw string
:return: RLE-encoded string
"""
list_string = list(string)
last_character = None
character_count = 0
return_list = []
for index in range(len(list_string)):
character = list_string[index]
if last_character != character:
if last_character is not None:
return_list += write_char_to_list(last_character, character_count)
last_character = character
character_count = 1
else:
character_count += 1
if index == (len(list_string) - 1):
return_list += write_char_to_list(last_character, character_count)
return ''.join(return_list)
def rle_decode(string):
"""
Decodes string using Run-Length encoding
:param string: Input encoded string
:return: Raw decoded string
"""
list_string = list(string)
last_character = None
is_last_character_number = False
character_count = 0
return_list = []
number_buffer = []
for character in list_string:
if not character.isdigit() and is_last_character_number:
count = int(''.join(number_buffer))
return_list += [character for i in range(count)]
number_buffer.clear()
is_last_character_number = False
if character.isdigit():
number_buffer.append(character)
is_last_character_number = True
else:
return_list += character
return ''.join(return_list)
print("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")
print(rle_encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"))
print(rle_decode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"))
| true |
c1ea2fc8c755e9ca87fb78c8938a01c82d1e302c | SmischenkoB/campus_2018_python | /Kyrylo_Yeremenko/3/task1.py | 2,019 | 4.1875 | 4 | """
This script solves task 3.1 from Coding Campus 2018 Python course
(Spell number)
"""
NUM_POWS_OF_TEN = {100: 'Hundred', 1000: 'Thousand', 1000000: 'Million'}
NUMS = \
{
0: "Zero",
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine",
10: "Ten",
11: "Eleven",
12: "Twelve",
13: "Thirteen",
14: "Fourteen",
15: "Fifteen",
16: "Sixteen",
17: "Seventeen",
18: "Eighteen",
19: "Nineteen",
20: "Twenty",
30: "Thirty",
40: "Forty",
50: "Fifty",
60: "Sixty",
70: "Seventy",
80: "Eighty",
90: "Ninety"
}
def say_number_less_hundred(number):
"""
Spells number that is less than 100
:param number: Integer between 0 and 100
:return: String containing spelled number, if number is higher than range then empty string
"""
return_string = ""
if number < 20:
return_string = NUMS[number]
elif number < 100:
return_string = NUMS[number - number % 10]
if number % 10 != 0:
return_string += ' ' + NUMS[number % 10]
return return_string
def say_number(number):
"""
Spells given number in string
:param number: Integer between 0 and 999 999 999 999
:return: String containing spelled number or None if number is not in range
"""
if not 0 < number < 999999999999:
return None
return_string = say_number_less_hundred(number)
if not return_string:
max_power = max([key for key in NUM_POWS_OF_TEN.keys() if key <= number])
return_string = say_number(int(number / max_power)) + ' ' + NUM_POWS_OF_TEN[max_power]
if number % max_power != 0:
return_string += ' ' + say_number(number % max_power)
return return_string
| false |
c955386992b1cf118dd6b8c1ffb792c98a12012e | SmischenkoB/campus_2018_python | /Dmytro_Shalimov/1/8.py | 1,062 | 4.125 | 4 | <<<<<<< HEAD
print("Validate a 24 hours time string.")
user_input = input("Enter time: ")
if len(user_input) != 5:
print(False)
hours = user_input[:2]
minutes = user_input[3:]
if hours.isnumeric() and minutes.isnumeric():
hours_in_int = int(hours)
minutes_in_int = int(minutes)
if hours_in_int < 0 or hours_in_int > 23:
print(False)
elif minutes_in_int < 0 or minutes_in_int > 59:
print(False)
else:
print(True)
else:
print(False)
=======
print("Validate a 24 hours time string.")
user_input = input("Enter time: ")
if len(user_input) != 5:
print(False)
hours = user_input[:2]
minutes = user_input[3:]
if hours.isnumeric() and minutes.isnumeric():
hours_in_int = int(hours)
minutes_in_int = int(minutes)
if hours_in_int < 0 or hours_in_int > 23:
print(False)
elif minutes_in_int < 0 or minutes_in_int > 59:
print(False)
else:
print(True)
else:
print(False)
>>>>>>> 715fd0763b415a13fb28a483f258a5eadc1ec931
| true |
92295f2ad2b0ed8ff4d35474780dba9dc88e16e5 | SmischenkoB/campus_2018_python | /Kateryna_Liukina/3/3.5 Verify brackets.py | 766 | 4.25 | 4 | def verify_brackets(string):
"""
Function verify brackets
Args:
string(str): string to verify brackets
Returns:
bool: return true if all brackets are closed and are in right order
"""
brackets_opening = ('(', '[', '{')
brackets_closing = (')', ']', '}')
brackets_dict = dict(zip(brackets_opening, brackets_closing))
bracket_stack = []
for ch in string:
if ch in brackets_opening:
bracket_stack.append(ch)
elif ch in brackets_closing:
if len(bracket_stack) == 0:
return False
if ch == brackets_dict[bracket_stack[-1]]:
bracket_stack.pop(-1)
else:
return False
return(len(bracket_stack) == 0)
| true |
2d9d5ecb3a53c62da62052da5f849c71384a0300 | SmischenkoB/campus_2018_python | /Mykola_Horetskyi/3/Crypto Square.py | 1,074 | 4.125 | 4 | import math
def encode(string):
"""
Encodes string with crypto square method
Args:
string (str) string to be encoded
Returns:
(str) encoded string
"""
encoded_string = "".join([character.lower() for character in string
if character.isalpha()])
length = len(encoded_string)
number_of_columns = math.ceil(math.sqrt(length))
encoded_string = "".join([encoded_string[i::number_of_columns] for i in range(number_of_columns)])
return encoded_string
def decode(string):
"""
Decodes string encoded with crypto square method
Args:
string (str) string to be decoded
Returns:
(str) dencoded string
"""
decoded_string = "".join([character.lower() for character in string
if character.isalpha()])
length = len(decoded_string)
number_of_rows = math.floor(math.sqrt(length))
decoded_string = "".join([decoded_string[i::number_of_rows] for i in range(number_of_rows)])
return decoded_string
| true |
e63105840c53f6e3ea05835cb8a67afe38e741cc | SmischenkoB/campus_2018_python | /Lilia_Panchenko/1/Task7.py | 643 | 4.25 | 4 | import string
input_str = input('Your message: ')
for_question = 'Sure.'
for_yelling = 'Whoa, chill out!'
for_yelling_question = "Calm down, I know what I'm doing!"
for_saying_anything = 'Fine. Be that way!'
whatever = 'Whatever.'
is_question = False
if ('?' in input_str):
is_question = True
is_yelling = True
has_letters = False
is_yelling = input_str.isupper()
has_letters = input_str.islower() or is_yelling
if (not has_letters):
print(for_saying_anything)
elif (is_question):
if (is_yelling):
print(for_yelling_question)
else:
print(for_question)
elif (is_yelling):
print(for_yelling)
else:
print(whatever)
| true |
3f2039d4698f8b153ef13deaee6ec80e266dae3c | SmischenkoB/campus_2018_python | /Yurii_Smazhnyi/2/FindTheOddInt.py | 402 | 4.21875 | 4 | def find_odd_int(sequence):
"""
Finds and returns first number that entries odd count of times
@param sequence: sequnce to search in
@returns: first number that entries odd count of times
"""
for i in sequence:
int_count = sequence.count(i)
if int_count % 2:
return i
test_list = [1, 2, 3, 4, 5, 6, 2, 3, 3, 1]
print(find_odd_int(test_list))
| true |
5fbf80dd6b1bc1268272eb9e79c6c6e792dcc680 | SmischenkoB/campus_2018_python | /Tihran_Katolikian/2/CustomMap.py | 606 | 4.3125 | 4 | def custom_map(func, *iterables):
"""
Invokes func passing as arguments tuples made from *iterables argument.
:param func: a function which expects len(*iterables) number of arguments
:param *iterables: any number of iterables
:return: list filled with results returned by func argument. length of list
will be equal to a length of the shortest iterable argument
:rtype: list
"""
results = [func(*args) for args in zip(*iterables)]
return results
find_sum = lambda x, y: x + y
sum_of_vectors = custom_map(find_sum, [1, 2, 1], [-1, -2, -1])
print(sum_of_vectors)
| true |
8b4e88df052850d51cc6541535b0d4dddcdf2a0a | SmischenkoB/campus_2018_python | /Lilia_Panchenko/2/Allergies.py | 1,075 | 4.21875 | 4 | def two_pow(pow):
"""
two_pow(pow)
This function returns 2 in pow 'pow'
Args:
pow (int): pow to perform
Returns:
int: result of performing pow 'pow' on base 2
"""
return 2**pow
def allergies(score):
"""
allergies(score)
This function returns list of person's allergies
Args:
score (int): cumulated allergy score
Returns:
list: list of allergies
"""
allergies = {
'eggs' : 1,
'peanuts' : 2,
'shellfish' : 4,
'strawberries' : 8,
'tomatoes' : 16,
'chocolate' : 32,
'pollen' : 64,
'cats' : 128
}
bin_score_list = []
while score > 0:
bin_score_list.append(score % 2)
score //= 2
patient_allergies = []
for i in range(len(bin_score_list)):
two_in_i = two_pow(i)
list_allergies_values = list(allergies.values())
if bin_score_list[i] > 0 and two_in_i in list_allergies_values:
index_to_look_for = list_allergies_values.index(two_in_i)
list_allergies_keys = list(allergies.keys())
patient_allergies.append(list_allergies_keys[index_to_look_for])
return patient_allergies
| false |
03cd271429808ad9cf1ca520f8463a99e91c9321 | SmischenkoB/campus_2018_python | /Tihran_Katolikian/2/FindTheOddInt.py | 1,183 | 4.375 | 4 | def find_odd_in_one_way(list_of_numbers):
"""
Finds an integer that present in the list_of_number odd number of times
This function works as efficient as possible for this task
:param list_of_numbers: a list of integers in which must be at least one integer
which has odd number of copies there
:return: an integer that present in the list_of_number odd number of times
"""
for number in list_of_numbers:
if list_of_numbers.count(number) % 2 == 1:
return number
def find_odd_in_second_way(list_of_numbers):
"""
Finds an integer that present in the list_of_number odd number of times.
This function is likely to work less efficient than find_odd_in_one_way function
:param list_of_numbers: a list of integers in which must be at least one integer
which has odd number of copies there
:return: an integer that present in the list_of_number odd number of times
"""
for i in list_of_numbers:
count = 0
for j in list_of_numbers:
if i == j:
count += 1
if count % 2 == 1:
return i
print(find_odd_in_second_way([1, 2, 3, 1, 3, 2, 1]))
| true |
a19c8d2bf61250e9789f95a202f86dafbe371166 | SmischenkoB/campus_2018_python | /Ruslan_Neshta/3/VerifyBrackets.py | 897 | 4.3125 | 4 | def verify(string):
"""
Verifies brackets, braces and parentheses
:param string: text
:return: is brackets/braces/parentheses matched
:rtype: bool
"""
stack = []
is_valid = True
for ch in string:
if ch == '(' or ch == '[' or ch == '{':
stack.append(ch)
elif ch == ')' or ch == ']' or ch == '}':
if len(stack) == 0:
is_valid = False
break
else:
if ch == ')' and stack[-1] == '(' or ch == ']' and stack[-1] == '[' or ch == '}' and stack[-1] == '{':
stack.pop(-1)
else:
stack.append(ch)
else:
is_valid = len(stack) == 0
return is_valid
if __name__ == "__main__":
line = 'Some string with parentheses( and brackets [])'
is_line_valid = verify(line)
print(is_line_valid)
| true |
6855d88767abbe577f76e8263f5b1ec6aa9a6dee | SmischenkoB/campus_2018_python | /Dmytro_Skorobohatskyi/2/armstrong_numbers.py | 917 | 4.125 | 4 | def amount_digits(number):
""" Function recognize amount of digit in number.
Args:
number(int): specified number
Returns:
int: amount of digits in number
"""
counter = 0
while number != 0:
counter += 1
number //= 10
return counter
def check_if_armstrong_number(number):
""" Function checks if passed number is armstrong.
Args:
number(int): specified number
Returns:
bool: Return True if number is armstrong,
otherwise - return False
"""
sum = 0
number_length = amount_digits(number)
process_number = number
while process_number != 0:
last_digit = process_number % 10
addition = last_digit ** number_length
sum += addition
process_number //= 10
is_armstrong_number = sum == number
return is_armstrong_number
| true |
05cbb9c991b61b3ad9fbe22fff411cb2ff6bba81 | SmischenkoB/campus_2018_python | /Mykola_Horetskyi/2/Run length encoding.py | 1,459 | 4.4375 | 4 | def rle_encode(original_string):
"""
Encodes string using run-length encoding
Args:
original_string (str) string to encode
Returns:
(str) encoded string
"""
encoded_string = ''
current_character = ''
character_count = 0
for character in original_string:
if character == current_character:
character_count += 1
else:
if character_count > 1:
encoded_string += str(character_count) + current_character
elif character_count ==1:
encoded_string += current_character
current_character = character
character_count = 1
if character_count > 1:
encoded_string += str(character_count) + current_character
elif character_count ==1:
encoded_string += current_character
return encoded_string
def rle_decode(encoded_string):
"""
Decodes string using run-length decoding
Args:
encoded_string (str) string to decode
Returns:
(str) decoded string
"""
decoded_string = ''
current_count_string = ''
for character in encoded_string:
if character.isdigit():
current_count_string += character
elif current_count_string:
decoded_string += int(current_count_string) * character
current_count_string = ''
else:
decoded_string += character
return decoded_string
| false |
9879e700bccb8329e9a1b5e5ddca71abfb0aa7ba | SmischenkoB/campus_2018_python | /Dmytro_Shalimov/2/1.py | 1,338 | 4.4375 | 4 | from collections import Counter
print("Given an array, find the int that appears an odd number of times.")
print("There will always be only one integer that appears an odd number of times.")
print("Do it in 3 different ways (create a separate function for each solution).")
def find_odd_number_1(sequence):
"""
Function find int which appears in function odd number of times.
There should be only one int that appears an odd number of times.
Uses method count()
:param list sequence: a list of ints
:return: int which appears odd number of times
:rtype: int
"""
number = 0
for x in sequence:
count = sequence.count(x)
if count % 2 != 0:
number = x
break
return number
def find_odd_number_2(sequence):
"""
Function find int which appears in function odd number of times.
There should be only one int that appears an odd number of times.
Uses Counter class
:param list sequence: a list of ints
:return: int which appears odd number of times
:rtype: int
"""
temp = Counter(sequence)
return list(temp.keys())[0]
user_input = input("Enter sequence using spaces: ")
numbers = list(map(int, user_input.split()))
print(find_odd_number_2(numbers))
| true |
3c2510888352bd0867e04bf557b473af4b4ecfa9 | SmischenkoB/campus_2018_python | /Kyrylo_Yeremenko/3/task5.py | 858 | 4.46875 | 4 | """
This script solves task 3.5 from Coding Campus 2018 Python course
(Verify brackets)
"""
brackets = \
{
'{': '}',
'[': ']',
'(': ')'
}
def verify_brackets(string):
"""
Verify that all brackets in string are paired and matched correctly
:param string: Input string containing brackets
:return: True/False depending on bracket validity
"""
bracket_stack = [character for character in string if character in brackets or character in brackets.values()]
bracket_stack.reverse()
pair_stack = []
while bracket_stack:
next_item = bracket_stack.pop()
if next_item in brackets:
pair_stack.append(brackets[next_item])
elif pair_stack and next_item != pair_stack.pop():
return False
return not pair_stack
| true |
c45867f3199dbb730ae4764ece11d7a4742af826 | walton0193/cti110 | /P3HW2_BasicMath_WaltonKenneth.py | 1,198 | 4.1875 | 4 | #This program is a calculator
#It performs basic math operations
#CTI - 110
#P3HW2 - BasicMath
#Kenneth Walton
#17 March 2020
def add(number1, number2):
return number1 + number2
def subtract(number1, number2):
return number1 - number2
def multiply(number1, number2):
return number1 * number2
print('Menu')
print('1. Add Numbers');
print('2. Multiply Numbers');
print('3. Subtract Numbers');
print('4. Exit')
number1 = int(input('Enter the first number: '))
number2 = int(input('Enter the second number: '))
operation = input(('''Enter the operation you would like to perform:
1 for addition
2 for multiplication
3 for subratction
'''))
if operation == '1':
print('number1 + number2 = ', add(number1, number2))
elif operation == '2':
print('number1 * number2 = ', multiply(number1, number2))
elif operation == '3':
print('number1 - number2 = ', subtract(number1, number2))
print('number1 - number2')
elif operation == '4':
exit('Program will terminate')
else:
print('Error, you have not chosen a valid operation. Please try again')
| true |
b0c99ad473d14d8488a904db839ca328c1cceb1d | Patricia-Henry/tip-calculator-in-python- | /tip_calculator_final.py | 440 | 4.28125 | 4 | print("Welcome to the Tip Calculator")
bill_total = float(input("What was the bill total? $"))
print(bill_total)
tip = int(input("How much of a tip do you wish to leave? 10, 12, 15 \n"))
people_eating = int(input("How many people are splitting the bill?"))
percentage_tip = tip / 100
tip_amount = bill_total * percentage_tip
total_bill = tip_amount + bill_total
amount_to_pay = total_bill / people_eating
print(amount_to_pay) | true |
28fcd79f93af5e8516506dcb1402152ff26b9cfb | samdoty/smor-gas-bord | /morty.py | 995 | 4.28125 | 4 | # If you run this there is a bunch of intro stuff that will print
a = 10
print(a + a)
my_income = 100
tax_rate = 0.1
my_taxes = my_income * tax_rate
print(my_taxes)
print('hello \nworld')
print('hello \tworld')
print(len('hello'))
print(len('I am'))
mystring = "Hello World"
print(mystring[2])
print(mystring[-1])
mystring2 = "abcdefghijk"
print(mystring2[2:])
# stop index below is upto but not including
print(mystring2[:3])
print(mystring2[3:6])
print(mystring2[1:3])
# for what ever reason you can do this to get everything
print(mystring2[::])
# same thing to reverse
print(mystring2[::-1])
# there is this step size thing to jump every character
print(mystring2[::2])
print(mystring2[::3])
# start : stop : step size
# Immutability
name = "Sam"
# name[0] = 'P' doesn't work
last_letters = name[1:]
print(last_letters)
# String Concatenation
print('P' + last_letters)
x = 'Hello '
print(x + 'my name is Sam')
letter = 'z'
print(letter * 10)
print(letter.upper) | true |
d928744c32bde2b1aa046090a2fac343b2faf10d | SallyM/implemented_algorithms | /merge_sort.py | 1,458 | 4.1875 | 4 | def merge_sort(input_list):
# splitting original list in half, then each part in half thru recursion
# until left and right are each one-element lists
if len(input_list) > 1:
# print 'len(input_list)= {}'.format(len(input_list))
split = len(input_list)//2
left = input_list[: split]
right = input_list[split :]
# print 'split list ', left, right
# recursion
merge_sort(left)
merge_sort(right)
i = 0
j = 0
k = 0
# print 'i', i
# print 'j', j
# print 'k', k
while i < len(left) and j < len(right):
# comparing elements at each position of split lists, then merging them into one list
if left[i] < right[j]:
input_list[k] = left[i]
i += 1
# print 'i', i
else:
input_list[k] = right[j]
j += 1
# print 'j', j
k += 1
# print 'k', k
while i < len(left):
input_list[k] = left[i]
i += 1
k += 1
# print 'i', i
# print 'k', k
# print 'merged list', input_list
while j < len(right):
input_list[k] = right[j]
j += 1
k += 1
# print 'j', j
# print 'k', k
# print 'merged list', input_list
return input_list
| true |
6f74a09eb4b76315055d796874feeb993514e8f7 | USFMumaAnalyticsTeam/Kattis | /Autori.py | 590 | 4.1875 | 4 | # This python code is meant to take a single string that is in a
# long naming variation (ex. Apple-Boy-Cat) and change it
# to a short variation (ex. ABC)
import sys
# Receive user input as string
long_var = input()
# Verify user input is no more than 100 characters
if (long_var.count('') > 100):
sys.exit()
# Create an empty list
my_list = []
# Go through each letter in string
# and check if it's uppercase
# If so add to list
for letter in long_var:
if (letter.isupper()) == True:
my_list.append(letter)
# print list
print ("".join(my_list)) | true |
e9c7187e3f56e6bd0dd46ac18c0ff70b879eb0b0 | sahilshah1/algorithm-impls | /course_schedule_ii.py | 2,497 | 4.15625 | 4 | # There are a total of n courses you have to take, labeled from 0 to n - 1.
#
# Some courses may have prerequisites, for example to take course 0 you have
# to first take course 1, which is expressed as a pair: [0,1]
#
# Given the total number of courses and a list of prerequisite pairs,
# return the ordering of courses you should take to finish all courses.
#
# There may be multiple correct orders, you just need to return one of them.
# If it is impossible to finish all courses, return an empty array.
#
# For example:
#
# 2, [[1,0]]
# There are a total of 2 courses to take. To take course 1 you should have finished course 0.
# So the correct course order is [0,1]
#
# 4, [[1,0],[2,0],[3,1],[3,2]]
# There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2.
# Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3].
# Another correct ordering is[0,2,1,3].
#
import unittest
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = {}
for i in xrange(0, numCourses):
graph[i] = {"has_prereqs": set(),
"is_prereq_for": set()}
for prereq in prerequisites:
course = prereq[0]
req = prereq[1]
graph[course]["has_prereqs"].add(req)
graph[req]["is_prereq_for"].add(course)
courses = []
courses_with_no_prereqs = filter(lambda x: not graph[x]["has_prereqs"], graph.keys())
while courses_with_no_prereqs:
courses.append(courses_with_no_prereqs.pop(0))
if len(courses) == numCourses:
return courses
for next_course in graph[courses[-1]]["is_prereq_for"]:
graph[next_course]["has_prereqs"].remove(courses[-1])
if not graph[next_course]["has_prereqs"]:
courses_with_no_prereqs.append(next_course)
return []
class CourseScheduleIITest(unittest.TestCase):
def test_find_order_basic(self):
order = Solution().findOrder(2, [[1,0]])
self.assertEquals(order, [0, 1])
def test_key_error(self):
order = Solution().findOrder(4, [[0, 1], [3, 1], [1, 3], [3, 2]])
self.assertEquals(order, [])
if __name__ == '__main__':
unittest.main() | true |
81f3c89de7aebd1d982e710bdf87ad9e62334f5e | heyese/python_jumpstart | /birthday.py | 1,973 | 4.34375 | 4 | import datetime
def get_birth_date():
print('Please tell me when you were born:')
year = int(input('Year [YYYY]: '))
month = int(input('Month [mm]: '))
day = int(input('Day [dd]: '))
print('\n')
bdate = datetime.date(year, month, day)
return bdate
def is_a_leap_year(year):
leap_year = False
if year % 4 == 0:
leap_year = True
if year % 100 == 0:
leap_year = False
if year % 400 == 0:
leap_year = True
return leap_year
def leap_year_check(date):
# If person was born on Feb 29, and the current
# year isn't a leap year, we should adjust the birthday
# for the current year to be Feb 28.
if (date.month, date.day) == (2, 29):
print('Wow - you were born on Feb 29th! A leap year ...')
current_year = datetime.date.today().year
if is_a_leap_year(current_year):
print('This year, {}, is also a leap year.'.format(current_year))
else:
print('This year, {}, is not a leap year, so your birthday is / was Feb 28th.'.format(current_year))
return date - datetime.timedelta(days=1)
return date
def main():
# print header
print('{0}\n{1:^25}\n{0}'.format('-' * 25, 'BIRTHDAY APP'))
# Get date of birth
bdate = get_birth_date()
print('It looks like you were born on {}'.format(bdate))
# Do a leap year check
# Could be born on Feb 29 but have birthday on Feb 28 this year ...
bdate = leap_year_check(bdate)
today = datetime.date.today()
# Current year's birthday
birthday = datetime.date(today.year, bdate.month, bdate.day)
diff = today - birthday
if diff.days == 0:
print('Congrats! It\'s your birthday today!')
elif diff.days < 0:
print('It is your birthday in {} days time'.format(-diff.days))
else:
print('It was your birthday {} days ago'.format(diff.days))
if __name__ == '__main__':
main()
| false |
52d0586ed3cdbe18346e70d45883b74ec929e6c7 | pavankalyannv/Python3-Problems | /HackerRank.py | 1,718 | 4.34375 | 4 | Problme: @HackerRank
==========
Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
Input Format
-------------
The first line contains an integer, , the number of students.
The subsequent lines describe each student over lines; the first line contains a student's name, and the second line contains their grade.
Constraints
---------------
There will always be one or more students having the second lowest grade.
Output Format
----------------
Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.
Sample Input 0
---------------
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Sample Output 0
------------------
Berry
Harry
Explanation 0
---------------
There are students in this class whose names and grades are assembled to build the following list:
python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
The lowest grade of belongs to Tina. The second lowest grade of belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.
solution: python3
===========================
marksheet = []
for _ in range(0,int(input())):
marksheet.append([input(), float(input())])
second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))
| true |
944f2a67f38f40370b64c9e97914e355009b9c6b | lixuanhong/LeetCode | /LongestSubstring.py | 979 | 4.15625 | 4 | """
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
#思路:从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。直到扫描到最后一个字母。
class Solution:
def lengthOfLongestSubstring(self, s):
start = len_max = 0
char_dict = {}
for i in range(len(s)):
if s[i] in char_dict and start <= char_dict[s[i]]:
start = char_dict[s[i]] + 1
else:
len_max = max(len_max, i - start + 1)
char_dict[s[i]] = i
return len_max
obj = Solution()
print(obj.lengthOfLongestSubstring("pwwkew"))
| true |
6a9652efd51c9215b6a00cc5b1a626c971d2313a | lixuanhong/LeetCode | /IntegerToEnglishWords.py | 1,974 | 4.125 | 4 | """
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
Example 1:
Input: 123
Output: "One Hundred Twenty Three"
Example 2:
Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
"""
"""
思路:将数字以千为单位分组(3位数)。使用除法和取模运算将数字以千为单位拆分成数组,然后将其转化为单词。
题目中限定了输入数字范围为0到2^31 - 1之间,最高只能到billion位,3个一组也只需处理四组即可.
注意边界条件的处理,不需要考虑添加单词And。
"""
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
list1 = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Forteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
list2 = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
def words(n):
if n < 20:
return list1[n-1:n]
if n < 100:
return [list2[n/10 - 2]] + words(n%10) #cannot concatenate list object and 'str'
if n < 1000:
return [list1[n/100-1]] + ["Hundred"] + words(n%100)
for idx, value in enumerate(["Thousand", "Million", "Billion"], 1): #enumerate(iterable, start = 1) 表示enumerate从1开始counting, 否则默认是0
if n < 1000 ** (idx+1):
return words(n/1000**idx) + [value] + words(n%1000**idx)
return " ".join(words(num)) or "Zero" #注意:这里是用or!!
| false |
73cc42b9f05f5b83b6e81cee8f3aa2ad1ac786b8 | bo-boka/python-tools | /NumberTools/iterate.py | 1,265 | 4.1875 | 4 | def print_multiples(n, high):
i = 1
while i <= high:
print n*i, '\t',
i += 1
print
def print_mult_table(high):
i = 1
while i <= high:
print_multiples(i, high)
i += 1
def print_digits(n):
"""
>>> print_digits(13789)
9 8 7 3 1
>>> print_digits(39874613)
3 1 6 4 7 8 9 3
>>> print_digits(213141)
1 4 1 3 1 2
"""
while n:
j = n % 10
n = n/10
print j,
def num_even_digits(n):
"""
>>> num_even_digits(123456)
3
>>> num_even_digits(2468)
4
>>> num_even_digits(1357)
0
>>> num_even_digits(2)
1
>>> num_even_digits(20)
2
"""
i = 0
while n:
if n % 2 == 0:
i += 1
n = n / 10
return i
def sum_of_squares_of_digits(n):
"""
>>> sum_of_squares_of_digits(1)
1
>>> sum_of_squares_of_digits(9)
81
>>> sum_of_squares_of_digits(11)
2
>>> sum_of_squares_of_digits(121)
6
>>> sum_of_squares_of_digits(987)
194
"""
j = (n % 10)**2
while n:
n = n/10
j = j + (n % 10)**2
print j
if __name__ == '__main__':
import doctest
doctest.testmod()
| false |
df7978f0c6a2f0959ecf5ead00a2d05f18325b10 | gauravdhmj/Project | /if programfile.py | 2,761 | 4.1875 | 4 | name = input("please enter your name:")
age = input("How old are you, {0}".format(name))
age = int(input("how old are you, {0}".format(name)))
print(age)
# USE OF IF SYNTAX
if age >= 18:
print("you are old enough to vote")
print("please put an x in the ballot box")
else:
print("please come back after {} years".format(18 - age))
print("Please guess a number between 1 and 10:")
guess = int(input())
# Method 1
if guess < 5:
print("Please guess a higher number")
guess = int(input())
if guess == 5:
print("Well done ,you guessed it correctly")
else:
print("you have not guessed correctly")
elif guess > 5:
print("Please guess a lower number")
guess = int(input())
if guess == 5:
print("Well done ,you guessed it correctly")
else:
print("you have not guessed correctly")
else:
print("You got it right the first time")
# Method 2
if guess != 5:
if guess < 5:
print("Please guess higher")
else:
print("Please guess lower")
guess = int(input())
if guess == 5:
print("Well done ,you guessed it correctly")
else:
print("you have not guessed correctly")
else:
print("You got it right the first time")
# USE OF AND and OR
age = int(input("How old are you?"))
# if (age>=16 and age<=65):
if (16 <= age <= 65):
print("Have a good day at work")
if (age < 16) or (age > 66):
print("Enjoy your meal at work")
else:
print("have a good day at work")
x = "false"
if x:
print("x is true")
print("""False: {0}
None: {1}
0: {2}
0.0: {3}
empty list[]: {4}
empty tuple(): {5}
empty string '': {6}
empty string "": {7}
empty mapping {{}}: {8}
""".format(False,bool(None),bool(0),bool(0.0),bool([]),bool(()),bool(''),bool(""),bool({}) ))
x = input("Please enter some text")
if x:
print('You entered "{}" '.format(x) )
else:
print("you did not enter anything")
# USE OF NOT KEYWORD
print(not True)
print(not False)
# EXAMPLE OF NOT KEYWORD
age = int(input("how old are you,"))
if not(age <= 18):
print("you are old enough to vote")
print("please put an x in the ballot box")
else:
print("please come back after {} years".format(18 - age))
# USE OF IN KEYWORD(DONE IN PREVIOUS VIDEOS)
parrot = "Norwegnian blue"
letter = input("enter any character\n")
if letter in parrot:
print("give me the letter {} lol".format(letter))
else:
print("apne pass rakh ise")
# USE OF NOT IN KEYWORD
parrot = "Norwegnian blue"
letter = input("enter any character\n")
if letter not in parrot:
print("apne pass rakh ise")
else:
print("give me the letter {} lol".format(letter))
| true |
bdf2b0fe68c75b4e9c5fe1c1173ebd19fa8cf5ff | CHS-computer-science-2/python2ChatBot | /chatBot1.py | 808 | 4.40625 | 4 | #This is the starter code for the Chatbot
# <Your Name Here>
#This is a chatbot and this is a comment, not executed by the program
#Extend it to make the computer ask for your favorite movie and respond accordingly!
def main():
print('Hello this is your computer...what is your favorite number?')
#Declaring our first variable below called 'computerfavnumber' and storing the
#value 33
computerfavnumber=25
#We now declare a variable but set the variable to hold whatever the *user*
#inputs into the program
favnumber = input("Number please: ")
print(favnumber + '...is a very nice number indeed. So...what is your name?')
name=input()
print('what a lovely name: ' + name + '...now, I will reveal what my favourite number is:')
print (computerfavnumber)
main()
| true |
a66ee557c0557d6dfe61852771995e3143b74022 | thatdruth/Drew-Lewis-FinalCode | /ExponentFunction.py | 247 | 4.40625 | 4 |
print(3**3) #Easy exponent
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(4,3)) #A coded loop exponent function
| true |
f97a33df94c0b8bf5424a74bef1d7cc584b7bfb7 | GabrielDaKing/Amateur_ML | /amateur_ml/regression/linear.py | 1,448 | 4.34375 | 4 | class Linear:
"""
A class to handle the basic training and pridiction capability
of a Linear Regression model while storing the slope and intercept.
"""
def __init__(self):
self.slope = 0
self.intercept = 0
def fit(self, x, y):
"""
A function to set the slope and intercept of the line of regression i.e. fit the line to the given data.
Args:
x (list(float)): The independent variable values
y (list(float)): The dependent variable values
"""
self.slope = 0
self.intercept = 0
assert len(x)==len(y)
x_sq = [i**2 for i in x]
xy = [i*j for i,j in zip(x,y)]
sum_x = sum(x)
sum_y = sum(y)
sum_x_sq = sum(x_sq)
sum_xy = sum(xy)
n=len(x)
self.slope = ((n*sum_xy)-(sum_x*sum_y))/((n*sum_x_sq)-sum_x**2)
self.intercept = ((sum_y*sum_x_sq)-(sum_x*sum_xy))/((n*sum_x_sq)-sum_x**2)
def predict(self, x):
"""Predicts the values of the dependent variable based on the independent variable provided
Args:
x (list(float)): The independent variable values
Returns:
list(float): The predicted dependent values
"""
y = [self.slope*i+self.intercept for i in x]
return y
def __repr__(self):
return "Slope: "+str(self.slope)+"\nIntercept: "+str(self.intercept)
| true |
6cbb8bcbc7196063a08f9c9caf5b13433aa1ba05 | kiranrraj/100Days_Of_Coding | /Day_62/zip_in_python.py | 698 | 4.15625 | 4 | # Title : Zip function in python
# Author : Kiran Raj R.
# Date : 11:11:2020
languages = ["Malayalam", "tamil", "hindi", "english", "spanish"]
popularity = [10, 20, 50, 100, 40]
area = ['kerala', 'tamil nadu', 'north india', 'world', 'spain']
name =['kiran', 'vishnu', 'manu', 'sivan']
age = [32, 25,24]
first_zip = zip(languages, popularity, area)
second_zip = zip(name, age)
print(first_zip)
print(second_zip)
value1 = list(first_zip)
value2 = set(second_zip)
print(value1)
print(value2)
name ,age = zip(*value2)
print(f"Name: {name} Age: {age} ")
print("------------------------------------------")
for i in value1:
print(f"--Language: {i[0]} --Speaks in: {i[1]} --Popularity: {i[2]}") | false |
ef7fc6de72d7f28fe6dacb3ad4c2edfcebce3d3d | kiranrraj/100Days_Of_Coding | /Day_59/delete_elemt_linked_list_frnt_back.py | 1,971 | 4.375 | 4 | # Title : Linked list :- delete element at front and back of a list
# Author : Kiran raj R.
# Date : 30:10:2020
class Node:
"""Create a node with value provided, the pointer to next is set to None"""
def __init__(self, value):
self.value = value
self.next = None
class Simply_linked_list:
"""create a empty singly linked list """
def __init__(self):
self.head = None
def printList(self):
linked_list = []
temp = self.head
while(temp):
linked_list.append(temp.value)
temp = temp.next
print(f"The elements are {linked_list}")
def search_list(self, item):
temp = self.head
while temp.next != None:
temp = temp.next
if temp.value == item:
print(f"Found {temp.value}")
break
def delete_fist_elem(self):
if self.head == None:
print("The linked list is empty")
else:
self.head = self.head.next
def delete_elem_end(self):
# print(elem.next, elem.value)
if self.head == None:
print("The linked list is empty")
else:
temp = self.head
while temp != None:
if temp.next.next == None:
temp.next = None
temp = temp.next
sl_list = Simply_linked_list()
sl_list.head = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
sl_list.head.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
sl_list.printList()
sl_list.search_list(20)
sl_list.search_list(2)
sl_list.search_list(3)
print("List before deletion at start: ", end="")
sl_list.printList()
sl_list.delete_fist_elem()
print(f"List after deletion at start: ", end="")
sl_list.printList()
print("List before deletion at end: ", end="")
sl_list.printList()
sl_list.delete_elem_end()
print(f"List after deletion at end: ", end="")
sl_list.printList()
| true |
854616d109a06681b8765657cb5ba0e47689484f | kiranrraj/100Days_Of_Coding | /Day_12/dict_into_list.py | 537 | 4.15625 | 4 | # Title : Convert dictionary key and values into a new list
# Author : Kiran raj R.
# Date : 26:10:2020
# method 1 using dict.keys() and dict.values()
main_dict = {'a': 'apple', 'b': 'ball',
'c': 'cat', 'd': 'dog', 'e': 'elephant'}
list_keys = list(main_dict.keys())
list_values = list(main_dict.values())
print(list_keys, list_values)
# method 2 using dict.items()
listkeys = []
listvalues = []
for keys, values in main_dict.items():
listkeys.append(keys)
listvalues.append(values)
print(listkeys, listvalues)
| true |
19ea68c556c52b616ab33e76b24e779a21a8bc08 | kiranrraj/100Days_Of_Coding | /Day_7/count_items_string.py | 998 | 4.1875 | 4 | # Title : Find the number of upper, lower, numbers in a string
# Author : Kiran raj R.
# Date : 21:10:2020
import string
def count_items(words):
word_list = words.split()
upper_count = lower_count = num_count = special_count = 0
length_wo_space = 0
for word in words:
word = word.rstrip()
length_wo_space += len(word)
for index in range(len(word)):
if word[index].isupper():
upper_count += 1
if word[index].islower():
lower_count += 1
if word[index] in string.punctuation:
special_count += 1
if word[index].isnumeric():
num_count += 1
print(f"User entered string is: {words}")
print(f"Total length is {length_wo_space}\nSmall letters in string: {lower_count}\nCapital letters in string: {upper_count}\nSpecial characters in string: {special_count}\nNumbers count in string: {num_count}")
count_items("kiran raj r 12345 ,!# QWERR")
| true |
ec074f7136a4a786840144495d61960430c61c1c | kiranrraj/100Days_Of_Coding | /Day_26/linked_list_insert.py | 1,340 | 4.125 | 4 | # Title : Linked list insert element
# Author : Kiran Raj R.
# Date : 09:11:2020
class Node:
def __init__(self,data):
self.next = None
self.data = data
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
start = self.head
while start:
print(start.data)
start = start.next
def append_list(self, data):
new_elem = Node(data)
start = self.head
if start is None:
start = new_elem
return
while start.next is None:
start = start.next
start.next = new_elem
def prepand_list(self, data):
new_elem = Node(data)
new_elem.next = self.head
self.head = new_elem
def index_after(self, index, data):
start = self.head
new_elem = Node(data)
if not start:
print("The list is empty")
new_elem.next = index.next
index.next = new_elem
def index_before(self, index, data):
start = self.head
new_elem = Node(data)
if not start:
print("The list is empty")
while start:
if start.next == index:
new_elem.next = start.next
start.next =index
start = start.next
| true |
25ee94661cc1cce075df1356cbd9e9c76c9eb2be | kiranrraj/100Days_Of_Coding | /Day_47/check_tri_angle.py | 402 | 4.21875 | 4 | # Title : Triangle or not
# Author : Kiran Raj R.
# Date : 30/11/2020
angles = []
total = 0
for i in range(3):
val = float(input(f"Enter the angle of side {i}: "))
angles.append(val)
total = sum(angles);
# print(total)
if total == 180 and angles[0] != 0 and angles[1] != 0 and angles[2] != 0:
print("Valid angles for a triangle")
else:
print("Provided angles cannot form a triangle") | true |
037d537dcac93a71179b8e44f66441384778bc4e | kiranrraj/100Days_Of_Coding | /Day_52/palindrome.py | 442 | 4.125 | 4 | # Title : Palindrome
# Author : Kiran raj R.
# Date : 19:10:2020
userInput = input("Enter a number or word to check whether it is palinfrome or note :").strip()
reverse_ui = userInput[-1::-1]
# if userInput == reverse_ui:
# print(f"'{userInput}' is a palindrome")
# else:
# print(f"'{userInput}' is not a palindrome")
print(f"'{userInput}' is a palindrome") if userInput == reverse_ui else print(f"'{userInput}' is not a palindrome") | false |
13917f87c5fd24ee4f0f90bc0d5152aa2dccce83 | priyankaVi/Python | /challenge 3 #strings.py | 1,983 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
###challenge3 STRINGSabs
# In[ ]:
020
## Ask the user to enter their first name
##and then display the length of their name
# In[2]:
user=input("nter the first name")
len(user)
# In[ ]:
021
#Ask the user to enter their first name
#and then ask them to enter their surname.
#Join them together with a space between and
display the name
#and the length of whole name.
# In[4]:
user=input("enter the first name")
surname=input("enter the surname")
name= user+" "+surname
print("name")
len(name)
length=len(name)
print(length)
# In[ ]:
###Ask the user to enter their first name
and surname in lower case.
Change the case to title case
and join them together.
Display the finished result.
023
# In[7]:
user=input("enter the fiorstname")
surname=input("enter the surname")
surname.lower()
print(loweer)
# In[ ]:
#Ask the user to enter their first name.
#If the length of their first name is under five characters,
#ask them to enter their surname and
join them together (without a space) and
display the name in upper case.
If the length of the first name is five or more characters,
display their first name in lower case.
026
# In[12]:
user=input("enter the firstname")
if len(name)<5:
sur=input("enter the surname")
user=user+sur
else:
print(user.lower())
# In[11]:
user=input("enter the first name")
user=user.upper()
print(user)
# In[ ]:
026
###Pig Latin takes the first consonant of a word,
moves it to the end of the word
and adds on an “ay”.
If a word begins with a vowel you just add “way”
to the end. For example, pig becomes igpay,
banana becomes ananabay, and
aadvark becomes aadvarkway.
Create a program that will ask the
user to enter a word and change it into Pig Latin.
Make sure the new word is displayed in lower case.
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
| true |
4e78133f183038327019c656f1671b0c0c04d38c | dimaswahabp/Kumpulan-Catatan-Fundamental | /KumpulanCatatan/Daynote10.py | 2,614 | 4.25 | 4 | #10.1.1 How to make class
class Mobil:
warna = 'merah'
tahun = 2010
mobil1 = Mobil()
print(mobil1.warna)
print(vars(mobil1))
#10.1.2 How to make class properties
class MobilCustom():
def __init__(self, warna, tahun):
self.color = warna
self.year = tahun
mobil1 = MobilCustom(warna='pink', tahun=2010)
mobil2 = MobilCustom(warna='navy', tahun=2018)
print(mobil1.color)
print(mobil1.year)
class Mobil2():
def __init__(self, warna, tahun, model):
self.color = warna
self.year = tahun
self.model = model
mobil1 = Mobil2(warna='pink', tahun=2010, model=['A','B'])
mobil2 = Mobil2(warna='navy', tahun=2018, model=['C','D'])
print(mobil1.model)
print(mobil2.model)
class Mobil3():
def __init__(self, warna, tahun, model):
self.color = warna
self.year = tahun
self.model = model
def jadul(self):
if self.year < 2010:
return True
else:
return False
def spek_mobil(self):
return 'Warna mobil {0}, tahun mobil {1}, model mobil {2}'.format(self.color.upper(), self.year, self.model.upper())
#10.1.3 How to add function inside a class
mobil1 = Mobil3(warna='pink', tahun=2010, model='X')
mobil2 = Mobil3(warna='navy', tahun=2018, model='Z')
print(mobil1.model)
print(f'apakah jadul?', mobil1.jadul()) # --> how to call method inside class
print(mobil1.spek_mobil())
'''
class Mobil:
def __init__(self, warna, duduk):
self.color = warna
self.seat = duduk
class Hatcback(Mobil): # --------- Cara 1
pass
class Sedan(Mobil): # ------------ Cara 2
def __init__(self, warna, duduk):
X.__init__(self, warna, duduk)
class Car(Mobil): # -------------- Cara 3 (dengan menambahkan property baru)
def __init__(self, warna, duduk, gps, sound_sys, bel):
super().__init__(warna, duduk)
self.gps = gps
self.sound_sys = sound_sys
self.bel = bel
mobil1 = Mobil('Black', 4)
car1 = Car('Pink', 8, True, 'Simbada', True)
print(mobil1.color, mobil1.seat)
print(car1.color, car1.seat, car1.gps, car1.sound_sys, car1.bel)
print(vars(car1)) # --------- cara menampilkan semua variable
print(car1.__dict__) # ------ cara lain menampilkan semua variable
car1.velg = '18 inch'
print(vars(car1))
delattr(car1, 'velg') # ------ Tidak untuk menghapus property yang ada di Class
print(vars(car1))
del car1.color
print(vars(car1))
data_new_lambda = list(map(lambda x: Student(x['nama'], x['usia']),student_data))
print(data_new_lambda[0].nama)
print(data_new_lambda[0].usia)
'''
| false |
51f346a94b5b7df4ae2b093dabfd75fe076b2624 | andrefabricio-f/mateapp-clase-03 | /operaciones incrementadas.py | 234 | 4.125 | 4 | #Operaciones con Incremento
a = 23
print("a=23 -->", a)
a=a+1
print("a=a+1 -->", a)
a+=1
print("a+=1 -->", a)
#a++ -> ERROR
a*=2
print("a*=2 -->", a)
a/=2
print("a/=2 -->", a)
a-=2
print("a-=1 -->", a)
a**=2
print("a**=1 -->", a)
| false |
04ae203c5141337886d98e9902d3f91a09213988 | arturblch/game_patterns | /result/command.py | 1,848 | 4.34375 | 4 | # TODO: Улучшить обработчик ввода (InputHandler) описанный ниже.
# 1. Необходимо добавить возможность измение настройки кнопок. (Например поставить выстрел на ПКМ.)
# 2* Добавить возможность передавать в метод параметр(ы). (Например можно передавать юнит, который будет выполнять, команду)
# 3* Для возможности реализовать реплеи, необходимо реализовать "отменяемые" методы (хотя бы перемещения). Для примера дан класс Unit.
BUTTON_W = 1
BUTTON_A = 2
BUTTON_S = 3
BUTTON_D = 4
BUTTON_LBM = 5
BUTTON_RBM = 6
BUTTON_PRESSED = 1
def isPressed(button):
if button == BUTTON_PRESSED:
return True
return False
def moveForward():
print('Move forward')
def moveBackward():
print('Move backward')
def moveLeft():
print('Move left')
def moveRight():
print('Move right')
def shoot():
print('Shoot the gun!!')
def setAutoTarget():
print('Automatic targeting')
class InputHandler(object):
def handle_input(self):
if (isPressed(BUTTON_W)):
moveForward()
elif (isPressed(BUTTON_A)):
moveLeft()
elif (isPressed(BUTTON_S)):
moveBackward()
elif (isPressed(BUTTON_D)):
moveRight()
elif (isPressed(BUTTON_LBM)):
shoot()
elif (isPressed(BUTTON_RBM)):
setAutoTarget()
class Unit(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def moveTo(self, x, y):
self.x = x
self.y = y
print('Move to ({}, {})'.format(x, y))
| false |
8ebf60db3e82ed6276dadbf80487e09d5006f397 | zhongziqi/python_study | /python_cases/case_9.py | 246 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
# 等三秒打印我爱你
import time
obj = {'a':'i like you','b':'i love you'}
# print dict.values(obj)
# print dict.keys(obj)
# print dict.values(obj)
for key,value in dict.items(obj):
print value
time.sleep(3)
| false |
dfa353728f27230e57cde4ea7d3ed84d0746527a | ramlaxman/Interview_Practice | /Strings/reverse_string.py | 548 | 4.21875 | 4 | # Reverse a String iteratively and recursively
def reverse_iteratively(string):
new_string = str()
for char in reversed(string):
new_string += char
return new_string
def test_reverse_iteratively():
assert reverse_iteratively('whats up') == 'pu stahw'
def reverse_recursively(string):
print('')
length = len(string)
if length == 1:
return string
return string[length-1] + reverse_recursively(string[:-1])
def test_reverse_recursively():
assert reverse_recursively('whats up') == 'pu stahw'
| true |
799e14b86ce12ec280138c525258ffb8094bd399 | nickLuk/python_home | /16_1home2.py | 803 | 4.125 | 4 | # Програма пошуку святкових днів
day = int(input("Введіть день місяця: "))
mount = int(input("Введіть місяць: "))
def holy(day, mount):
if day == 1 and mount == 1:
print("<<<Новий рік>>")
elif day == 7 and mount == 1:
print("<<<Різдво>>>")
elif day == 8 and mount == 3:
print("<<<Міжнародний жіночий день>>>")
elif day == 9 and mount == 5:
print("<<<День перемоги>>>")
elif day == 28 and mount == 6:
print("<<<День конституції>>>")
elif day == 24 and mount == 8:
print("<<<День незалежності>>>")
else:
print("Цього свята нема в базі")
holy(day, mount) | false |
d516b1c2b45bf8145759ba5ae676f24c1c7384ce | ahmad-elkhawaldeh/ICS3U-Unit-4-03-python | /loop3.py | 779 | 4.5 | 4 | #!/usr/bin/env python3
# Created by: Ahmad El-khawaldeh
# Created on: Dec 2020
# a program that accepts a positive integer;
# then calculates the square (power of 2) of each integer from 0 to this number
def main():
# input
positive_integer = print(" Enter how many times to repeat ")
positive_string = input("Enter Here plz : ")
# process & output
try:
positive_integer = int(positive_string)
for loop_counter in range(positive_integer + 1):
positive_exponent = loop_counter ** 2
print("{0}² = {1}".format(loop_counter, positive_exponent))
except AssertionError:
print('Given input is not a number.')
except ValueError:
print('Given input is not a number.')
if __name__ == "__main__":
main()
| true |
88e33f77320d763870cd15d893ca18866b8daa3d | carlosmgc2003/guia1paradigmas5 | /ejercicio4.py | 876 | 4.15625 | 4 | #Escribir un programa que reciba como parametro un string de elementtos separados por coma y retorne
#una lista conteniendo cada elemento.
def formatear_lista(lista : list) -> list:
return list(map(lista_from_string, lista))
#Modificar la funcion anterior pero obteniendo correctamente cada dato segun su tipo, dado el siguiente
#orden int, string, bool.
#Modificar para que dada una lista de strings devuelva otra lista, pero con los campos formateados.
def lista_from_string(string : str) -> list:
lista = list(string.split(','))
return [int(lista[0]), lista[1], bool(lista[2])]
if __name__ == "__main__":
ejemplo = [
'14,Juana Perez,True',
'16,Raul Dell,False',
'18,Mariana Castillo,True',
'176,Pedro Rodriguez,False'
]
print(lista_from_string(ejemplo[0]))
print(formatear_lista(ejemplo))
| false |
93e6f42a043dccbdee8a819d44eb6e5367f7ff1d | MarcelaSamili/Desafios-do-curso-de-Python | /Python/PycharmProjects/funções/desafio 104.py | 600 | 4.15625 | 4 | # Crie um programa que tenha a função leiaInt(),
# que vai funcionar de forma semelhante ‘
# a função input() do Python, só que fazendo a
# validação para aceitar apenas um valor numérico. Ex: n = leiaInt(‘Digite um n: ‘)
def leiaint(msg):
ok = False
v = 0
while True:
n = str(input(msg))
if n.isnumeric():
v = int(n)
ok = True
else:
print('\033[31mESTA FORMA NÃO É VÁLIDA!\033[m')
if ok:
break
return v
n = leiaint('Digite um valor n:')
print(f'Voce acabou de digitar o número {n}') | false |
8d4ece54c9eec19652392378331799d49966efe3 | MarcelaSamili/Desafios-do-curso-de-Python | /Python/PycharmProjects/aula 14/desafio 059.py | 1,245 | 4.125 | 4 | #Crie um programa que leia dois valores e mostre um menu na tela:
'''[ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa'''
#Seu programa deverá realizar a operação solicitada em cada caso.
from time import sleep
print('MENU')
v1 = float(input('Digite um valor:'))
v2 = float(input('Digite outro valor:'))
resposta = 0
#n = [v1,v2]
multiplica = 0
while resposta != 5:
resposta = int(input('''[ 1 ] somar\n[ 2 ] multiplicar\n[ 3 ] maior\n[ 4 ] novos números\n[ 5 ] sair do programa\n>>>>O que voce que fazer?'''))#essas opções poderiam ser num print(), ue tb ira funcionar
if resposta == 1:
soma = v1 + v2
print('a soma de {} + {} é {}'.format(v1, v2, soma))
if resposta == 2:
multiplica = v1 * v2
print('O número {} x {} = {:.2f}'.format(v1,v2,multiplica))
if resposta == 3:
if v1 > v2:
print('{} é maior'.format(v1))
else:
print('{} é maior'.format(v2))
if resposta == 4:
v1 = float(input('Digite um valor:'))
v2 = float(input('Digite outro valor:'))
elif resposta == 5:
print('FINALIZANDO...')
sleep(1)
print('==='*10)
sleep(1)
print('OK! FIM DO PROGRAMA.')
| false |
baf5351dc7f66539d19f62e1fa9069fa5faca834 | MarcelaSamili/Desafios-do-curso-de-Python | /Python/PycharmProjects/aula 9/desafio 022.py | 966 | 4.28125 | 4 | #crie um programa que leia o nome completo de uma pessoa e mostre na tela:
#o nome com todas as letras maiusculas
#o nome com todas as letras minusculas
#quantas letras tem ao todo sem comsiderar os espaços
#quantas letras tem o primeiro nome
nome = str(input('Digite seu nome completo:')).strip()
print('Seu nome em maiusculo: {}'.format(nome.upper()))
print('Seu nome em minusculo: {}'.format(nome.lower()))
print('Seu nome ao todo tem {} letras'.format(len(nome)-nome.count(' ')))
d = nome.split()
print('Seu primeiro nome é {} e tem {} letras'.format(d[0],len(d[0])))
'''print('Seu primeiro nome tem {} letras'.format(nome.find(' ')))'''
#a logica disso é que como o programa começa acontar de 0, eu estou dizendo com esse (' ') espaço que é pra ele contar quantas letras tem de 0 ate o espaço
#e como eu ja coloquei em cima .strip()pra elininar espaços inicias e finais inuteis vai da certo, mais o melhor jeito é o primeio ele é mais lógic também.
| false |
beb1c1a8624e6f434571c831c831b82f247921b6 | MarcelaSamili/Desafios-do-curso-de-Python | /Python/PycharmProjects/aula 12/desafio 041.py | 905 | 4.28125 | 4 | #A Confederação Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta
#E mostre sua categoria, de acordo com a idade:
'''Até 9 anos: MIRIM ;Até 14 anos: INFANTIL; Até 19 anos: JÚNIOR; Até 25 anos: SÊNIOR; Acima de 25 anos: MASTER'''
from datetime import date
ano = int(input('Qual ano voce nasceu?'))
atual = date.today().year
idade = atual - ano
if idade <= 9:
print('Voce tem {} anos'.format(idade))
print('Voce é dacategoria MIRIM!')
elif idade <=14:
print('Voce tem {} anos'.format(idade))
print('Voce é da categoria INFNTIL!')
elif idade <= 19:
print('Voce tem {} anos'.format(idade))
print('Voce é da categoria JÚNIOR!')
elif idade <=25:
print('Voce tem {} anos'.format(idade))
print('Voce é da categoria SÊNIOR!')
elif idade >=26:
print('Voce tem {} anos'.format(idade))
print('Voce é da categoria MASTER!')
| false |
c0c7507d3d351d1cdd4dff4624acef7f54b4b52f | bikash-das/pythonprograms | /practice/check_list.py | 1,293 | 4.21875 | 4 | def is_part_of_series(lst):
'''
:param: lst - input is the set of integers (list)
:output: returns true if the list is a part of the series defined by the following.
f(0) = 0 f(1) = 1 f(n) = 2*f(n-1) - 2*f(n-2) for all n > 1.
'''
assert(len(lst) > 0)
if(lst[0] != 0):
return False
else:
if(len(lst) == 1):
return True
if(lst[1] != 1):
return False
else:
if(len(lst) == 2):
return True
a = 0 # first initial value is 0
b = 1 # second initial value is 1
i = 2 # loop variable starting at 2, because we already checked for index 0 and 1
lst_length = len(lst)
while(i < lst_length):
c = 2 * (b - a) # f(n) = 2 * (f(n-1) - f(n-2)) = 2 * (b - a)
if(c != lst[i]):
return False
a = b
b = c
i += 1
return True
if __name__ == "__main__":
print("Enter the list of integers seperated by a Space")
lst = [int(x) for x in input().split()]
if(is_part_of_series(lst)):
print("True: {}. List is PART of the Given Series".format(lst))
else:
print("False: {}. List is NOT PART of the Given Series".format(lst)) | true |
3ad3950e0d0b1cef1791b7563714f3ffec93d4ac | bikash-das/pythonprograms | /tkinter/ch-1/clickEvent2.py | 761 | 4.3125 | 4 | import tkinter as tk
from tkinter import ttk
# create an instance of window (tk)
win = tk.Tk() # creates an empty window
# action for button click
def click():
btn.configure(text = "Hello " + name.get()) # get() to retrive the name from the text field
# create a Label
ttk.Label(win, text = "Enter a name: ").grid(column = 0, row = 0)
# add a Text Box Entry widget, StringVar = string variable (telling beforehand)
name = tk.StringVar()
input = ttk.Entry(win, width = 15, textvariable = name) # width is hardcoded, it will not change
input.grid(column = 0, row = 1)
# add a Button
btn = ttk.Button(win, text = "Click", command = click)
btn.grid(column = 1, row = 1)
input.focus() # cursor focused in text box
# start the GUI
win.mainloop()
| true |
5e9c092473f6f2e780979df5f11b74d30db9d346 | bikash-das/pythonprograms | /ds/linkedlist.py | 1,233 | 4.15625 | 4 | class node:
def __init__(self,data):
self.value = data
self.next=None;
class LinkedList:
def __init__(self):
self.start = None;
def insert_last(self,value):
newNode = node(value)
if(self.start == None):
self.start = newNode;
else:
# search last node to insert
temp = self.start
while temp.next != None:
temp = temp.next
temp.next = newNode
def delete_first(self):
if(self.start == None):
print("Linked List Empty")
else:
#temp = self.start
self.start = self.start.next #if no second present than, start will contain None
def display_list(self):
if self.start == None:
print("List empty")
else:
temp=self.start
while(temp != None):
print(temp.value,end=" ")
temp = temp.next
if __name__ == '__main__':
mylist = LinkedList()
mylist.insert_last(10)
mylist.insert_last(20)
mylist.insert_last(30)
mylist.insert_last(40)
mylist.display_list()
print()
mylist.delete_first()
mylist.display_list()
| true |
b1578b627b3cd2f2f6675c4cab839c7665211440 | ToxicMushroom/bvp-python | /oefensessie 1/oefening4.py | 366 | 4.28125 | 4 | # first vector
x1 = float(input("Enter x-coordinate of the first vector: "))
y1 = float(input("Enter y-coordinate of the first vector: "))
# second vector
x2 = float(input("Enter x-coordinate of the second vector: "))
y2 = float(input("Enter y-coordinate of the second vector: "))
inwendig_product = x1 * x2 + y1 * y2
print("Ïnner product is:", inwendig_product) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.