blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
389ec37fa582b3d379b01d13b3f9aa44265dd922 | cvhs-cs-2017/sem2-exam1-jman7150 | /Encrypt.py | 1,703 | 4.34375 | 4 | """
Write a code that will remove vowels from a string and run it for the sentence:
'Computer Science Makes the World go round but it doesn't make the world round itself!'
Print the save the result as the variable = NoVowels
"""
def NoVowels(AnyString):
newString = ""
for ch in AnyString:
if ord(ch) is 97 or ord(ch) is 65:
newString = newString + ""
elif ord(ch) is 69 or ord(ch) is 101:
newString = newString + ""
elif ord(ch) is 73 or ord(ch) is 105:
newString = newString + ""
elif ord(ch) is 79 or ord(ch) is 111:
newString = newString + ""
elif ord(ch) is 85 or ord(ch) is 117:
newString = newString + ""
else:
newString = newString + ch
return newString
String = "Computer Science Makes the World go round but it doesn't make the world round itself!"
x = NoVowels(String)
print (x)
"""Write an encryption code that you make up and run it for the variable NoVowels"""
def NoVowels(x):
newString = ""
for ch in x:
if ord(ch) is 97 or ord(ch) is 65:
newString = newString + "$"
elif ord(ch) is 69 or ord(ch) is 101:
newString = newString + "^"
elif ord(ch) is 73 or ord(ch) is 105:
newString = newString + "*"
elif ord(ch) is 79 or ord(ch) is 111:
newString = newString + "%"
elif ord(ch) is 85 or ord(ch) is 117:
newString = newString + "!"
else:
newString = newString + ch
return newString
String = "Computer Science Makes the World go round but it doesn't make the world round itself!"
x = NoVowels(String)
print (x)
| true |
a7181fd0ddfc4fba1b653e06e05c34d917690dbb | JoshuaMeza/ProgramacionEstructurada | /Unidad 3-Funciones/Ejercicio43.py | 2,972 | 4.21875 | 4 | """
Author Joshua Immanuel Meza Magana
Version 1.0
Program who count how many positive and negative numbers are on N numbers, 0 break the count.
"""
#Functions
def specifyNumbers():
"""
It gets the N numbers that we will count.
Args:
_N (int): Value of the number of numbers
Returns:
The N numbers that will be counted
"""
_N=0
_N=int(input())
if _N<0:
while _N<0:
_N=int(input())
return _N
def inputNumbers(_N):
"""
Get a vector of the numbers that we will compare.
Args:
_N (int): Number of numbers
_listNumbers (list): The temporary list of numbers
num (int): Variable where the user input the numbers
con (int): Counter
Returns:
Values of the list of numbers
"""
_listNumbers=[]
num=0
con=0
while con<_N:
num=int(input())
con=con+1
if num==0:
con=_N
else:
_listNumbers.append(num)
return _listNumbers
def pResult(_N,_listNumbers):
"""
It calculates the amount of positive numbers.
Args:
_N (int): Number of numbers
_listNumbers (list): List of numbers
_pos (int): Ammount of positive numbers
Returns:
Ammount of positive numbers
"""
_pos=0
for x in _listNumbers:
if x>0:
_pos=_pos+1
return _pos
def nResult(_N,_listNumbers):
"""
It calculates the amount of negative numbers.
Args:
_N (int): Number of numbers
_listNumbers (list): List of numbers
_neg (int): Ammount of negative numbers
Returns:
Ammount of negative numbers
"""
_neg=0
for x in _listNumbers:
if x<0:
_neg=_neg+1
return _neg
def printResults(_pos,_neg):
"""
It print the amount of positive and negative numbers
Args:
_pos (int): Copy of the value of the positive numbers
_neg (int): Copy of the value of the negative numbers
Returns:
Nothing
"""
print(_pos)
print(_neg)
def main():
#Input
"""
It recives the N amount of numbers, and then it reads them.
Args:
N (int): Number of numbers
listNumbers (list): List of numbers
"""
N=0
listNumbers=[]
N=specifyNumbers()
listNumbers.extend(inputNumbers(N))
#Process
"""
Calculate how many positive and negative numbers are on the N numbers.
Args:
pos (int): Ammount of positive numbers
neg (int): Amount of negative numbers
N (int): Number of numbers
listNumbers (list): List of numbers
"""
pos=pResult(N,listNumbers)
neg=nResult(N,listNumbers)
#Output
"""
Print the results.
"""
printResults(pos,neg)
if __name__=="__main__":
main()
| true |
cf56c17dc4d5d912013ef55466911dee5e042fda | ainnes84/DATA520_HW_Notes | /Get_Weekday.py | 692 | 4.71875 | 5 | def get_weekday(current_weekday, days_ahead): # or day_current, days_ahead
""" (int, int) -> int
Return which day of the week it will be days_ahead days from
current_weekday.
current_weekday is the current day of the week and is in the
range 1-7, indicating whether today is Sunday (1), Monday (2),
..., Saturday (7).
days_ahead is the number of days after today.
>>> get_weekday(3, 1)
4
>>> get_weekday(6, 1)
7
>>> get_weekday(7, 1)
1
>>> get_weekday(1, 0)
1
>>> get_weekday(4, 7)
4
>>> get_weekday(7, 72)
2
"""
return (current_weekday + days_ahead - 1) % 7 + 1
| true |
babb5f609272132392a4e6b6f7fa4209f62ac2d5 | ainnes84/DATA520_HW_Notes | /file_editor.py | 1,719 | 4.21875 | 4 | import os.path
def file_editor(writefile):
while os.path.isfile(writefile):
rename = input('The file exists. Do you want to rename the file? (y/n)')
if rename == 'y':
print ('I will rename the ' + writefile + ' file.')
filename = input('Please give new file name (In .txt format)')
new_file = filename + '.txt'
rename_file = open(new_file,'w')
for line in open (writefile):
rename_file.write(line)
rename_file.close()
print ('Renaming file')
break
elif rename == 'n':
overwrite = input('Will not rename file. Would you like to overwrite the file? (y/n)')
if overwrite == 'y':
print ('I will overwrite the ' + writefile + ' file.')
with open(writefile, 'w') as file:
new_file = input ('Enter info to overwrite the file.')
file.write(new_file)
print ('Overwritting file')
break
elif overwrite == 'n':
cancel = input('Would you like to cancel? (y/n)')
if cancel == 'y':
print('I will cancel file editor!')
break
elif cancel == 'n':
print ('You chose not to cancel. Restarting program.')
continue
else:
print ('Invalid key pressed')
continue
print ('Writing over file')
else:
print ('Invalid Key Pressed')
continue
if __name__=='__main__':
file_editor('file_example.txt')
| true |
ea313897b6a0b264b0f492b6275dc3d7d8c0ad2b | ainnes84/DATA520_HW_Notes | /count_duplicates.py | 507 | 4.25 | 4 | def count_duplicates(dictionary):
""" (dict) -> int
Return the number of values that appear two or more times.
>>> count_duplicates({'A': 1, 'B': 2, 'C': 1, 'D': 3, 'E': 1})
1
"""
duplicates = 0
values = list(dictionary.values())
for item in values:
if values.count(item) >= 2:
duplicates = duplicates + 1
occurrences = values.count(item)
for x in range(occurrences):
values.remove(item)
return duplicates
| true |
87d9533f914f4a0cb9c25fbe838a45acd24b303c | kenny2892/RedditProfileSaver-C-Sharp | /Database/sqlite_helper.py | 1,467 | 4.21875 | 4 | import sqlite3
from sqlite3 import Error
# Source for how to use Sqlite in Python: https://www.sqlitetutorial.net/sqlite-python/
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def create_post(conn, reddit_posts):
"""
Create a new project into the projects table
:param conn:
:param reddit_posts:
:return: reddit_posts id
"""
sql = ''' INSERT INTO RedditPost(Number, Title, Author, Subreddit, Hidden, Date, UrlContent, UrlPost, UrlThumbnail, IsSaved, IsNsfw)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) '''
cur = conn.cursor()
cur.execute(sql, reddit_posts)
conn.commit()
return cur.lastrowid
def find_post_count(conn):
cur = conn.cursor()
cur.execute("SELECT * FROM sqlite_sequence")
rows = cur.fetchone()
return int(rows[1])
def select_all_post_keys(conn):
"""
Query all rows in the RedditPosts table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM RedditPost ORDER BY NUMBER DESC")
rows = cur.fetchall()
post_keys = []
for row in rows:
post_keys.append(row[2] + " - " + row[3] + " - " + row[6])
return post_keys | true |
20cff6b03d5d7d2cb34b24adc911f05701fb190f | ritasonak/Python-Samples | /Pluralsight/Fundamentals/Docstring_Demo.py | 470 | 4.125 | 4 | """Retrieve and print words from a URL
"""
import urllib2
def fetch_words(url):
"""Fetch a list of words from URL.
:param
url: The URL of a UTF-8 text document.
:return:
A list of strings containing the words from the document.
"""
story = urllib2.urlopen(url)
story_words = []
for line in story:
line_words = line.split()
for word in line_words:
story_words.append(word)
return story_words | true |
4f7140f2b36c772bee6f83d865e7fa2205c06979 | kmerchan/holbertonschool-interview | /0x1C-island_perimeter/0-island_perimeter.py | 2,591 | 4.28125 | 4 | #!/usr/bin/python3
"""
Defines function to calculate the perimeter of an island
represented by a list of list of ints
"""
def island_perimeter(grid):
"""
Calculates the perimeter of an island represented by a list of list of ints
parameters:
grid [list of list of ints]: represents the island & surrounding water
* 0s represent water & 1s represent land
* Each cell is a sqaure with side length of 1
* Cells are connected horizontally/vertically (not diagonally)
* Grid is rectangular, with width and height not exceeding 100
* The grid is completely surrounded by water
* Islands do not have "lakes" (water completely inside the island)
* There is only one island or nothing
returns:
the perimeter of the island
"""
error_msg = "grid must be a list of lists of ints representing an island"
if type(grid) is not list:
raise TypeError(error_msg)
for row in grid:
if type(row) is not list:
raise TypeError(error_msg)
for column in row:
if type(column) is not int:
raise TypeError(error_msg)
if column is not 0 and column is not 1:
raise ValueError(
"grid must contain only 0s & 1s representing water & land")
perimeter = 0
for row in range(len(grid)):
for column in range(len(grid[row])):
if grid[row][column] == 1:
perimeter += is_edge(grid, row, column)
return perimeter
def is_edge(grid, row, column):
"""
Determines if the given cell is on the edge of the island
parameters:
grid [list of lists of ints]: represents the island
row [int]: the index of row for the current cell
column [int]: the index of column for the current cell
returns:
1-4, if the given cell is on an edge, the number of edges
0, if the cell of land is in the interior of the island
"""
edge_count = 0
if row == 0:
edge_count += 1
if row == (len(grid) - 1):
edge_count += 1
if row != 0 and grid[row - 1][column] == 0:
edge_count += 1
if row != (len(grid) - 1) and grid[row + 1][column] == 0:
edge_count += 1
if column == 0:
edge_count += 1
if column == (len(grid[row]) - 1):
edge_count += 1
if column != 0 and grid[row][column - 1] == 0:
edge_count += 1
if column != (len(grid[row]) - 1) and grid[row][column + 1] == 0:
edge_count += 1
return edge_count
| true |
b1e36c377de098bebae5361b8bb64df364612c22 | ASHWINIBAMBALE/Calculator | /calculator.py | 818 | 4.15625 | 4 | def add(n1,n2):
return n1+n2
def subtract(n1,n2):
return n1-n2
def multiply(n1,n2):
return n1*n2
def divide(n1,n2):
return n1/n2
operations={
"+":add,
"-":subtract,
"*":multiply,
"/":divide
}
def calculator():
num1=float(input("Enter the first number:"))
for symbol in operations:
print(symbol)
shld_con=True
while shld_con:
operation_Symbol=input("Enter the opeartion from :")
num2=float(input("Enter the nxt number:"))
calculation=operations[operation_Symbol]
result=calculation(num1,num2)
print(f"{num1} {operation_Symbol} {num2}={result}")
cont=input(f"Type 'Y' to continue with {result} and 'N' to end: " ).lower()
if cont=="y":
num1=result
else:
shld_con=False
exit()
calculator()
| true |
926051d16f0ca8e3a19d98e8460c9ed27ea19700 | ehedaoo/Practice-Python | /Basic28.py | 412 | 4.1875 | 4 | # Write a Python program to print out a set
# containing all the colors from color_list_1 which are not present in color_list_2.
# Test Data :
# color_list_1 = set(["White", "Black", "Red"])
# color_list_2 = set(["Red", "Green"])
# Expected Output :
# {'Black', 'White'}
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print([x for x in color_list_1 if x not in color_list_2]) | true |
9b9912a3790e0af2a0fb1dc0ece3afcd3e5e990f | ehedaoo/Practice-Python | /Basic4.py | 212 | 4.28125 | 4 | # Write a Python program which accepts the user's first and last name
# and print them in reverse order with a space between them.
name = input("Enter your name please: ")
if len(name) > 0:
print(name[::-1]) | true |
8331b70e425b25d1cf4f1f8a08bfd316b4af4978 | ehedaoo/Practice-Python | /Basic3.py | 254 | 4.40625 | 4 | # Write a Python program which accepts the radius of a circle from the user and compute the area.
import math
radius = int(input("Enter the radius of the circle: "))
area1 = math.pi * pow(radius, 2)
print(area1)
area2 = math.pi * radius**2
print(area2) | true |
7352122a917e1228a98fdb984a84c1852852b3e6 | ehedaoo/Practice-Python | /Basic35.py | 552 | 4.3125 | 4 | # Write a Python program to add two objects if both objects are an integer type.
def add_numbers(a, b):
if not (isinstance(a, int) and isinstance(b, int)):
raise TypeError("Inputs must be integers")
return a + b
obj1 = int(input("Enter an integer 1: "))
obj2 = int(input("Enter an integer 2: "))
print(add_numbers(obj1, obj2))
# import ast
#
# def value():
# obj1 = input()
# try:
# return isinstance(ast.literal_eval(obj1), int)
# except ValueError:
# return ast.literal_eval(obj1)
#
# print(value())
| true |
8e4912c44b713408b18770aa1599ecdc4b120c14 | azrap/python-rest-heroku-deploy | /test.py | 762 | 4.34375 | 4 | import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
create_table = "CREATE TABLE users (id int, username text, password text)"
cursor.execute(create_table)
# must be a tuple
user = (1, 'jose', "superpass")
# the ? signifies parameters we'll insert
# must insert tuple with the number of ? = the parameters
insert_query = "INSERT INTO USERS values (?, ?, ?)"
cursor.execute(insert_query, user)
users = [(2, 'jan', "superpass"), (3, 'anne', "superpass")]
# executemany for many rows vs just one row
cursor.executemany(insert_query, users)
select_query = "SELECT * FROM users"
for row in cursor.execute(select_query):
print(row)
#commit = save
connection.commit()
# close the connection
connection.close()
| true |
69d66c38bbe996130ab3b880db60785903f3ec82 | IPostYellow/python100day | /7天专题函数/Day1.py | 1,595 | 4.28125 | 4 | '''第一天'''
'''
1.python中的函数是什么?
答:函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段,
只有在被调用时才会执行。要在Python中定义函数,需要使用def关键字。
'''
'''
2.python2和python3的range(100)的区别
python2返回列表,python3返回迭代器,节约内存
'''
'''
3.fun(args,**kwargs)中的args,**kwargs什么意思?
答:*args 和 **kwargs主要用于函数定义。你可以将不定数量的参数传递给一个函数。
这里的不定的意思是:预先并不知道函数的使用者会传递多少个参数给你,
所以在这个场景下使用这两个关键字。
*args和**kwargs可以同时在函数的定义中,但是args必须在**kwargs前面.
*args是用来发送一个非键值对的可变参数的参数列表给一个函数。
'''
def aaa(a, *args):
print(a)
for i in args:
print(i)
aaa('hi')
aaa('hi', 'hello', 'world')
'''
**kwargs允许你将不定长度的键值对作为参数传递给一个函数。
如果你想要在一个函数里处理带名字的参数,你应该使用**kwargs。
'''
def aaa(**kwargs):
for k, v in kwargs.items():
print(k, v)
aaa(name='maishu', city='San Francisco')
'''
什么是函数:函数是组织好的,重复使用的实现一定功能的代码段。
python2的range函数和python3的区别:python2返回列表,python3返回迭代器省内存
函数的可变参数:*args和**kwargs,*args表示发送一个可变参数的不带键值对的参数列表,**kwargs表示不定长的参数
''' | false |
a29906f6d600932ae8eb65adc4351ca5e9f1ff0e | Mukesh656165/Strings_datatypes | /str_programme.py | 652 | 4.125 | 4 | # write a programme to reverse a string
#Tech 1-> Using of slice method
s = 'rekoj'
op = s[::-1]
print(op)
# when using slice oprator step size should be a pos or neg number otherwise error
op1= s[::0]
print(op1)
# take input from user
s1 = input('enter a string to reverse :')
ops1= s1[::-1]
print(ops1)
#Tech -2
p = 'mukesh'
r = reversed(p)
print(r)
print(type(r))
for ch in r:
print(ch,end='')
#Tech - 3
p1 = 'mukesh_kumar'
r1 = reversed(p1)
output = ''.join(r1)
print(output)
#Tech -4
a = 'mukesh'
re = ''
i = len(a)-1
while i >=0:
re = re+a[i]
i = i-1
print(re)
Tech - 5
text = 'Mukesh'
l = ''
for i in text:
l = i+l
print(l)
| false |
508f310f385227201fccef2cfdfb8ebbcfd071b0 | rahcosta/Curso_em_Video_Python_3 | /Parte 2/9.5. Simulador de Caixa Eletrônico.py | 960 | 4.125 | 4 | '''Crie um programa que simule o funcionamento de um caixa eletrônico.
No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa
vai informar quantas cédulas de cada valor serão entregues.
OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.'''
print('-=' * 15)
print(' CAIXA ELETRÔNICO BANCO RCA')
print('-=' * 15)
valor = int(input('Digite o valor que deseja sacar: R$ '))
total = valor
cedula = 50
total_ced = 0
while True:
if total >= cedula:
total -= cedula
total_ced += 1
else:
if total_ced > 0:
print(f'Total de {total_ced} cédula(s) de R$ {cedula:.2f} reais')
if cedula == 50:
cedula = 20
elif cedula == 20:
cedula = 10
elif cedula == 10:
cedula = 1
total_ced = 0
if total == 0:
break
print('-=' * 15)
print('Agradecemos pela preferência! \nVolte sempre!') | false |
d09f6c8bfde750e9da883818308f201d5326a999 | rahcosta/Curso_em_Video_Python_3 | /Parte 2/6.2. Conversor de bases numéricas.py | 768 | 4.1875 | 4 | # ESCREVA UM PROGRAMA QUE LEIA UM NÚMERO INTEIRO QUALQUER E PEÇA PARA O USUÁRIO ESCOLHER
# QUAL SERÁ A BASE DE CONVERSÃO:
# 1 PARA BINÁRIO;
# 2 PARA OCTAL;
#3 PARA HEXADECIMAL.
n = int(input('Digite o número a ser convertido: '))
print('Escolha a base de conversão:')
print('[ 1 ] converter para BINÁRIO \n[ 2 ] converter para OCTAL \n[ 3 ] converter para HEXADECIMAL')
escolha = int(input('Sua opção: '))
if escolha == 1:
print(f'O número {n} convertido para Binário corresponde a {bin(n)[2:]}')
elif escolha == 2:
print(f'O número {n} convertido para Octal corresponde a {oct(n)[2:]}')
elif escolha == 3:
print(f'O número {n} convertido para Hexadecimal corresponde a {hex(n)[2:]}')
else:
print('Opção inválida. Tente novamente!') | false |
26c1a999204f51d76d53497f3e14b2494e57cf07 | rahcosta/Curso_em_Video_Python_3 | /Parte 2/8.7. Sequência de Fibonacci.py | 647 | 4.1875 | 4 | '''Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros
elementos de uma Sequência de Fibonacci. Exemplo:
0 – 1 – 1 – 2 – 3 – 5 – 8'''
'''Os números seguintes são sempre a soma dos dois números anteriores.
Portanto, depois de 0 e 1, vêm 1, 2, 3, 5, 8, 13, 21, 34…'''
elementos = int(input('Quantos elementos da Seguência de Fibonacci deseja mostrar? '))
n1 = 1
anterior = 0
cont = 2
print('0, 1,', end=' ')
while cont < elementos:
cont += 1
n1 = n1 + anterior
print(n1, end='')
if cont < elementos:
print(', ', end='')
anterior = n1 - anterior
print(' FIM')
| false |
a753c60df2e85e2e803c4632c53c3dde31dbc787 | rahcosta/Curso_em_Video_Python_3 | /Parte 2/8.2. Jogo da Advinhação 2.py | 936 | 4.125 | 4 | '''Melhore o jogo do exercício 5.1 onde o computador vai “pensar” em um número entre 0 e 10.
Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites
foram necessários para vencer.'''
from random import randint
from time import sleep
print('-' * 50)
print('Vamos ver se você é bom em advinhação? \nEu estou pensando em um número entre 0 e 10.')
print('-' * 50)
palpites = 0
computador = randint(0, 10)
usuario = int(input('Qual número eu pensei? '))
print('\033[7mProcessando...\033[m')
sleep(1)
while usuario != computador:
palpites += 1
print('\033[1;31mErrou!\033[m', end=(' '))
if usuario > computador:
print('Pensei num número MENOR...')
else:
print('Pensei num número MAIOR...')
usuario = int(input(f'Tente novamente: '))
print(f'''\033[1;34mParabéns, você acertou!\033[m
Você precisou de {palpites} tentativa(s) para acertar.''')
| false |
577263315755fd659705d83036e18c842096c63f | GitHubToMaster/PythonProgramFromIntroToPrac | /python_work/第一部分/cars.py | 584 | 4.46875 | 4 | cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort() #按照字母顺序升序排序,会对列表进行永久性修改
print(cars)
cars.sort(reverse=True) #按照字母顺序降序排序,会对列表进行永久性修改
print(cars)
cars2 = ['bmw', 'audi', 'toyota', 'subaru']
## 进行临时性排序
print(sorted(cars2))
print(sorted(cars2, reverse=True))
print(cars2)
## 对列表进行反转:倒着打印列表,
cars3 = ['bmw', 'audi', 'toyota', 'subaru']
cars3.reverse() #永久性的修改列表中元素的顺序,对列表中各个元素进行反转
print(cars3) | false |
5cb40df0d005df2a3c0caf071285b30911b6a0d2 | dduong7/dduong7-_pcc_cis012_homework | /Module 4/mathematical.py | 951 | 4.375 | 4 | # Create two variables (you pick the name) that have an integer value of 25,000,000 but one uses underscores as a
# thousand separator and the other doesn't.
var_int = 25000000
varr_int = 25_000_000
# Print out each variable using an f string with the following format "<Var Name>: <Var Value>" where <Var Name> is
# replaced with the variable name you selected and <Var Value> is it's variable.
print(f'var_int: {var_int}')
print(f'varr_int: {varr_int}')
# Create a variable (you pick the name) that has a float value of 175000.0 using the exponential (e) notation.
# Print the value to the terminal.
floating = 1.75e5
print(floating)
# Finally, prompt the user to enter a base and then an exponent. Print out to the user the following:
# <base> to the power of <exponent> = <value>
base = float(input("Enter a base"))
exponent = float(input("Enter a exponent"))
value = base**exponent
print(f'{base} to the power of {exponent} = {value}')
| true |
573c91766b1ece833891767b7c6a7ef7ae306398 | joew1994/isc-work | /python/tuples.py | 543 | 4.15625 | 4 | #a TUPLE = a sequence like a list, except it can not be modified once created
# created using normal brackets instead of square brackets
#but still index with square brackets
#emunerate function = produces index and values in pairs.
#question 1
t = (1,)
print t
print t[-1]
tup = range(100, 200)
print tup
tup2 = tuple(tup)
print tup
print tup2
print tup[0], tup[-1]
#question 2
mylist = [23, "hi", 2.4e-10]
for item in mylist:
print item, mylist.index(item)
for (count, item) in enumerate(mylist):
print count, item
| true |
6eccdf6c93349b1885f911e2a863bc95e39f07d3 | sdrsnadkry/pythonAssignments | /Functions/7.py | 361 | 4.28125 | 4 | def count(string):
upperCount = 0
lowerCount = 0
for l in string:
if l.isupper():
upperCount += 1
elif l.islower():
lowerCount += 1
else:
pass
print("Upper string Count: ", upperCount,
"\nLower String Count: ", lowerCount)
string = input("Enter a string: ")
count(string)
| true |
8e9d4540f197553ce8ee741201507c04075b4bd2 | danijar/training-py | /tree_traversal.py | 1,945 | 4.34375 | 4 | from tree import Node, example_tree
def traverse_depth_first(root):
"""
Recursively traverse the tree in order using depth first search.
"""
if root.left:
yield from traverse_depth_first(root.left)
yield root.value
if root.right:
yield from traverse_depth_first(root.right)
def traverse_breadth_first(root):
"""
Iteratively traverse the tree using breadth first search.
"""
queue = [root]
while queue:
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
yield node.value
def traverse_constant_space(root):
"""
Iteratively traverse the tree in order with using constant additional
space over the results list. Makes use of parent pointers.
"""
elements = []
node, child = root, None
while True:
# Visit left child if existing and not already done
if node.left and not child:
node, child = node.left, None
continue
# Add value if left was visited or didn't exist
if child is node.left:
elements.append(node.value)
# Visit right node if existing and not already done
if node.right and child is not node.right:
node, child = node.right, None
continue
# Traverse upwards if we are not the root
if node.parent:
node, child = node.parent, node
continue
break
return elements
def print_elements(title, elements):
title = '{: <18}'.format(title)
elements = ', '.join(str(x) for x in elements)
print(title, elements)
if __name__ == '__main__':
tree = example_tree()
tree.print()
print_elements('Depth first', traverse_depth_first(tree))
print_elements('Constant space', traverse_constant_space(tree))
print_elements('Breadth first', traverse_breadth_first(tree))
| true |
fa1c5da5d10b4a3b1e1a5b39301ad98c11294a89 | danijar/training-py | /digits_up_to.py | 2,656 | 4.25 | 4 | def digits(number):
"""Generator to iterate over the digits of a number from right to left."""
while number > 0:
yield number % 10
number //= 10
def count_digits_upto(the_number, the_digit):
"""Count the amount of digits d occuring in the numbers from 0 to n
with runtime complexity of O(log n)."""
count = 0
for index, digit in enumerate(digits(the_number)):
power = pow(10, index)
decimal = digit * power
number = the_number % (power)
count += index * (decimal // 10)
if digit > the_digit:
count += pow(10, index)
elif digit == the_digit:
count += number + 1
return count
def count_digits_upto_naive(the_number, the_digit):
"""Naive implementation of the above function useful for testing
with runtime complexity of O(n * log n)."""
count = 0
for number in range(1, the_number + 1):
for digit in digits(number):
if digit == the_digit:
count += 1
return count
def interactive():
print('Count the amount of digits d occuring in the numbers from 0 to n')
while True:
digit = int(input('d: '))
range_ = int(input('n: '))
print('Result: ', count_digits_upto(range_, digit))
print('Reference:', count_digits_upto_naive(range_, digit))
print('')
def test():
for base in range(1, 10):
for number in range(1, 1000):
result = count_digits_upto(number, base)
result_naive = count_digits_upto_naive(number, base)
assert result == result_naive
def benchmark(function=count_digits_upto, input_range=range(0, 10000)):
"""Compare algorithm with naive implementation and print timings in CSV format"""
import time
def measure(times, function, *args, **kwargs):
best = None
for i in range(times):
start = time.perf_counter()
result = function(*args, **kwargs)
duration = time.perf_counter() - start
best = min(best, duration) if best is not None else duration
return best
def measure_all(times, function, *args, **kwargs):
start = time.process_time()
for i in range(times):
function(*args, **kwargs)
duration = time.process_time() - start
return duration
print('input,1,2,3,4,5,6,7,8,9')
for number in input_range:
print(number, end='')
for base in range(1, 10):
duration = measure(5, function, number, base)
print(',' + str(duration), end='')
print('')
if __name__ == '__main__':
interactive()
| true |
75005f329735e2d241747d7d2cda7b06d6e30c94 | crystalDf/Automate-the-Boring-Stuff-with-Python-Chapter-01-Python-Basics | /MathOperators.py | 258 | 4.1875 | 4 | # ** Exponent
print(2 ** 3)
# % Modulus/remainder
print(22 % 8)
# // Integer division/ oored quotient
print(22 // 8)
# when the * operator is used on one string value and one integer value,
# it becomes the string replication operator.
print('Alice' * 5)
| true |
078d077ae95661565d3e657a19a8496b07a033e0 | jcburnworth1/Python_Programming | /computer_science/towers_of_hanoi_stacks/towers_of_hanoi_script.py | 2,841 | 4.3125 | 4 | ## Towers of Hanoi - CodeAcademy
from computer_science.towers_of_hanoi_stacks.stack import Stack
## Start the game
print("\nLet's play Towers of Hanoi!!")
# Create the Stacks
stacks = []
left_stack = Stack("Left")
middle_stack = Stack("Middle")
right_stack = Stack("Right")
## Add each individual stack in a large list
stacks += [left_stack, middle_stack, right_stack]
# Set up the Game
num_disks = int(input("\nHow many disks do you want to play with?\n"))
## If user enters < 3 disks, reprompt for a number
while num_disks < 3:
num_disks = int(input("\nEnter a number greater than or equal to 3\n"))
## Number of disks from above on the left stack
for disk in range(num_disks, 0, -1):
left_stack.push(disk)
## Calculate optimal moves and notify the user
num_optimal_moves = (2 ** num_disks) - 1
print("\nThe fastest you can solve this game is in {0} moves".format(num_optimal_moves))
# Get User Input
def get_input():
## Add towers first letter for moving
choices = [stack.get_name()[0] for stack in stacks]
## Prompt for where you want the moves to be made
while True:
## Print L, M, R for which stack you are selecting
for i in range(len(stacks)):
name = stacks[i].get_name()
letter = choices[i]
print("Enter {0} for {1}".format(letter, name))
## Capture the user input
user_input = input("")
## Return the index of the input letter
if user_input in choices:
for i in range(len(stacks)):
if user_input == choices[i]:
return stacks[i]
# Play the Game
num_user_moves = 0
## While right stack does not equal number of disk, play the game
while right_stack.get_size() != num_disks:
## Show user current layout of stacks
print("\n\n\n...Current Stacks...")
for stack in stacks:
stack.print_items()
## Prompt user for a move
while True:
print("\nWhich stack do you want to move from?\n")
from_stack = get_input()
print("\nWhich stack do you want to move to?\n")
to_stack = get_input()
## Determine if there is a valid move and either make of deny that move
if from_stack.get_size() == 0:
print("\n\nInvalid Move. Try again!.")
elif to_stack.get_size() == 0 or from_stack.peek() < to_stack.peek():
disk = from_stack.pop()
to_stack.push(disk)
num_user_moves += 1
break
else:
print("\n\nInvalid Move. Try again!.")
## Once all disks are on the right, notify user of how well they did
print("\n\nYou completed the game in {0} moves, and the optimal number of moves is {1}".format(num_user_moves,
num_optimal_moves)) | true |
b85a5495b451c01f5c992521c88e0514eb4be948 | jcburnworth1/Python_Programming | /basic_python/scrabble_functions.py | 2,600 | 4.28125 | 4 | ## Scrabble - CodeAcademy
## Initial Variables
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4,
1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
## Combine letters and points into a list
letters_to_points = {letter:point for letter, point in zip(letters, points)}
## Add the blank tile to the letter_to_points dictionary
letters_to_points.update({" ": 0})
## Update point totals
def update_point_totals(dictionary):
## Loop over player_to_words and score
for player, words in player_to_words.items():
## Initialize player_points to score and total words
player_points = 0
## Loop over that players words and add to player_points
for word in words:
player_points += score_word(word)
## Update the proper players points
player_to_points.update({player: player_points})
## Play a word
def play_word(player, word):
## Update word list for a given player
player_to_words[player].append(word)
## Run update to player scores
update_point_totals(player_to_words)
## Score the words
def score_word(word):
## Initialize variable to total score of a word
word_score = 0
## Loop over the word and total up the points
## Throw in an upper just in case
for letter in word.upper():
word_score += letters_to_points.get(letter, 0)
return word_score
## Test score_word function
brownie_points = score_word("brownie")
print("Brownie Score: " + str(brownie_points))
## player_to_words dictionary will capture the words played by each player
player_to_words = {"player1": ["blue", "tennis", "exit"],
"wordNerd": ["earth", "eyes", "machine"],
"Lexi Con": ["eraser", "belly", "husky"],
"Prof Reader": ["zap", "coma", "period"]}
## player_to_points dictionary will score the words by each player
player_to_points = {}
## Loop over player_to_words and score
for player, words in player_to_words.items():
## Initialize player_points to score and total words
player_points = 0
## Loop over that players words and add to player_points
for word in words:
player_points += score_word(word)
## Initial loop to score players
player_to_points.update({player: player_points})
## Print current scores from players_to_points
for player, score in player_to_points.items():
print("{player}'s current score: {score}".format(player = player, score = score)) | true |
e835849a8f28383c7368a132f7f936fe4a18a7a7 | JoeltonLP/python-exercicios | /ex004.py | 600 | 4.25 | 4 | #!/usr/bin/python3
# Faca um programa que leia algo pelo teclado e mostre na tela o seu tipo
#primitivo e todas as informacoes possiveis sobre ele.
something = input('Type something: ')
print('which type primitive value? {}' .format(type(something)))
print('only have space? {}' .format(something.isspace()))
print('is a number? {}' .format(something.isdecimal()))
print('is a alphanumeric? {}' .format(something.isnumeric()))
print('is a alpha? {}' .format(something.isalpha()))
print('is all upercase? {}' .format(something.isupper()))
print('is all lowercase? {}' .format(something.islower()))
| false |
baf1c9013f89e4e73e46ec3bac27f915ca6fb3fd | redi-vinogradov/leetcode | /rotate_array.py | 398 | 4.1875 | 4 | def rotate(nums, k):
""" The trick is that we are moving not just each value but slice of array
to it's new position by calculating value of modulus remainder
"""
k = k % len(nums)
if k == 0:
return
nums[:k], nums[k:] = nums[-k:], nums[:-k]
print(nums)
def main():
nums = [1,2,3,4,5,6,7]
k = 3
rotate(nums, k)
if __name__ == '__main__':
main()
| true |
e2c2a407cb7422c4529db7131b41aee5f065c027 | aragaomateus/PointOfService | /Main.py | 1,576 | 4.15625 | 4 | ''' Creating the restaurant pos program in python'''
from Table import Table
# Function for initializing the table objects assingning a number to it.
def initiateTables():
tablesGrid = [Table(i) for i in range(21)]
return tablesGrid
# Function for printing the floor map when needed.
def printTables(tables):
for i in range(1,21):
print(f'{tables[i].getNumber():2}', end = " | ")
if i == 5 or i == 10 or i == 15 or i == 20:
print("\n")
def mainMenu(tables):
printTables(tables)
option = input("a - Add Table:\no - Open Table:\n")
return option
def main ():
# variables declaration and initializations
tables = initiateTables()
userPasswords = []
userPasswords.append(1234)
'''
First page:
Enter your password: '''
password = 0
while password not in userPasswords:
password = int(input("Enter your password"))
if password not in userPasswords:
print("Wrong password type again")
option = mainMenu(tables)
if option == 'a':
print("Opening add table...")
elif option == 'o':
print("Opening open table...")
'''
Main Menu view:
a - Add Table:
number of the table:
number of people in the table:
Adding order to the table: for each seat:
{print out the orders}
o - Open Table:
a - Add new order
v - View orders
p - print bill
'''
main()
| true |
487e4a3fdbb30210d7a0faad073437bc88eb6892 | m120402/maule | /server.py | 1,859 | 4.15625 | 4 | import socket
# Tutorial came from:
# https://pythonprogramming.net/sockets-tutorial-python-3/
# create the socket
# AF_INET == ipv4
# SOCK_STREAM == TCP
# The s variable is our TCP/IP socket.
# The AF_INET is in reference to th family or domain, it means ipv4, as opposed to ipv6 with AF_INET6.
# The SOCK_STREAM means it will be a TCP socket, which is our type of socket.
# TCP means it will be connection-oriented, as opposed to connectionless.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# A socket will be tied to some port on some host.
# In general, you will have either a client or a server type of entity or program.
# In the case of the server, you will bind a socket to some port on the server (localhost).
# In the case of a client, you will connect a socket to that server, on the same port that the server-side code is using.
# For IP sockets, the address that we bind to is a tuple of the hostname and the port number.
s.bind((socket.gethostname(), 1234))
# Now that we've done that, let's listen for incoming connections.
# We can only handle one connection at a given time, so we want to allow for some sort of a queue, just incase we get a slight burst.
# If someone attempts to connect while the queue is full, they will be denied.
# Let's make a queue of 5
s.listen(5)
# And now, we just listen!
while True:
# now our endpoint knows about the OTHER endpoint.
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
# So we've made a connection, and that's cool, but we really want to
# send messages and/or data back and forth. How do we do that?
# Our sockets can send and recv data. These methods of handling data
# deal in buffers. Buffers happen in chunks of data of some fixed size.
# Let's see that in action:
clientsocket.send(bytes("Hey there!!!","utf-8")) | true |
4b6a42ff50842c497db16d19844b41ca8a23de27 | huangsam/ultimate-python | /ultimatepython/classes/basic_class.py | 2,673 | 4.625 | 5 | """
A class is made up of methods and state. This allows code and data to be
combined as one logical entity. This module defines a basic car class,
creates a car instance and uses it for demonstration purposes.
"""
from inspect import isfunction, ismethod, signature
class Car:
"""Basic definition of a car.
We begin with a simple mental model of what a car is. That way, we
can start exploring the core concepts that are associated with a
class definition.
"""
def __init__(self, make, model, year, miles):
"""Constructor logic."""
self.make = make
self.model = model
self.year = year
self.miles = miles
def __repr__(self):
"""Formal representation for developers."""
return f"<Car make={self.make} model={self.model} year={self.year}>"
def __str__(self):
"""Informal representation for users."""
return f"{self.make} {self.model} ({self.year})"
def drive(self, rate_in_mph):
"""Drive car at a certain rate in MPH."""
return f"{self} is driving at {rate_in_mph} MPH"
def main():
# Create a car with the provided class constructor
car = Car("Bumble", "Bee", 2000, 200000.0)
# Formal representation is good for debugging issues
assert repr(car) == "<Car make=Bumble model=Bee year=2000>"
# Informal representation is good for user output
assert str(car) == "Bumble Bee (2000)"
# Call a method on the class constructor
assert car.drive(75) == "Bumble Bee (2000) is driving at 75 MPH"
# As a reminder: everything in Python is an object! And that applies
# to classes in the most interesting way - because they're not only
# subclasses of object - they are also instances of object. This
# means that we can modify the `Car` class at runtime, just like any
# other piece of data we define in Python
assert issubclass(Car, object) and isinstance(Car, object)
# To emphasize the idea that everything is an object, let's look at
# the `drive` method in more detail
driving = getattr(car, "drive")
# The variable method is the same as the instance method
assert driving == car.drive
# The variable method is bound to the instance
assert driving.__self__ == car
# That is why `driving` is considered a method and not a function
assert ismethod(driving) and not isfunction(driving)
# And there is only one parameter for `driving` because `__self__`
# binding is implicit
driving_params = signature(driving).parameters
assert len(driving_params) == 1
assert "rate_in_mph" in driving_params
if __name__ == "__main__":
main()
| true |
1233b07fb7e52520645d588af089fee900483281 | huangsam/ultimate-python | /ultimatepython/syntax/loop.py | 2,727 | 4.4375 | 4 | """
Loops are to expressions as multiplication is to addition. They help us
run the same code many times until a certain condition is not met. This
module shows how to use the for-loop and while-loop, and also shows how
`continue` and `break` give us precise control over a loop's lifecycle.
Note that for-else and while-else loops exist in Python, but they are
not commonly used. Please visit this link for some examples:
https://stackoverflow.com/a/59491247/9921431
"""
def main():
# This is a `for` loop that iterates on values 0..4 and adds each
# value to `total`. It leverages the `range` iterator. Providing
# a single integer implies that the start point is 0, the end point
# is 5 and the increment step is 1 (going forward one step)
total = 0
for i in range(5):
total += i
# The answer is...10!
assert total == 10
# This is a `for` loop that iterates on values 5..1 and multiplies each
# value to `fact`. The `range` iterator is used here more precisely by
# setting the start point at 5, the end point at 0 and the increment
# step at -1 (going backward one step)
fact = 1
for i in range(5, 0, -1):
fact *= i
# The answer is...120!
assert fact == 120
# This is a simple `while` loop, similar to a `for` loop except that the
# counter is declared outside of the loop and its state is explicitly
# managed inside of the loop. The loop will continue until the counter
# exceeds 8
i = 0
while i < 8:
i += 2
# The `while` loop terminated at this value
assert i == 8
# This is a `while` loop that stops with `break` and its counter is
# multiplied in the loop, showing that we can do anything to the
# counter. Like the previous `while` loop, this one continues until
# the counter exceeds 8
i = 1
break_hit = False
continue_hit = False
other_hit = False
while True:
i *= 2
if i >= 8:
# The `break` statement stops the current `while` loop.
# If this `while` loop was nested in another loop,
# this statement would not stop the parent loop
break_hit = True
break
if i == 2:
# The `continue` statement returns to the start of the
# current `while` loop
continue_hit = True
continue
# This statement runs when the counter equals 4
other_hit = True
# The `while` loop terminated at this value
assert i == 8
# The `while` loop hit the `break` and `continue` blocks
assert break_hit is True
assert continue_hit is True
assert other_hit is True
if __name__ == "__main__":
main()
| true |
5191ec83e749d9e838e1984665e9a250069bcf84 | Yanaigaf/NextPy-Coursework | /nextpy1.1.py | 982 | 4.25 | 4 | import functools
# 1.0 - write a oneliner function that attaches a symbol to every element of an iterable
# and prints all elements as a single string
def combine_coins(symbol, gen):
return ", ".join(map(lambda x: symbol + str(x), gen))
print(combine_coins('$', range(5)))
# 1.1.2 - write a oneliner function that doubles every character in a string
def double_letter(my_str):
return ''.join((map(lambda x: x * 2, my_str)))
print(double_letter("python"))
# 1.1.3 - write a oneliner function that receives a number and returns
# all numbers that can be divided by four up to that number
def four_dividers(number):
return list(filter(lambda x: x % 4 == 0, range(1, number + 1)))
print(four_dividers(9))
print(four_dividers(3))
# 1.1.4 - write a oneliner function that receives a number and returns its sum of digits
def sum_of_digits(number):
return functools.reduce(lambda x, y: x + y, map(lambda x: int(x), str(number)), 0)
print(sum_of_digits(104))
| true |
2fa430c5e0cee76e4e9a8beecbbb4f63a2530739 | cmhuang0328/hackerrank-python | /introduction/2-python-if-else.py | 588 | 4.125 | 4 | #! /usr/bin/env python3
'''
Task
Given an integer, , perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of to , print Not Weird
If n is even and in the inclusive range of to , print Weird
If n is even and greater than , print Not Weird
Input Format
A single line containing a positive integer, n.
Constraints
1 <= n <= 100
'''
if __name__ == '__main__':
n = int(input())
# range function (x, y) means x to y - 1
if ( n in range(6, 21) or n % 2.0 == 1):
print("Weird")
else:
print("Not Weird")
| true |
9f1dc01dcb82ca4d2d6e223e8f43be93aa744b43 | CristianoFernandes/LearningPython | /exercises/Ex_033.py | 676 | 4.1875 | 4 | print('#' * 45)
print('#' * 15, 'Exercício 033', '#' * 15)
numero = int(input('Digite o primeiro numero: '))
numero2 = int(input('Digite o segundo numero: '))
numero3 = int(input('Digite o terceiro numero: '))
# Testa menor
menor = numero
if menor > numero2:
menor = numero2
if menor > numero3:
menor = numero3
# Testa maior
maior = numero
if maior < numero2:
maior = numero2
if maior < numero3:
menor = numero3
print('O menor número é {} e o maior é {}'.format(menor, maior))
# numeros = [numero, numero2, numero3]
# numeros_ordenados=sorted(numeros)
# print('O menor número é {} e o maior é {}'.format(numeros_ordenados[0], numeros_ordenados[2]))
| false |
2bbd8eeb959c2eb53dfe860f1b835df62ad3a131 | Archana-SK/python_tutorials | /Handling_Files/_file_handling.py | 2,036 | 4.21875 | 4 | # File Objects
# r ---> Read Only, w ---> Write Only, a ---> Append, r+ ---> Read and Write
# Reading file without using Context manager
f = open('read.txt', 'r')
f_contents = f.read()
print(f_contents)
f.close()
# Reading file Using Context Manager (No need to close the file explicitly when file is opened using contex manager)
with open('read.txt') as f:
f_contents = f.readlines() # Returns a List
for line in f_contents:
print(line, end='')
print('Number of lines in the file ', len(f_contents)) # Prints total number of lines in the file
with open('read.txt') as f:
f_contents = f.read() # Reads the entire contents of the file into a variable as string
print(f_contents, end='')
with open('read.txt') as f:
print(f.readline(), end='') # Reads one line at a time
print(f.readline(), end='')
print(f.readline(), end='')
with open('read.txt') as f:
line = f.readline()
while line:
print(line, end='')
line = f.readline()
with open('read.txt') as f:
for line in f: # Loads only one line at a time and prints the line
print(line, end='')
# Reading 10 characters at a time
size_to_read = 10
with open('read.txt') as f:
f_contents = f.read(size_to_read)
print(f_contents, end='')
f_contents = f.read(size_to_read)
print(f_contents, end='')
# Writing to file
with open('write.txt', 'a') as f:
f.write('Hello world')
f.write('\n')
# Working with Multiple Files
with open('from_file.txt', 'r') as wf:
with open('to_file.txt', 'w') as wt:
for line in wf:
wt.write(line)
# Printing the line's with line numbers
with open('from_file.txt') as f:
for linenumber, line in enumerate(f, start=1):
print(linenumber, line, end='')
# Reading the file in reversed order
with open('read.txt') as f:
for line in reversed(list(f)):
print(line, end='')
# Finding the length of each line in the text file
with open('read.txt') as f:
for line in f:
print(len(line))
| true |
10beb77fb6294dcb65c43870f26d86efae24096e | AndreiKorzhun/CS50x | /pset7_SQL/houses/roster.py | 870 | 4.125 | 4 | import cs50
import csv
from sys import argv, exit
# open database for SQLite
db = cs50.SQL("sqlite:///students.db")
def main():
# checking the number of input arguments in the terminal
if len(argv) != 2:
print(f"Usage: python {argv[0]} 'name of a house'")
exit(1)
# sample of students of the specified house
students = (db.execute('''
SELECT first, middle, last, birth
FROM students WHERE house = ?
ORDER BY last, first
''', argv[1]))
# iterates over each student
for row in students:
# doesn't display the middle name if it isn't specified
if row['middle'] == None:
print('{} {}, born {}'.format(row['first'], row['last'], row['birth']))
else:
print('{} {} {}, born {}'.format(row['first'], row['middle'], row['last'], row['birth']))
main()
| true |
f2f35bd0fa2e0a0bde87df9ca4274f8e1124ef37 | remycloyd/projects | /python Programs/miningRobots.py | 1,247 | 4.125 | 4 | # You are starting an asteroid mining mission with a single harvester robot. That robot is capable of mining one gram of mineral per day.
# It also has the ability to clone itself by constructing another harvester robot.
# That new robot becomes available for use the next day and can be involved in the mining process or can be used to construct yet another robot.
# Each day you will decide what you want each robot in your fleet to do.
# They can either mine one gram of mineral or spend the day constructing another robot.
# Write a program to compute a minimum number of days required to mine n grams of mineral.
# Note that you can mine more mineral than required. Just ensure that you spent the minimum possible number of days to have the necessary amount of mineral mined.
# Input: A single integer number n, which is the number of grams of mineral to be mined.
# The value of n will be between 1 and 1000000 (inclusive).
# Output: A single integer, the minimum number of days required to mine n grams of mineral.
def miningOp(n):
x = 0
if n == 0:
return 1
elif n == 1:
return 2
return min(miningOp(n - 1) + 1, miningOp(n - 1) + miningOp(n - 2))
print(miningOp(5))
# print([miningOp(n) for n in range(8)])
| true |
0bf11b0e84d68cd7ddc03aa21afb1ca27c75cf61 | balaji-s/Python-DSA | /mergesort.py | 1,197 | 4.15625 | 4 | count = 0
def mergesort(array_elements):
global count
if len(array_elements) > 1:
midpoint = len(array_elements)//2
left_half = array_elements[:midpoint]
right_half = array_elements[midpoint:]
#print(left_half)
#print(right_half)
mergesort(left_half)
mergesort(right_half)
i = 0
j = 0
k = 0
#print("splitting over")
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
array_elements[k] = left_half[i]
print(left_half[i],right_half[j])
i = i + 1
count += 1
else:
array_elements[k] = right_half[j]
count += 1
j = j + 1
k = k + 1
while i < len(left_half):
array_elements[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
array_elements[k] = right_half[j]
j += 1
k += 1
#print("another",array_elements)
print(count)
#array = [19,5,3,1,45,34,21]
array = [5, 3, 1, 0, 2, 4]
mergesort(array)
print(array) | false |
b671e84a60e0ca80d31d0d502ada7307005ed206 | Nickbonat22/CIS210 | /p51_binaryr.py | 2,722 | 4.25 | 4 | '''
Binary Encoding and Decoding Recursively
CIS 210 F17 Project 5, Part 1
Author: Nicholas Bonat
Credits:
Convert a non-negative integer to binary recursively and prints it. Then
converts back to decimal form and prints the value.
'''
import doctest
def dtob(n):
'''(int) -> str
Function dtob takes non-negative integer as a parameter and returns
its binary representation.
>>> dtob(27) #basic example of use
'11011'
>>> dtobr(-1) #boundary test
'n must be greater than or equal to 0'
>>> dtob(0) #edge case
'0'
>>> dtob(2) #edge case
'10'
'''
if type(n) == str:
strError = 'n must be a integer'
return strError
if n < 0:
error = 'n must be greater than or equal to 0'
return error
binary = ''
if n == 0:
return '0'
while n > 0:
b_remain = str( n % 2 )
n = n // 2
binary += b_remain
binary = binary[::-1]
return binary
def btod(b):
'''(str) -> int
Function btod takes a binary representation of an integer
as input and returns the corresponding integer.
>>> btod('0000')
0
>>> btod('1101')
13
>>> btod('111111')
63
'''
decimal = 0
power = len(b) - 1
for char in b:
num = int(char)
decimal += ( num * ( 2 ** power) )
power -= 1
return decimal
def dtobr(n):
'''(int) -> str
Function dtobr ecursively converts an interger to a
string of binary numbers.
>>> dtobr(27) #basic example of use
'11011'
>>> dtobr(-1) #boundary test
'n must be greater than or equal to 0'
>>> dtobr(0) #edge case
'0'
>>> dtobr(1) #edge case
'1'
>>> dtobr('2') #boundary case
'n must be a integer'
>>> dtobr(27888) #boundary case
'110110011110000'
'''
if type(n) == str:
strError = 'n must be a integer'
return strError
if n < 0:
error = 'n must be greater than or equal to 0'
return error
if n == 0:
return str(0)
if n == 1:
return str(1)
r = n % 2
b = n // 2
return str(dtobr(b))+str(r)
def main():
'''() -> None
Function main checks binary conversion functions by encoding and decoding
number
'''
number = int(input("Enter a non-negative integer: "))
binary = dtob(number)
binaryR = dtobr(number)
print('Binary format is {}'.format(binary))
print('Binary format recursively is {}'.format(binaryR))
decimal = btod(binary)
print('Back to decimal {}'.format(decimal))
if __name__ == '__main__':
doctest.testmod()
main()
| true |
c660f52deb7cbf8ee3cbe223e4611cc4971edb2a | Nickbonat22/CIS210 | /p1_2_fizzbuzz.py | 998 | 4.21875 | 4 | '''
Fizzbuzz
CIS 210 F17 Project 1-2
Author: Nicholas Bonat
Credits: N/A
Print a number or word based on if that number is divisble by 3,5, or both.
'''
def fb(n):
'''(int) -> None
Print 1 through n with every number divisible by 3 printing fizz, every
number divisible by 5 printing buzz, and every number divisible by 3 and
5 printing fizzbuzz.
>>> fb(0)
Game Over!
>>> fb(9)
1
2
fizz
4
buzz
fizz
7
8
fizz
Game Over!
>>> fb(15)
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
Game Over!
'''
for i in range(1,n+1):
if i % 3 == 0 and i % 5 == 0:
print("fizzbuzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print(i)
print("Game Over!")
return None
| false |
878ad2087a24100fce96b6cf80feb543fae809f1 | gordwilling/data-structures-and-algorithms | /unscramble-computer-science-problems/Task4.py | 1,297 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
from operator import itemgetter
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
if __name__ == '__main__':
callers = set(map(itemgetter(0), calls))
numbers_with_texts_out = map(itemgetter(0), texts)
numbers_with_texts_in = map(itemgetter(1), texts)
numbers_with_calls_in = map(itemgetter(1), calls)
not_telemarketers = set(numbers_with_texts_out) \
.union(numbers_with_texts_in) \
.union(numbers_with_calls_in)
possible_telemarketers = sorted(callers.difference(not_telemarketers))
print("These numbers could be telemarketers: ")
for number in possible_telemarketers:
print(number)
| true |
b848295a1ae8ed1915d00addf29610a1f218c167 | Hosen-Rabby/Learn-Python-The-Hard-Way | /access tuple items.py | 413 | 4.4375 | 4 | print("Can Access Tuple Items-by referring to the index number, inside square brackets")
thistuple = ("kat", "Gari", "toy","Laptop","TV")
print(thistuple[2])
print("Negative Indexing")
print("refers to the last item -",thistuple[-1])
print("refers to the 2nd last item -",thistuple[-2])
print("Range of Indexes")
print(thistuple[1:])
print(thistuple[1:6])
print(thistuple[:5])
print(thistuple[1:-1]) | true |
2f6886c8bce04639b618373074366bc9587e011f | nathanbrand12/training | /src/upperCase.py | 801 | 4.15625 | 4 | # message = 'Fugazi and his diamonds'
# message_2 = 'the plug'
# full_sentence = message + " " + message_2
# print(message.lower())
# '-----------------------'
# print(message.upper())
# '-----------------------'
# print(full_sentence.upper())
# '------------------------'
# print(full_sentence.lower())
print("MATHEMATICAL OPERATIONS")
import math
a =5
b = 21
b1 = 3
b2 = 5
c = a+b
d = c-b
e = b*a
f = math.sqrt(b)
sum_n= a+b+b1+b2
average_num = sum_n/4
average_num2 = a+b+b1+b2/4
print('ADDITION')
print(a+b)
print('ADDITION 2')
print(c)
print('SUBTRACTION')
print(d)
print('Multiplication')
print(e)
print('division')
print(b/a)
print('modulus')
print(b%a)
print('exponentials')
print(b**a)
print('square root')
print(f)
print('average')
print(average_num)
print('average 2')
print(average_num2)
| false |
0065eda3217c9a30b9d1950134dc7ee2e32cecff | nathanbrand12/training | /src/LCM.py | 681 | 4.15625 | 4 | # def lcm(x, y):
# if x > y:
# greater = x
# else:
# greater = y
# while(True):
# if((greater % x == 0) and (greater % y == 0)):
# lcm = greater
# break
# greater += 1
# return lcm
#
# num1 = float(input("Input first number: "))
# num2 = float(input("Input second number: "))
# result = lcm(num1, num2)
# print(result)
## N FACTORIAL
# def factorial(x):
# if x == 0:
# return 1
# elif x == 1:
# return 1
# elif x < 0:
# print("Invalid! Negative numbers cannot be computed")
# else:
# return x * factorial(x-1)
#
# x=int(input("Input number: "))
# print(factorial(x))
| true |
99bf18bfd7ff60cfd5232c098ac24abc46322804 | datdev98/cryptography | /cipher/additive_cipher.py | 632 | 4.125 | 4 | plain = 'abcdefghijklmnopqrstuvwxyz'
cipher = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encrypt(plain_text, key):
text = ''
for ch in plain_text:
text += cipher[(plain.index(ch) + key) % 26]
return text
def decrypt(cipher_text, key):
text = ''
for ch in cipher_text:
text += plain[(cipher.index(ch) -key) % 26]
return text
def main():
plain_text = input("Enter text: ")
key = int(input("Enter key: "))
result = encrypt(plain_text, key)
print('Encrypted text:', result)
print('Redecrypt:', decrypt(result, key))
if __name__ == '__main__':
main()
| false |
ba649ccca5473151dc9589d6af7ad1e6f5ecec70 | Neftali56/Tarea-02 | /porcentajes.py | 748 | 4.15625 | 4 | #encoding: UTF-8
# Autor: Neftalí Rodríguez Martínez, A01375808.
# Descripcion: Este programa lee el número de mujeres y hombres inscritos en una clase, calcula el número de alumnos
# inscritos, así como el porcentaje respectivo de mujeres y hombres.
# A partir de aquí escribe tu programa
num_mujeres = int (input("Ingrese el total de mujeres inscritas: "))
num_hombres = int (input("Ingrese el total de hombres inscritos: "))
totalalumnos = num_hombres + num_mujeres
porc_mujeres = (num_mujeres * 100) / totalalumnos
porc_hombres = (num_hombres * 100) / totalalumnos
print("El número de alumnos inscritos es: ", totalalumnos)
print ("El porcentaje de mujeres inscritas es: ", porc_mujeres)
print ("El porcentaje de hombres inscritos es: ", porc_hombres)
| false |
2116093f8ffbfa923aadafb438783606230009c4 | varshinicmr/varshinivenkatesh | /operators.py | 1,502 | 4.125 | 4 | def add(a,b):
return a+b
def sub(a,b):
return a-b
def mult(a,b):
return a*b
def divide(a,b):
return a/b
i=int(input("enter value of a: "))
j=int(input("enter value of b: "))
o=input("what do you want to do? +,-,*,/: ")
if(o=='+'):
res=add(i,j)
elif(o=='-'):
res=sub(i,j)
elif(o=='*'):
res=mult(i,j)
elif(o=='/'):
res=divide(i,j)
print(res)
enter value of a: 10
enter value of b: 5
what do you want to do? +,-,X,/: +
15
dl210@soetcse:~/varshini$ python3 operators.py
enter value of a: 20
enter value of b: 20
what do you want to do? +,-,x,/: -
0
dl210@soetcse:~/varshini$ python3 operators.py
enter value of a: 40
enter value of b: 10
what do you want to do? +,-,x,/: /
4.0
dl210@soetcse:~/varshini$ python3 operators.py
enter value of a: 20
enter value of b: 40
what do you want to do? +,-,x,/: x
Traceback (most recent call last):
File "operators.py", line 19, in <module>
res=mult(i,j)
File "operators.py", line 6, in mult
return axb
NameError: name 'axb' is not defined
dl210@soetcse:~/varshini$ python3 operators.py
enter value of a: 4
enter value of b: 7
what do you want to do? +,-,x,/: x
28
dl210@soetcse:~/varshini$ python3 operators.py
enter value of a: 7
enter value of b: 8
what do you want to do? +,-,x,/: x
Traceback (most recent call last):
File "operators.py", line 23, in <module>
print(res)
NameError: name 'res' is not defined
dl210@soetcse:~/varshini$ python3 operators.py
enter value of a: 8
enter value of b: 9
what do you want to do? +,-,x,/: *
72
| false |
40d1883293de62280485ab3c60ff6616b4ef1e8f | liangjian314/thinkpython2 | /chapter6:有返回值的函数/exercise6_2.py | 782 | 4.25 | 4 | # 回文词(palindrome)指的是正着拼反着拼都一样的单词,如 “noon”和“redivider”。 按照递归定义的话,如果某个词的首字母和尾字母相同,而且中间部分也是一个回文词,那它就是一个回文词
# 编写一个叫 is_palindrome 的函数,接受一个字符串作为实参。如果是回文词,就返回 True ,反之则返回 False。记住,你可以使用内建函数 len 来检查字符串的长度。
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if len(word) <= 1:
return True
if first(word) != last(word):
return False
return is_palindrome(middle(word))
print(is_palindrome('noon'))
| false |
3d3614529418f856f6ebeb6f6ca8c526a91ba707 | liangjian314/thinkpython2 | /chapter9:文字游戏/exercise9_5.py | 360 | 4.125 | 4 | # 编写一个名为uses_all的函数,接受一个单词和一个必须使用的字符组成的字符串。
# 如果该单词包括此字符串中的全部字符至少一次,则返回True。
def uses_all(word, uses_str):
for letter in uses_str:
if letter not in word:
return False
return True
print(uses_all('hell', 'hello'))
| false |
7f2fc6389628f4d74de363e5cea3327d3041bf39 | ankitbansal2101/data-structures | /queue.py | 1,731 | 4.1875 | 4 | #fifo(first in first out)
#using list
q=[]
q.insert(0,"a")
q.insert(0,"b")
q.insert(0,"c")
q.pop()
#using deque
from collections import deque
q=deque()
q.appendleft("a")
q.appendleft("b")
q.appendleft("c")
q.pop()
#using inbuilt queue
# Initializing a queue
q = Queue(maxsize = 3)
# qsize() give the maxsize
# of the Queue
print(q.qsize())
# Adding of element to queue
q.put('a')
q.put('b')
q.put('c')
# Return Boolean for Full
# Queue
print("\nFull: ", q.full())
# Removing element from queue
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
# Return Boolean for Empty
# Queue
print("\nEmpty: ", q.empty())
q.put(1)
print("\nEmpty: ", q.empty())
print("Full: ", q.full())
# This would result into Infinite
# Loop as the Queue is empty.
# print(q.get())
#using python class
class Queue:
def __init__(self):
self.que=deque()
def enqueue(self,val):
self.que.appendleft(val)
def dequeue(self):
self.que.pop()
class Queue:
def __init__(self, head=None):
self.storage = [head]
def enqueue(self, new_element):
return self.storage.insert(0,new_element)
def peek(self):
return self.storage[-1]
def dequeue(self):
return self.storage.pop()
# Setup
q = Queue(1)
q.enqueue(2)
q.enqueue(3)
# Test peek
# Should be 1
print q.peek()
# Test dequeue
# Should be 1
print q.dequeue()
# Test enqueue
q.enqueue(4)
# Should be 2
print q.dequeue()
# Should be 3
print q.dequeue()
# Should be 4
print q.dequeue()
q.enqueue(5)
# Should be 5
print q.peek()
q=Queue()
q.enqueue("ankit")
print(q.que)
q.enqueue("bansal")
print(q.que)
q.dequeue()
print(q.que)
| true |
6d7c431c0d4d2d4938f1f939fe4f3b19096bdee5 | karinsasaki/Python_ML_projects | /guess_number_game/build/lib/guess_number_game/guess_number.py | 2,850 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 8 12:56:50 2020
@author: sasaki
"""
import random
import guess_number_game.utils as utils
#class Chosen:
# """Class of the chosen number.
#
# min_bound (int>=0): minimum bound of range the program can choose a number from. Default is 0.
# max_bound (int>=1): maximum bound of range the program can choose a number from. Default is 10.
# """
#
# def __init__(self, min_bound=0, max_bound=11):
# self.value = random.randint(min_bound, max_bound)
# self.bound_min = min_bound
# self.bound_max = max_bound
# self.digits_sum = None
# self.parity = None
#
# def get_digits_sum(self):
# r = 0
# n = self.value
# while n:
# r, n = r + n % 10, n // 10
# print(r)
# self.digits_sum = r
#
# def get_parity(self):
# if (self.value % 2) == 0:
# print('even')
# self.parity = 'even'
# else:
# print('odd')
# self.parity = 'odd'
def play_game(min_bound=0, max_bound=11, num_trials=5, seed=False):
"""Program randomly chooses a positive integer. Then prompts the user to guess the chosen number. In each wrong attempt the program will give a hint that the number is greater or smaller than the one guessed. Optionally, the user is also allowed to find out more information about the number, by querying the variable attributes.
Parameters:
min_bound (int>=0): minimum bound of range the program can choose a number from. Default is 0.
max_bound (int>=1): maximum bound of range the program can choose a number from. Default is 10.
num_trials (int>=1): number of chances user has to guess the correct number. Default is 5.
Returns:
val (int): 1 if the user huessed correctly, 0 if not.
"""
# check input parameters make sense
if max_bound <= min_bound:
raise ValueError#, ("max_bound should be greater than min_bound.")
if num_trials <= 0:
raise ValueError#, ("num_trials needs to be greater than 0.")
# randonly choose a number
# chosen = Chosen(min_bound, max_bound)
if seed:
random.seed(seed)
chosen = random.randint(min_bound, max_bound)
trial = num_trials
# give the user n goes
while trial >= 0:
if trial == 0:
print("Game over.")
else:
print("You have {} goes left.".format(trial))
# ask the user to guess the number
guess = int(input("Please guess an integer between {} and {}: ".format(min_bound, max_bound-1)))
# compare guessed number to chosen number and print hint
[txt, val] = utils.eval_guess(chosen, guess)
print(txt)
trial = trial - 1
if val == 1:
break
return(val) | true |
4f88343db2cd456fa3930da1b2ee0cf0d8793be1 | TARUNJANGIR/FSDP_2019 | /DAY2/Hands_On_1.py | 383 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 16:51:39 2019
@author: HP
"""
# Create a list of number from 1 to 20 using range function.
# Using the slicing concept print all the even and odd numbers from the list
our_list = list(range(21))
print (type(our_list))
print (our_list)
print ('even numbers>')
print (our_list[ ::2 ])
print('odd numvers>')
print (our_list[ 1::2 ]) | true |
2453dad75840fdb875fb6be8b330afa77c70e60d | KhairulIzwan/Python-for-Everybody | /Values and Types/Exercise/3/main.py | 732 | 4.6875 | 5 | #!/usr/bin/env python3
"""
Assume that we execute the following assignment statements:
width = 17
height = 12.0
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
1. width//2
2. width/2.0
3. height/3
4. 1 + 2 \* 5
"""
#
width = 17
height = 12.0
#
print("width: %.2f" % width)
print("height: %.2f" % height)
print("\n")
#
calc = width // 2
print("width // 2: %.2f" % calc)
print(type(calc))
print("\n")
#
calc = width / 2.0
print("width / 2.0: %.2f" % calc)
print(type(calc))
print("\n")
#
calc = height / 3
print("height / 3: %.2f" % calc)
print(type(calc))
print("\n")
#
calc = 1 + 2 * 5
print("1 + 2 * 5: %.2f" % calc)
print(type(calc))
print("\n")
| true |
40517f70d8c803ea2ed1184d6428d47b896d38b7 | michaelamican/python_starter_projects | /Python_Fundamentals/Functions_Basic_II.py | 1,511 | 4.3125 | 4 | #Countdown - Create a function that accepts a number as an input. Return a new array that counts down by one, from the number (as arrays 'zero'th element) down to 0 (as the last element). For example countDown(5) should return [5,4,3,2,1,0].
def count_down(int):
i = int
while i >= 0:
print(i)
i -= 1
#Print and Return - Your function will receive an array with two numbers. Print the first value, and return the second.
def print_return(x,y):
print(x)
return(y)
#First Plus Length - Given an array, return the sum of the first value in the array, plus the array's length.
def first_plus(arr)
for i in arr():
sum = len(arr())+arr[0]
return sum
#Values Greater than Second - Write a function that accepts any array, and returns a new array with the array values that are greater than its 2nd value. Print how many values this is. If the array is only element long, have the function return False
def greater_than_sec(arr):
arrnew = ['']
x = arr[1]
count = 0
if len(arr()) >= 2:
if i in arr > x:
arrnew.push(i)
count += 1
print(count)
return arrnew
#This Length, That Value - Write a function called lengthAndValue which accepts two parameters, size and value. This function should take two numbers and return a list of length size containing only the number in value. For example, lengthAndValue(4,7) should return [7,7,7,7].
def length_and_value(x,y):
len(arr()) = x
while i in arr():
i = y
return arr() | true |
5e3d78e715d03ac40400cc9ae33bf35b396be8bb | Ylfcynn/Python_Practice | /Python/TensorFlow/data_format.py | 1,397 | 4.125 | 4 | """
Deep Learning Using TensorFlow: Introduction to the TensorFlow library
An exercise with Matt Hemmingsen
A subfield of machine learning, inspired by the structure and function of the brain,
often called artificial neural networks.
Deep learning can solve broader problems without specifically defining each feature, unlike machine learning,
which solves specific problems according to specific dataset or constraints.
Input layer:
hiden layer: There be neuron!
Output layer:
Multiple hidden layers = 'deep neural network'
"""
import random
import pickle
import tensorflow
INPUTS = list()
OUTPUTS = list()
def equation(w, x, y, z):
"""
This models an arbitrary equation.
:param w:
:param x:
:param y:
:param z:
:return:
"""
first = x * y
second = w + first + z
return second / 2
def create_data(num):
global INPUTS
global OUTPUTS
for i in range(num):
w = random.randint(1, 1000)
x = random.randint(1, 5000)
y = random.randint(1, 25000)
z = random.randint(1, 100000)
INPUTS.append([w, x, y, z])
answer = equation(w, x, y, z)
OUTPUTS.append([answer])
create_data(100000)
train_x = INPUTS[:60000]
train_y = OUTPUTS[:60000]
test_x = INPUTS[60000:]
test_y = OUTPUTS[60000:]
with open('data_set.pickle', 'wb') as f:
pickle.dump([train_x, train_y, test_x, test_y], f)
| true |
423d2342360be47f1af94b4c9388a286dcc2235d | Ylfcynn/Python_Practice | /Python/atm-interface/atm_interface.py | 2,739 | 4.3125 | 4 | """
This is a menu for accessing a user's account. Logic is located in account.py
"""
from account import Account
import pychalk
acct = Account # pep484 annotations
USER_ACCOUNTS = dict() # Refactor this. If it stays global, UPPERCASE!
def user_menu(account):
"""
Displays a menu of user options and initiates operations.
:return:
"""
user_opts = {'1': 'Get balance', '2': 'Make a withdrawal', '3': 'Make a deposit', '4': 'Interest rate report'}
for key, value in user_opts.items():
print(key, ' ⟹ ', value, sep='\n')
selection = input('Please make a selection: ')
if selection == '1':
try:
balance = user_accounts['llama']
except KeyError:
print('Insufficient funds')
user_menu()
elif selection == '2':
try:
account.withdraw()
#balance = user_accounts['llama']
except KeyError:
print('Insufficient funds')
user_menu()
def make_account() -> acct:
new_ident = input('Please enter a unique identifier for your account name: ')
account = Account(new_ident)
return account
def retrieval():
pass
def login_menu() -> str:
"""
Displays a welcome menu with login and new account options.
:return:
"""
welcome_opts = {'1': 'Access your account', '2': 'Open a new account'}
for key, value in welcome_opts.items():
print(key, ' ⟹ ', value, sep='\n')
selection = input('>>> ')
if selection == '1':
ident = input('Please enter your account name: ')
if ident in USER_ACCOUNTS:
account = Account(ident)
user_menu(account)
else:
print('Account not found.')
login_menu()
elif welcome_opt == '2':
account = make_account()
print(f'The account {account.ident} has been created.')
user_menu(account)
else: # A while loop can also be used for error handling
print('Invalid. Please enter an option from the menu below. ')
return login_menu() # Take care to return this if the call is terminal.
def ようこそ():
welcome_prompt = '''
Welcome to the BankBuddy 2600® - "Keeping it safe. Keeping it secret.™"
Chernobog Industries, Inc.
Providing powerful and secure solutions for the financial industry since 2017.
Please select an option from the menu.
'''
print(welcome_prompt)
return login_menu()
ようこそ()
| true |
f56fbddeba596cb59d85c15de2aa5145769c2eb7 | Ylfcynn/Python_Practice | /credit.py | 1,799 | 4.375 | 4 | """
Goal
Write a function which returns whether a string containing a credit card number is valid as a boolean.
Write as many sub-functions as necessary to solve the problem.
Write doctests for each function.
--------------------
Instructions
1. Slice off the last digit. That is the **check digit**.
2. Reverse the digits.
3. Double every other element in the reversed list.
4. Subtract nine from numbers over nine.
5. Sum all values.
6. Take the second digit of that sum.
7. If that matches the check digit, the whole card number is valid.
For example, the worked out steps would be:
1. `4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 5`
2. `4 5 5 6 7 3 7 5 8 6 8 9 9 8 5`
3. `5 8 9 9 8 6 8 5 7 3 7 6 5 5 4`
4. `10 8 18 9 16 6 16 5 14 3 14 6 10 5 8`
5. `1 8 9 9 7 6 7 5 5 3 5 6 1 5 8`
6. 85
7. 5
8. Valid!
"""
def validate(account_number):
"""
>>> validate([4, 5, 5, 6, 7, 3, 7, 5, 8, 6, 8, 9, 9, 8, 5, 5])
Valid!
>>> validate([6, 5, 1, 6, 4, 3, 7, 5, 1, 6, 4, 9, 3, 8, 5, 4])
Invalid!
"""
plastic_fantastic = list() # Preferred over using 'var = []'
check_digit = str(account_number.pop())
smun = account_number[::-1]
for n in range(len(smun)):
elem = smun[n]
if n % 2 == 0:
elemite = elem * 2
else:
elemite = elem
plastic_fantastic.append(elemite)
plastic_bombastic = list()
for n in range(len(plastic_fantastic)):
num = plastic_fantastic[n]
if num > 9:
plastic_bombastic.append(num - 9)
else:
plastic_bombastic.append(num)
digi_two = str(sum(plastic_bombastic))[1]
if digi_two == check_digit:
print('Valid!')
else:
print('Invalid!')
return
| true |
dfd12c2fa65c0f412c9eb6d14003ee4b21447697 | Ylfcynn/Python_Practice | /hammer.py | 1,655 | 4.1875 | 4 | """
Write a function that returns the meal for any given hour of the day.
Breakfast: 7AM - 9AM
Lunch: 12PM - 2PM
Dinner: 7PM - 9PM
Hammer: 10PM - 4AM
>>> meal(7)
'Breakfast time.'
>>> meal(13)
'Lunch time.'
>>> meal(20)
'Dinner time.'
>>> meal(21)
'No meal scheduled at this time.'
>>> meal(0)
'Hammer time.'
>>> meal(3)
'Hammer time.'
>>> meal(9999)
'Not a valid time.'
>>> meal(99767676766799)
'Not a valid time.'
"""
#Hard coded solution
# def meal(hour):
# if hour in [5, 6]:
# result = 'No meal scheduled at this time.'
# elif hour in [7, 8, 9]:
# result = 'Breakfast time.'
# elif hour in [10, 11]:
# result = 'No meal scheduled at this time.'
# elif hour in [12, 13, 14]:
# result = 'Lunch time.'
# elif hour in [15, 16, 17, 18, 21]:
# result = 'No meal scheduled at this time.'
# elif hour in [19, 20]:
# result = 'Dinner time.'
# elif hour in [22, 23, 24, 0, 1, 2, 3, 4]:
# result = 'Hammer time.'
# else:
# result = 'Not a valid time.'
#
# return result
#
def meal(hour):
if hour >= 5 :
result = 'No meal scheduled at this time.'
elif hour in [7, 8, 9]:
result = 'Breakfast time.'
elif hour in [10, 11]:
result = 'No meal scheduled at this time.'
elif hour in [12, 13, 14]:
result = 'Lunch time.'
elif hour in [15, 16, 17, 18, 21]:
result = 'No meal scheduled at this time.'
elif hour in [19, 20]:
result = 'Dinner time.'
elif hour in [22, 23, 24, 0, 1, 2, 3, 4]:
result = 'Hammer time.'
else:
result = 'Not a valid time.'
return result
| true |
7486275b192534951ab95cecd52e752faa2d4e03 | VakinduPhilliam/Python_Data_Mapping | /Python_List_Comprehensions.py | 495 | 4.125 | 4 | # Python Data Structures List Comprehensions
# List comprehensions provide a concise way to create lists.
# Common applications are to make new lists where each element is the result
# of some operations applied to each member of another sequence or iterable,
# or to create a subsequence of those elements that satisfy a certain condition.
# For Example;
squares = list(map(lambda x: x**2, range(10)))
squares
# Or Equivalently
squares1 = [x**2 for x in range(10)]
squares1
| true |
1e5a4bbcf9b1a60bb2a882e12d2d02d49797c272 | VakinduPhilliam/Python_Data_Mapping | /Python_List_Comprehensions (Example).py | 847 | 4.375 | 4 | # Python Data Structures List Comprehensions
# List comprehensions provide a concise way to create lists.
# Common applications are to make new lists where each element is the result
# of some operations applied to each member of another sequence or iterable,
# or to create a subsequence of those elements that satisfy a certain condition.
# A list comprehension consists of brackets containing an expression followed by
# a for clause, then zero or more for or if clauses.
# The result will be a new list resulting from evaluating the expression in the
# context of the for and if clauses which follow it.
# For example, this listcomp combines the elements of two lists if they are not equal:
combs = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
combs
| true |
73e15841e0a78a26eed4a1e70ec7ba5ad684d649 | nealorven/Python-Crash-Course | /1_Chapter_Basics/6_Dictionaries/Exercises/6_12_extension.py | 739 | 4.15625 | 4 | # Улучшение предыдущего кода.
cities = {
'rio de janeiro': {
'country': 'brazil',
'population': 6.32,
'fact': 'guanabara bay',
},
'florence': {
'country': 'italy',
'population': 382.347,
'fact': 'cattedrale di santa maria del fiore',
},
'venice': {
'country': 'italy',
'population': 261.358,
'fact': 'shuttle trams',
},
}
for city, description in cities.items():
print(f"City: {city}:")
# Работаем со вторым вложенным кортежем
for key, value in description.items():
population = description['population']
print(f"Population:{population}")
| false |
e68972eea98411d80c0f9386cc34a90ceec75132 | nealorven/Python-Crash-Course | /1_Chapter_Basics/3_Lists/8_sort.py | 358 | 4.1875 | 4 | # Метод sort() сортирует от A..Z:
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort() # Постоянное изменение порядка
print(cars)
# ['audi', 'bmw', 'subaru', 'toyota']
# от Z..A
cars.sort(reverse=True) # Постоянное изменение порядка
print(cars)
# ['toyota', 'subaru', 'bmw', 'audi']
| false |
d7c3c6c4a14ffb9b23f57fcfbab464a35963b7f5 | nealorven/Python-Crash-Course | /1_Chapter_Basics/7_While_cycles/Exercises/7_3_multiples_of_10.py | 324 | 4.21875 | 4 | number = input("Enter a multiple of 10: ")
number = int(number)
if number % 10 == 0:
print(f"\nThe number {str(number)} is multiple.")
else:
print(f"\nThe number {str(number)} not multiple.")
# Enter a multiple of 10: 101
# The number 101 not multiple.
# Enter a multiple of 10: 110
# The number 110 is multiple.
| true |
bac7551316b9025f88671c580126d591119d2b62 | nealorven/Python-Crash-Course | /1_Chapter_Basics/5_if_Operator/Exercises/Interactive/2_for_if_else.py | 406 | 4.28125 | 4 | names = {
'robert green':'robertgreen@gmail.com',
'neal orven':'nealorven@gmail.com',
'alen frojer':'alenfrojer@gmail.com',
'bob eron':'boberon@gmail.com'
}
name_search = input("Write your username to search for a mailing address: ")
for name, mail in names.items():
if name_search in name:
print(f"User: {name_search.title()} owns this email address: {mail}.")
# Дописать вывод отсутствия имени и почты
| true |
17cc17340c7e0144ec4abf5d80c4675d873cde3c | webAnatoly/learning_python | /fromPythonBook/uniquewords1.py | 641 | 4.125 | 4 | #!/usr/bin/env python3.4
'''
Here is a program from a study book that I'm reading.
The programm lists every word and the
number of times it occurs in alphabetical order for all the files listed on the
command line:
'''
import string
import sys
words = {}
strip = string.whitespace + string.punctuation + string.digits + "\"'"
for filename in sys.argv[1:]:
for line in open(filename):
for word in line.lower().split():
word = word.strip(strip)
if len(word) > 2:
words[word] = words.get(word, 0) + 1
for word in sorted(words):
print("'{0}' occurs {1} times".format(word, words[word]))
| true |
c0dad9e3f04b628492da4feec32e5f97ac6be3e9 | ash301/kuchbhi | /leap.py | 734 | 4.4375 | 4 | #take the year as input
def function(year):
leap = False
if(year%4 == 0):
if(year%100 == 0):
if(year%400 == 0):
leap = True
else:
leap = True
return leap
year = int(input("Enter the Year : "))
print function(year)
#Documentation taken from url:
#https://support.microsoft.com/en-in/kb/214019
# To determine whether a year is a leap year, follow these steps:
# 1)If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
# 2)If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
# 3)If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
# 4)The year is a leap year (it has 366 days).
# 5)The year is not a leap year (it has 365 days).
| true |
798b22bb29bce19bf46d4583a2d3422bc9e428fc | joaoaffonsooliveira/curso_python | /desafios/desafio04.py | 719 | 4.28125 | 4 | # Dissecando uma variável
variavel_dissecada = input('Digite a variável que você quer dissecar: ')
print('O tipo primitivo da variável {} é: '.format(variavel_dissecada), type(variavel_dissecada))
print('{} Só tem espaços?'.format(variavel_dissecada), variavel_dissecada.isspace())
print('{} É alfabético?'.format(variavel_dissecada), variavel_dissecada.isalpha())
print('{} É um número?'.format(variavel_dissecada), variavel_dissecada.isnumeric())
print('{} É alfanumérico?'.format(variavel_dissecada), variavel_dissecada.isalnum())
print('{} É maiusculo?'.format(variavel_dissecada), variavel_dissecada.isupper())
print('{} É maiusculo?'.format(variavel_dissecada), variavel_dissecada.istitle())
| false |
cf46bee5eb0a3ba95addb4a25960331c39003d81 | 3mRoshdy/Learning-Python | /09_generators.py | 472 | 4.28125 | 4 | # Generators are simple functions which return an iterable set of items, one at a time, in a special way.
# Using 'yield' keyword for generating Fibonacci
def fib():
a,b = 1,1
while 1:
yield a
a, b = b, b + a
# testing code
import types
if type(fib()) == types.GeneratorType:
print("Good, The fib function is a generator.")
counter = 0
for n in fib():
print(n)
counter += 1
if counter == 10:
break
| true |
790d755e7834ad0e9a081d74a4b087c6e656466e | ikarek-one/zoom-decoder | /zoomChatDecoderVer2.py | 2,619 | 4.125 | 4 |
print("Decoding Zoom chat .txt-s")
print("Enter the name (or path) of your .txt file!")
print("Examples: myFile.txt OR C:/Documents/meeting_saved_chat.txt")
fileName = input("Name of file: \n")
if(fileName == ""):
fileName = "meeting_saved_chat.txt"
print("\nEnter 'save' if you want to save your file. The file will be saved in the same directory ")
print("as the original file and have name <fileName>_MODIFIED.txt \n")
stream = open(fileName,'r').read()
#print("your file consists of " + str(len(stream)) + " symbols \n\n")
lines = stream.split("\n")
text = []
lastAuthor = []
for line in lines:
line = line.split(" ")
lineAuthor = []
startflag = False
endflag = False
for word in line:
if(endflag): #just plain message text
text.append(word)
if (startflag and not endflag): #an author of the current line
lineAuthor.append(word)
if(word == ":"): #add author name to the text and go to the message mode
lineAuthor.append(" \n")
if(lineAuthor != lastAuthor): #if an author wrote a few lines one by one, he'll be printed once
lastAuthor = lineAuthor
text.append("\n\t")
for w in lineAuthor:
text.append(w.upper())
endflag = True
if(word == "From"): #starts 'author name' mode
startflag = True
if(not endflag): #if the current line hasn't got words From or : is loaded
for w in line:
text.append(w)
text.append("\n") #adds the new-line symbol at the end of the line
text.append("\n\n\n\t\t END OF FILE! \n")
textAsString = ""
for word in text: #transforms a string array containing the whole result into one string
textAsString = textAsString + word + " "
"""
print("Enter 'save' if you want to save your file. The file will be saved in the same directory as the original file and have name <fileName>_MODIFIED.txt")
print(textAsString)
isSaving = input()
"""
decision = ""
while(decision != "end"):
decision = input("Write 'print', 'save' or 'end'! ")
if(decision == "save"):
newFilename: str = fileName[:-4] + "_MODIFIED.txt"
newFile = open(newFilename, 'a')
newFile.write(textAsString)
newFile.close()
if(decision == "print"):
print(textAsString)
"""
isEnd = " "
while( != "end"): #to keep the console on and prevent from accidental closing
isEnd = input("Enter 'end' to finish the programme: \n ")
"""
| true |
4c9eaad51acdfb0bdaa4d9c9faa6a2a4435ff63d | G3Code-CS/Intro-Python-I | /src/14_cal.py | 2,176 | 4.53125 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
"""
import sys
import calendar
import datetime
def printCalendar(*args):
isValidArgs = validate(*args)
argsList = list(args[1:])
now = datetime.datetime.now()
if (isValidArgs):
if len(argsList) == 0:
print(calendar.month(now.year, now.month))
elif len(argsList) == 1:
print(calendar.month(now.year, int(argsList[0])))
elif len(argsList) == 2:
print(calendar.month(int(argsList[1]), int(argsList[0])))
else:
print("Invalid input. Please enter the correct input.")
def validate(*args):
argsList = list(args[1:])
try:
if len(argsList) == 2:
if (int(argsList[0]) > 0) and (int(argsList[0]) < int(13))
and isinstance(int(argsList[0]), int):
if int(argsList[1]) > 0 and isinstance(int(argsList[1]), int):
return True
else:
return False
else:
return False
elif len(argsList) == 1:
if int(argsList[0]) > 0 and int(argsList[0]) < int(13)
and isinstance(int(argsList[0]), int):
return True
else:
return False
elif len(argsList) == 0:
return True
except TypeError:
return False
printCalendar(*sys.argv)
| true |
cef0c723b7f0ad7212ea8fbd5c80af1a8b039635 | tgaye/Learn_Python_the_Hard_Way | /ex11.py | 668 | 4.21875 | 4 | # ex.11 User Inputs
print('How old are you?', end=' ')
age = input()
print('How tall are you?', end=' ')
height = input()
print('How much do you weigh (lbs?)?', end=' ') # imperial system bc im an ignorant American.
weight = input()
print(f'So, you\'re {age} old, {height} tall and {weight} lbs heavy'.format(age, height, weight)) #used esc key for fun
# mistakes: windows terminal with multiple input() prompts is a pain, use IDE
# study drill:
# -3. Make your own form
print('What school did you go to?')
school = input()
print('What year did you graduate?')
year = int(input())
print(f'You graduated from {school} in the year {year}'.format(school, year))
| true |
9f7abd5a59f1514adb0be406e8dc20bb3ce2ba18 | hello-lily/learngit | /pytest/ex18.py | 683 | 4.21875 | 4 | # this one is like your scripts with argv
def print_two ( *args):
arg1,arg2 =args
print ("arg1: %r, arg2: %r" % (arg1, arg2))
#ok, that *args is actually pointless, we can just do this
# so what is*args? means a lot of strings
def print_two_again(arg1, arg2):
print ("arg1: %s, arg2: %s" % (arg1, arg2))
# %r there is ' with the word ;
# %s only the word you want to print
#this just takes one argument
def print_one(arg1):
print ("arg1: %r" % arg1)
#replace % use , ;
#" ," means and ;
#"% " means replace
#this one takes no arguments
def print_none():
print ("I got nothin'.")
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
| true |
35ad81c072dbe045d00dde3113728edabc6d09a3 | 00dbgpdnjs/combine_img | /combine_img/lst_reverse_and_zip.py | 965 | 4.625 | 5 | # reverse() vs reversed()
lst = [1, 2, 3, 4, 5]
print(lst)
lst.reverse() # reverse() : Reverse the order of "lst"
print(lst)
lst2 = [1, 2, 3, 4, 5]
print("lst2 뒤집기 전 : ", lst2)
# reversed() : Return a return var which is reversed ; lst2 is not changed unlike "lst"
lst3 = reversed(lst2)
print("리트스 2 뒤집은 후 : ", lst2)
print("리스트3 : ", list(lst3))
# << zip library >>
kor = ["사과", "바나나", "오렌지"]
eng = ["apple", "banana", "orange"]
# zip : Combine lists down >> [('사과', 'apple'), ('바나나', 'banana'), ('오렌지', 'orange')]
print(list(zip(kor, eng)))
mixed = [('사과', 'apple'), ('바나나', 'banana'), ('오렌지', 'orange')]
# * : Unzip[Seperate] >> [('사과', '바나나', '오렌지'), ('apple', 'banana', 'orange')]
print(list(zip(*mixed)))
kor2, eng2 = zip(*mixed)
print(kor2) # >> ('사과', '바나나', '오렌지')
print(eng2) # >> ('apple', 'banana', 'orange')
| false |
7e50f0fb6350e90dd0ac133337b1f2e45302d370 | Crillboy314/Curso-Basico-Python | /Parte I/Script1.py | 2,554 | 4.40625 | 4 | """
Script 1: Tipo de datos, ejecución de códigos y consola
Autor: kevinrojas
"""
"""
Este archivo fue presentado mientrás se impartía el curso de python.
"""
# PRINT es nuestra expresión con el exterior
print("Hola Mundo")
print("Hola", "Mundo")
print("Hola" + "Mundo")
# ademas permite resolver calculos simples (una gran calculadora)
print(5)
print(50+100)
print(123456789 * 987654321)
print(123456789 / 987654321)
# INPUT por su parte, nos permite incorporar informacion a un programa
# Recordar que INPUT considera como datos de tipo de string lo ingresado
#Programa "amistoso" para el calculo del IVA
Nombre = input("Como te llamas")
print("Hola " + Nombre)
Pago = input("Ingresa el valor a pagar")
PagoNum = int(Pago)
print("El valor total con IVA sería ", PagoNum + (0.12*PagoNum) )
# Python, como lenguaje de programación, ofrece una variedad de tipos de
# datos posibles con los cuales se puede trabajar de forma independiente
# desde la consola o por medio de un IDE
# Siempre podemos identificar el tipo de datos por medio de TYPE:
#Con datos numericos (float e integer):
a = 3
print(type(a))
b = 3.25
print(type(b))
#Con datos de tipo string (para represantacion de texto)
c = "USFQ"
print(type(c))
#Finalmente, los otros tipos de datos mas frecuentes en python son:
#Booleanos
d = 3 < 2
print(type(d))
#Listas LIST
Colegios = ["CADE", "POLI", "CHAT", "COM"]
print(type(Colegios))
#Diccionarios DICT
diccionario = {
"marca": "Toyota",
"modelo": "Camry",
"anio": 1998
}
print(type(diccionario))
#NOTA: Proceso de casting de puede hacer con int(), float(), str()
# Los controladores de flujo son los llamados de elementos mas usados
# en general en programacion, un ejemplo de esto puede ser:
# UTILIZANDO IF
a = float(input("Ingresa el primer numero"))
b = float(input("Ingresa el segundo numero"))
if b > a:
print("El segundo numero", b, "es mas grande que el primer numero ", a )
elif a == b:
print("los dos numeros son iguales")
else:
print("El primer numero", a, "es mas grande que el segundo numero ", a )
# UTILIZANDO FOR
x = range(3, 6)
for n in x:
print(n)
x = range(3, 20, 2)
for n in x:
print(n)
Colegios = ["CADE", "POLI", "CHAT", "COM"]
for name in Colegios:
print("Un colegio academico de la USFQ es", name)
# UTILIZANDO WHILE
i = 1
print("Voy a empezar a contar")
while i < 10:
print(i)
i = i + 1
# A continuacion, un ejemplo de loop infinito
#while True:
# print("Al infinito y mas alla, estoy en ", i)
# i = i + 1
| false |
343d8ddec7f5d12ce721c94b2c9dd96e53930147 | vchatchai/bootcamp-ai | /week1/tuple-cheat-sheet.py | 882 | 4.78125 | 5 | # %%
"""
- By convention, we generally use tuple for different datatypes
and list for similar datatypes
- Since tuple are immutable, then iteration througth tuple
is faster than with list!!!
- Tuple that contain immutables elements can be used as key for a
dictionary. With list, this is NOT possible.
- If you have data that doesn't change, implementing
it as tuple will GUARANTEE that is remains write-protected
"""
# Empty tuple
tuple = ()
print(tuple)
# Tuple containing integers
tuple1 = (1, 2, 3)
print(tuple1)
# Tuple with mixed datatypes
tuple1 = (1, 'hello', 3.4)
print(tuple1)
# Nested tuple
tuple1 = ('mouse', [8, 4, 6], (1, 2, 3))
print(tuple1)
# %%
# How to check 'type' in python
print(type(tuple))
# Create a tuple is not necessary to use '( )'
tuple2 = 1, 2, 3
print(type(tuple2))
#Creating a tuple with one element
tuple3 = 1,
print(type(tuple3)) | true |
6778b4cadbf8b1530bc949cf7903dafdc4c07edc | jdfdoyley/python_list | /python_list.py | 998 | 4.5 | 4 | # Create a list
# =============
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of Strings
names = ["Josephine", "Jess", "Marsha", "Krystal"]
# A list of mixed type
employee = [
"Jessie", "Lewis", 30, (1761, "S Military Hwy", "Norfolk", "VA", 23502),
True
]
# An empty list
empty_list = []
# The list() Constructor
# ======================
# Convert a string to a list
letters = list('abcdef') # Output: ['a', 'b', 'c', 'd', 'e', 'f']
print(letters)
# Convert a tuple to a list
numbers = list((2, 4, 6, 8)) # Output: [2, 4, 6, 8]
print(numbers)
# Nested List in Python
# =====================
author = [
"Dan", "Brown",
["Angels & Demons", "The Da Vinci Code", "The Lost Symbol", "Inferno"]
]
print(author)
# Access List Items by Index
# ==========================
# Access the first cat in the list
cats = ["persian", "bengal", "maine", "siamese", "ragdoll"]
print(cats[0]) # Output: persian
# Access the third cat in the list
print(cats[2]) # Output: maine | true |
92854e6164be7f96190de56031e29ce0bd43ec1a | lef17004/Daily-Coding-Challenges | /8:17-9:3 2020/reverse_list.py | 951 | 4.59375 | 5 | ###############################################################################
"""
Reverse List
8/19/2021
Time Complexity: O(n)
Description: Write function that reverses a list, preferably in place.
"""
###############################################################################
def reverse_list(list, start=0, stop=None):
"""
Start is inclusive, stop is exclusive.
"""
# If stop is the default, set it to the length of the list.
if stop is None:
stop = len(list)
# The index counting backwards.
right_index = stop
# Only need to iterate over half of the list.
for left_index in range(start, (stop // 2) + 1):
# Deincriment the right_index by 1 every time.
right_index -= 1
# Swap the element in the left_index with the one in the right_index.
list[left_index], list[right_index] = list[right_index], list[left_index]
| true |
76cd6f0dd04037b7e085da5d0a7f5d556345a567 | lef17004/Daily-Coding-Challenges | /8:17-9:3 2020/bubble_sort.py | 1,197 | 4.21875 | 4 |
###############################################################################
"""
Bubble Sort
8/17/2021
Time Complexity: O(n^2)
Description: Starting from the beginning of the list, compare every adjacent
pair, swap their position if they are not in the right order (the latter one is
smaller than the former one). After each iteration, one less element (the last
one) is needed to be compared until there are no more elements left to be
compared (Wikipedia).
"""
###############################################################################
def bubble_sort(list):
# Loop through every element in the array (skip the last one).
for pass_number in range(0, len(list) - 1):
# Go from the beggining of the list to the end.
# Swap elements if the item before is greater than the one after it.
for index in range(0, len(list) - 1 - pass_number):
if list[index] > list[index + 1]:
swap(index, index + 1, list)
def swap(index1, index2, list):
# This swaps the elements in the list at the given idexes.
list[index1], list[index2] = list[index2], list[index1]
| true |
9d73704305095fe1886f53493f503cf7dfb7ac2e | sraakesh95github/Python-Course | /Homeworks/Homework 1/hw1_1.py | 898 | 4.4375 | 4 | import sys
import math
# Program to calculate the time taken for a ball to drop from a height for a given initial velocity
#Set a constant value for acceleration due to gravity
g = 9.81;
#Get the height from which the ball is dropped
s = int(input("Enter height : "));
#Check for the height range
if s<10 or s>1000 :
print("Bad height specified. Please try again.");
sys.exit()
#Get the intial velocity with which the ball is thrown / dropped
u = float(input("Enter initial upward velocity : "));
#Check for the initial velocity range
if u<-20 or u>20 :
print("Initial velocity too large ! Slow down !");
sys.exit()
#Calculate the time taken for the ball to drop to the groud Negative initial velocity is given as the ball is moving downward
t = ((math.sqrt((u*u)+(2*g*s)) + u) / g);
#Print time taken
print("time to hit ground " + "{:.2f}".format(t) + " seconds");
| true |
b147b2c96fc928a21f25f9b5901be7a4fa88845d | DiamondGo/leetcode | /python/SortColors.py | 1,588 | 4.125 | 4 | '''
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
click to show follow up.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
'''
class Solution:
# @param {integer[]} nums
# @return {void} Do not return anything, modify nums in-place instead.
def sortColors(self, nums):
cr = cw = cb = 0
r = w = b = 0
while b < len(nums):
if nums[b] == 0:
cr += 1
nums[r] = 0
if cw > 0:
nums[w] = 1
if cb > 0:
nums[b] = 2
r += 1
w += 1
b += 1
elif nums[b] == 1:
cw += 1
nums[w] = 1
if cb > 0:
nums[b] = 2
w += 1
b += 1
elif nums[b] == 2:
cb += 1
b += 1
if __name__ == '__main__':
nums = [0]
Solution().sortColors(nums)
print(nums) | true |
3e2505c4409bfbe19aef3a9d3dd29d8d4eca1ea5 | DiamondGo/leetcode | /python/SlidingWindowMaximum.py | 1,300 | 4.125 | 4 | '''
Created on 20160511
@author: Kenneth Tse
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Therefore, return the max sliding window as [3,3,5,5,6,7].
Note:
You may assume k is always valid, ie: 1 <= k <= input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
'''
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
lastrow = nums
for i in range(k - 1):
lastrow = [max(lastrow[i-1], lastrow[i]) for i in range(1, len(lastrow))]
return lastrow
if __name__ == '__main__':
s = Solution()
print(s.maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3)) | true |
1f6e8cee4146df934701eb652ddc89523ded93aa | antonyaraujo/Listas | /Lista04/Questao9.py | 544 | 4.3125 | 4 | '''Faça uma função que dado um número n retorne o n-ésimo número de Fibonacci. O número de fibonacci é dado
por n0=0, n1=1, ni = ni-1+ni-2.'''
def fibonacci(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
fibonacci = 1
penultimo = 0
for i in range(1, n):
ultimo = fibonacci
fibonacci = ultimo + penultimo
penultimo = ultimo
return fibonacci
numero = int(input("Informe um número: "))
print("Fibonacci: ", fibonacci(numero))
| false |
da45103332d90801eeaf70e3ea6861d43c57a496 | antonyaraujo/Listas | /Lista04/Questao4.py | 812 | 4.28125 | 4 | ''' Escreva um programa que chame uma função que deve receber por parâmetro dois valores (um para comprimento
e outro para largura), calcular e apresentar na tela a área de um retângulo, através da fórmula do retângulo =
comprimento * largura. Repetir a chamada da função com a passagem de parâmetros enquanto não for digitado
um número negativo para o comprimento ou para a largura.'''
def area(comprimento, largura):
return comprimento * largura
comprimento = float(input("Comprimento do retângulo: "))
largura = float(input("Largura do retângulo: "))
while (comprimento > 0) and (largura > 0):
print("A área do retângulo é: ", (area(comprimento, largura)), "m²")
comprimento = float(input("Comprimento do retângulo: "))
largura = float(input("Largura do retângulo: "))
| false |
ac57e0a4885b8ae7de768fe249dade20208a15b5 | antonyaraujo/Listas | /Lista04/Questao11.py | 990 | 4.53125 | 5 | ''' Escreva um programa que contenha uma função que receba como parâmetros um caractere representando uma
operação matemática (+,-,/,*) e dois números reais representando os operandos. Sua função deve efetuar a
operação dada sobre os operandos e retornar o resultado. A função principal deve imprimir o resultado. (Obs.:
cuidado com a divisão por 0) '''
def calculadora(operacao, n1, n2):
if operacao == '+':
print("%.2f + %.2f = %.2f" %(n1, n2, n1 + n2))
elif operacao == '-':
print("%.2f - %.2f = %.2f" %(n1, n2, n1 - n2))
elif operacao == '*':
print("%.2f x %.2f = %.2f" %(n1, n2, n1 * n2))
elif operacao == '/':
try:
print("%.2f ÷ %.2f = %.2f" %(n1, n2, n1 / n2))
except ZeroDivisionError:
print("Não há divisão por zero")
operacao = input("Informe o tipo da operação: ")
n1 = float(input("Informe o valor 1: "))
n2 = float(input("Informe o valor 2: "))
calculadora(operacao, n1, n2)
| false |
2692298589c64d79dcf5d25ec4f59d03fff3cf64 | antonyaraujo/Listas | /Lista06/Questao4.py | 683 | 4.5625 | 5 | '''Faça um programa que contenha uma função. Essa função deve receber uma string, dois números
inteiros (representando posição inicial e posição final). A função deve construir uma substring da
string recebida por parâmetro, sendo que esta substring é o intervalo, na string original, entre os
dois valores também recebidos por parâmetro (inicial e final). Ao final a função deve imprimir na tela
esta substring construída. Copie um caracter por vez.
Exemplo: Se for digitada a string PROGRAMACAO e os valores 4 e 8 deverá ser impresso na tela a
substring GRAMA.'''
def substring(string, n1, n2):
return string[n1-1:n2]
print(substring("PROGRAMACAO", 4, 8)) | false |
2e62154aeea00630ab738fa1f98749f714aae44a | Rollbusch/Learning-Python | /Aulas/016.py | 368 | 4.1875 | 4 | # import math biblioeca de funções matemáticas
from math import trunc # só importa uma função da biblioteca math
num = float(input('Digite um número qualquer: ')) # trunc() somente quando for importado a função da biblioteca.
print('O número {}, tem a parte inteira {}'.format(num, trunc(num))) #math.trunc() mostra a parte inteira de um número.
| false |
af01fe43f281513beb6503b91fabc6d900e38489 | yosoydead/recursive-stuff | /visualising recursion/bla.py | 753 | 4.53125 | 5 | from turtle import *
t = Turtle()
wind = Screen()
#i use penup so that when the turtle is repositioned, it doesn't draw any lines
t.penup()
#starting position
t.setposition(-300,-300)
#make the turtle draw again
t.pendown()
#this is for speed test
t.speed(9)
#the method needs a turtle object to use to draw things
#lineLen is just the length of the first line
def draw(turtle, lineLen):
#if the lineLen reaches 0, the program will stop
if lineLen> 0:
#just move the turtle from left to right a certain distance
turtle.forward(lineLen)
#after drawing the first line, turn a certain angle at the left,
turtle.left(90)
#recall function
draw(turtle, lineLen-5)
draw(t, 500)
wind.exitonclick() | true |
f1e606e96dbea769da2adb4d543e5bd6b3a64c37 | AlDBanda/Python-Functions | /main.py | 2,177 | 4.46875 | 4 | #def greet():
# return "Hello Alfred"
#print(greet())
#============================
'''
Function with parameters
'''
#def greet(name):
# '''
# Greets a person passed in as argumrnt name: a name of a person to greet
# '''
# return f"Hello {name}, Good morning"
#print(greet("Felix"))
#print(greet("Arlo"))
#print(greet("Arien"))
#help(print)
#Function with parameters above
'''
Arbirtary parameters
'''
#def fruits (*names):
# '''
# Accepts unknown number of fruti names and prints each of them
# *name: list of fruits
# '''
#names are tuples
# for fruit in names:
# print(fruit)
#fruits("Orange", "Banana", "Apple", "Grapes)")
#Means you can accept one or many with arbitary paramaters
#====================================
'''
Keyword paramters
'''
#def greet(name, msg):
# '''
# This function greets a person with a given message
# name: person to greet
# msg: message to greet person with
# '''
# return f"Hello {name}, {msg}"
#print(greet("Alfred", "Good afternoon!"))
#print(greet("Good afternoon", "Arlo!"))
#Function becomes more useful
#print(greet(name= "Alfred", msg="Good afternoon!'))'"))
#print(greet(msg="Good afternoon", name="Arlo!"))
#using keyword as name allows you to write it whichever way round
'''
Arbitary Keyword parameters
'''
#def person(**student):
# print(type(student))
#person(fname="Alfred", lname="Banda")
#That comes in as a dictionary above
#def person(**student):
#print(type(student))
#print(student)
#for key in student:
#print(student[key])
#person(fname="Alfred", lname="Banda")
#person(fname="Alfred", lname="Banda", subject="Python")
'''
Default parameter
'''
#def greet(name='Alfred'):
# return f"Hello, {name}"
#print(greet())
#print(greet("Disa"))
'''
pass statement
'''
#def greet():
# pass
'''
Recursion
'''
#A method calling itself
def factorial_recursive(n):
'''
Multiply given number by every number less than it down to 1 in factorial way e.g. if n is 5 then calculate 5*4*3*2*1 = 120
'''
if n == 1:
return True
else:
return n * factorial_recursive(n -1)
print(factorial_recursive(50)) | true |
a62e16ff90361d0e60103355fe85838c54c611c9 | simgroenewald/NumericalDataType | /Numbers.py | 876 | 4.34375 | 4 | # Compulsory Task 1
Num1 = input("Enter your first number:")# Allows user to input their first number and saves it as variable number1
Num2 = input("Enter your second number:")# Allows user to enter their second number and saves it as variable number2
Num3 = input("Enter your third number:") # Allows the user to enter their third number and saves it as a variable number3
#The following changes the strings entered as Num1, Num2 and Num3 to integers
Num1 = int(Num1)
Num2 = int(Num2)
Num3 = int(Num3)
print (Num1 + Num2 + Num3)# Displays the awnser for adding all three numbers
print (Num1 - Num2)# Displays the answer for subtracting the second number from the first
print (Num3 * Num1)# Displays the product of the first and thrid number
print ((Num1 + Num2 + Num3) / Num3)# Displays the answer for the addition of all three number divided by the third number
| true |
137ed3c9089d953574204d65fad08722db04a813 | GayathriAmarneni/Training | /Programs/nToThePowern.py | 239 | 4.375 | 4 | # Program to calculate n to the power n.
base = int(input("Enter a base number: "))
result = 1
counter = 0
while counter < base:
result = result * base
counter = counter + 1
print(base, "to the power of", base, "is", result)
| true |
4d13a1c0cddb9ab162b99df61875359b3617ad91 | GayathriAmarneni/Training | /Programs/mToThePowern.py | 270 | 4.375 | 4 | #Program to calculate m to the power n.
base = int(input("Enter base number: "))
exponent = int(input("Enter exponent number: "))
result = 1
for exponent in range(0, exponent + 1, 1):
result = result * base
print(base, "to the power of", exponent, "is", result) | true |
6c1f1f2b78af6e4989c6bf0ebf8677e992e9e70e | datadiskpfv/basics1 | /printing.py | 874 | 4.21875 | 4 | print('Hello World')
print(1 + 2)
print(7 * 6)
print()
print("The End")
print("Python's strings are easy to use")
print('We can even include "quotes" in strings')
print("hello" + " world")
# using variables
greeting = "Hello"
name = "Paul"
print(greeting + name)
print(greeting + ' ' + name)
#greeting = 'Hello'
#name = input("Please enter your name: ")
#print(greeting + ' ' + name)
splitString = "\tThis string has been \nsplit over\n several \nlines"
print(splitString)
print('The pet shop owner said "No, no \'e\'s uh,...he\'s resting"')
print("The pet shop owner said \"No, no 'e's uh,...he's resting\"")
print('''The pet shop owner said "No, no 'e's uh,...he's resting"''')
print("""The pet shop owner said "No, no 'e's uh,...he's resting" """) # notice the space
anotherSplitString = """This string has been
split over
several lines"""
print(anotherSplitString) | true |
fdda56b607a15772990151abdc4a5d93a1bdcada | datadiskpfv/basics1 | /sets.py | 1,719 | 4.40625 | 4 | # sets are mutable objects (unless you use a frozen set)
# there is no ordering
farm_animals = {"sheep", "cow", "hen"}
print(farm_animals)
wild_animals = set(["lion", "tiger", "panther", "elephant", "hare"])
print(wild_animals)
wild_animals.add("horse")
wild_animals.add("ant")
print(wild_animals)
# you can also use discard
wild_animals.remove("ant")
print(wild_animals)
# to create a empty set, dont use {} this is a dictionary
empty_set = set()
print(empty_set.__class__)
even = set(range(0, 40, 2))
print(even)
print(len(even))
square_tuple = (4, 6, 9, 16, 25)
squares = set(square_tuple)
print(squares)
print(len(square_tuple))
print("Union")
print(even.union(squares))
print(even | squares) # can also use this instead of above
print(len(even.union(squares)))
print("Intersection")
print(even.intersection(squares))
print(even & squares) # can also use this instead of above
print(len(even.intersection(squares)))
print("difference")
print(sorted(even.difference(squares)))
print(sorted(even - squares)) # can also use this instead of above
print(len(even - squares))
print("Symmetric Difference")
print(even.symmetric_difference(squares))
print(even ^ squares) # can also use this instead of above
print(len(even.symmetric_difference(squares)))
print("Subsets and supersets")
tuple1 = set([4, 6, 16])
print("tuple1 is a subset of squares {}".format(tuple1.issubset(squares))) # can use <= as well
print("squares is a superset of tuple1 {}".format(squares.issuperset(tuple1))) # can use >= as well
frozen_set = frozenset(range(0, 10, 2))
#frozen_set.add ## add/pop, etc does not exist as its an immutable object
| true |
0cd37577dcd53530aaeb1988110fb141dfac3a24 | sutclifm0850/cti110 | /P4HW1_Sutcliffe.py | 313 | 4.15625 | 4 | #P4HW1
#Distance Travveled
#Sutcliffe
#March 25, 2018
speed = float(input('What is the speed of the vehicle in mph?'))
time = int(input('How many hours has it traveled?'))
print('Hour','\tDistance Traveled')
for Hour in range(1, time + 1 ):
distance = speed * Hour
print(Hour,'\t',distance)
| true |
61d7528d11582fa50ee89b4e44a420f4e2e025ee | AthaG/Kata-Tasks | /6kyu/MultiplesOf3Or5_6kyu.py | 715 | 4.25 | 4 | '''If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,
5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below
the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once. Also, if a
number is negative, return 0(for languages that do have them)'''
#First solution
def solution(number):
return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)
#Second solution
def solution(number):
res = []
x = 1
while x * 3 < number:
res.append(x*3)
if x * 5 < number:
res.append(x*5)
x += 1
return sum(set(res))
| true |
c43b4fcbd1989400e3bf9d78e1b9d319ebb5ffa9 | AthaG/Kata-Tasks | /6kyu/FindTheOrderBreaker_6kyu.py | 1,373 | 4.25 | 4 | '''In this kata, you have an integer array which was ordered by ascending except one
number.
For Example: [1,2,3,4,17,5,6,7,8]
For Example: [19,27,33,34,112,578,116,170,800]
You need to figure out the first breaker. Breaker is the item, when removed from
sequence, sequence becomes ordered by ascending.
For Example: [1,2,3,4,17,5,6,7,8] => 17 is the only breaker.
For Example: [19,27,33,34,112,578,116,170,800] => 578 is the only breaker.
For Example: [105, 110, 111, 112, 114, 113, 115] => 114 and 113 are breakers. 114 is
the first breaker.
When removed 114, sequence becomes ordered by ascending => [105, 110, 111, 112,
113, 115]
When removed 113, sequence becomes ordered by ascending => [105, 110, 111, 112,
114, 115]
For Example: [1, 0, 2] => 1 and 0 are the breakers. 1 is the first breaker.
When removed 1, sequence becomes ordered by ascending => [0, 2]
When removed 0, sequence becomes ordered by ascending => [1, 2]
For Example: [1, 2, 0, 3, 4] => 0 is the only breaker.
When removed 0, sequence becomes ordered by ascending. => [1, 2, 3, 4]
TASK:
Write a function that returns the first breaker.
Notes:
Input array does not contain any duplicate element.'''
def order_breaker(array):
for i, c in enumerate(array):
if array[i+1] < array[i]:
return array[i] if array[i] != 2 else 0
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.