blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4cb0316e7e5931647ac0c8324024dc956c5d6639 | theech/python-2018 | /strings/StringOperations.py | 2,614 | 4.6875 | 5 | # Python String Operations
# There are many operations that can be performed with string which makes it one of the most used.
# 1. Concatenation of Two or More Strings
# Joining of two or more strings into a single one is called concatenation.
#The + operator does this Python. Simply writing two string literals together also concatenates them. The
#The * operator can be used to repeat the string for a given number of times.
string00 = "Hello "
string01 = ' World!'
#using +
print('string00 + string01', string00 + string01)
#using *
print(string00 * 3)
#writing two string leterals together also concatenates them like + operator. If we want to concatenate string indefferent lines, we can
# parentheses.
#two string literals together
print("Hello" "world!")
#using parentheses
string02 = ("Hello"
" World "
"I am different person"
)
print(string02)
#---------------------------------------------------------------------------------------------------------------------------------------------#
# 2. Iterating Through String
# Using for loop we can iterate through a string. Here is an example to count the number of "e" in a string.
count = 0
for letter in string02:
if letter is 'e':
count += 1
print("There are ", count, "in a string02")
#--------------------------------------------------------------------------------------------------------------------------------------------#
# 3. String Membership Test
# We can test if a sub string exists a string or not, using the keyword "in"
letterCheck = 'L'
checkStringMember = letterCheck in string02
if checkStringMember is True:
print("It's ", letterCheck," in string02")
else:
print("It's not ", letterCheck, " in string02")
#--------------------------------------------------------------------------------------------------------------------------------------------#
# 4. Built-in function to Work with Python
# Various buit-in fucntion work with sequence, work with string as well.
# Some of the commontly use once are "enumerate()" and "len()". The "enumerate()" fucntion are returns an enumerate object. it contains the
# the index and value of all the items in the string as pairs. This can be useful for iteration
# Similarly, "len()" retruns the length (number of characters) of the string.
string03 = "cool one"
#enumerate()
ListEnumerate = list(enumerate(string03))
print('lest(enumerate(string03)) = ', ListEnumerate)
#character count using "len()" fucntion
print('len(stirng03 = ', len(string03))
| true |
977ad2d50b7456887d68b1c6a3d3685bd32ab1dd | juhyun0/python_SQLite | /delete_record.py | 362 | 4.125 | 4 | import sqlite3
conn=sqlite3.connect('test.db')
cursor=conn.cursor()
cursor.execute("""
DELETE FROM PHONEBOOK WHERE EMAIL=?
""", ('visal@bskim.com',))
conn.commit()
cursor.execute("SELECT NAME, PHONE, EMAIL FROM PHONEBOOK")
rows=cursor.fetchall()
for row in rows:
print("NAME: {0}, PHONE: {1}, EMAIL: {2}".format(row[0], row[1], row[2]))
cursor.close()
conn.close()
| false |
42ff6e2fa62fb2581ef35ac3e40e813314dc856c | karchi/codewars_kata | /已完成/Powers of 2.py | 661 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
# Powers of 2题目地址:https://www.codewars.com/kata/57a083a57cb1f31db7000028/train/python
'''
import unittest
class TestCases(unittest.TestCase):
def setUp(self):
pass
def test1(self):self.assertEqual(powers_of_two(0), [1])
def test2(self):self.assertEqual(powers_of_two(1), [1, 2])
def test3(self):self.assertEqual(powers_of_two(4), [1, 2, 4, 8, 16])
def powers_of_two(n):
return [2 ** i for i in range(n + 1)]
if __name__ == '__main__':
unittest.main()
'''
参考解法:
def powers_of_two(n):
return [1<<x for x in range(n + 1)]
''' | false |
49aebb74350ab463408119a4d902de779ae02f92 | karchi/codewars_kata | /已完成/Convert boolean values to strings 'Yes' or 'No'.py | 551 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
# Convert boolean values to strings 'Yes' or 'No'.题目地址:https://www.codewars.com/kata/53369039d7ab3ac506000467/train/python
'''
import unittest
class TestCases(unittest.TestCase):
def setUp(self):
pass
def test1(self):self.assertEqual(bool_to_word(True), 'Yes')
def test2(self):self.assertEqual(bool_to_word(False), 'No')
def bool_to_word(bool):
return "Yes" if bool else "No"
if __name__ == '__main__':
unittest.main()
'''
参考解法:
''' | false |
141bcef4c71f3feae81bf3d948ba0880ff8d311c | karchi/codewars_kata | /已完成/Basic Mathematical Operations.py | 967 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
# Basic Mathematical Operations题目地址:http://www.codewars.com/kata/57356c55867b9b7a60000bd7/train/python
'''
import unittest
class TestCases(unittest.TestCase):
def setUp(self):
pass
def test1(self):self.assertEqual(basic_op('+', 4, 7), 11)
def test2(self):self.assertEqual(basic_op('-', 15, 18), -3)
def test3(self):self.assertEqual(basic_op('*', 5, 5), 25)
def test4(self):self.assertEqual(basic_op('/', 49, 7), 7)
def basic_op(operator, value1, value2):
return eval(str(value1) + operator + str(value2))
if __name__ == '__main__':
unittest.main()
'''
参考解法:
def basic_op(operator, value1, value2):
if operator=='+':
return value1+value2
if operator=='-':
return value1-value2
if operator=='/':
return value1/value2
if operator=='*':
return value1*value2
''' | false |
3134207e30f642ef3c49c8fdacb2373ecf7a7beb | RLeary/little_things | /Python/is_square.py | 530 | 4.21875 | 4 | # is an integer square?
import math
def is_square(n):
# positive integers only
if n < 0:
return False
# math.sqrt returns a float, and squaring this value may not be accurate
# int() takes the floor of a number, and adding 0.5 to it should mean
# that we get the value we are looking for if the float is close enough
# to the int we need
root = math.sqrt(n)
return n == int(root + 0.5) ** 2
# return roor.is_integer()
print(is_square(4))
print(is_square(7))
print(is_square(1000373)) | true |
ca1319a3987b737536749470c02603b1e8c00c50 | brenmcnamara/coding-challenges | /src/middle-of-linked-list/solution.py | 1,216 | 4.34375 | 4 |
def find_middle(list):
"""Find the middle element of a linked list
Args:
- list: A linked list. Assuming this is a valid linked list, and not nil
Returns:
The middle element of the linked list.
"""
ptr1 = list
ptr2 = list['next'];
while ptr2:
ptr1 = ptr1['next']
assert ptr1, 'Expecting ptr1 to not be nil'
ptr2 = ptr2['next']
ptr2 = ptr2['next'] if ptr2 else ptr2
return ptr1
if __name__ == '__main__':
print("--- TESTING SOLUTION ---")
nodeA = {'value': 'A', 'next': None}
nodeB = {'value': 'B', 'next': None}
nodeC = {'value': 'C', 'next': None}
nodeD = {'value': 'D', 'next': None}
nodeE = {'value': 'E', 'next': None}
nodeA['next'] = nodeB
nodeB['next'] = nodeC
nodeC['next'] = nodeD
nodeD['next'] = nodeE
test1_result = find_middle(nodeA)
assert test1_result is nodeC, "Test 1 Failed"
print("Test 1 passed")
test2_result = find_middle(nodeE)
assert test2_result is nodeE, "Test 2 Failed"
print("Test 2 passed")
test3_result = find_middle(nodeD)
assert test3_result is nodeD or test3_result is nodeE, "Test 3 Failed"
print("Test 3 passed")
| true |
daca21300d4d012c53b6b0c13132e55150f9d0e0 | sandeeppalakkal/Algorithmic_Toolbox_UCSD_Coursera | /Programming_Challenges_Solutions/week4_divide_and_conquer/1_binary_search/binary_search.py | 1,728 | 4.125 | 4 | # Uses Python3
'''Binary Search
In this problem, you will implement the binary search algorithm that allows searching
very efficiently (even huge) lists, provided that the list is sorted.'''
'''Problem Description:
Task. The goal in this code problem is to implement the binary search algorithm.
Input Format. The first line of the input contains an integer 𝑛 and a sequence 𝑎0 < 𝑎1 < . . . < 𝑎𝑛−1
of 𝑛 pairwise distinct positive integers in increasing order. The next line contains an integer 𝑘 and 𝑘
positive integers 𝑏0, 𝑏1, . . . , 𝑏𝑘−1.
Constraints. 1 ≤ 𝑛, 𝑘 ≤ 104; 1 ≤ 𝑎𝑖 ≤ 109 for all 0 ≤ 𝑖 < 𝑛; 1 ≤ 𝑏𝑗 ≤ 109 for all 0 ≤ 𝑗 < 𝑘;
Output Format. For all 𝑖 from 0 to 𝑘 − 1, output an index 0 ≤ 𝑗 ≤ 𝑛 − 1 such that 𝑎𝑗 = 𝑏𝑖 or −1 if there
is no such index.'''
def binary_search(target,array,l,r):
n = r - l + 1
if n == 1:
if array[l] == target:
return l
else:
return -1
mid = (l + r) // 2
if target <= array[mid]:
index = binary_search(target,array,l,mid)
else:
index = binary_search(target,array,mid+1,r)
if index == -1:
return index
else:
return index
def search_and_index(a,b):
index = [0] * len(b)
for i,t in enumerate(b):
index[i] = binary_search(t,a,0,len(a)-1)
return index
def main():
a = list(map(int,input().split()))
n = a.pop(0)
assert n == len(a)
b = list(map(int,input().split()))
k = b.pop(0)
assert k == len(b)
index = search_and_index(a,b)
for i in index:
print(i, end=" ")
print()
if __name__ == '__main__':
main()
| true |
bf8125ebb2a628c2cd8cea13e7fddf0b2f01feec | sandeeppalakkal/Algorithmic_Toolbox_UCSD_Coursera | /Programming_Challenges_Solutions/week5_dynamic_programming1/1_money_change_again/money_change_dp.py | 1,291 | 4.125 | 4 | # Uses Python3
'''Money Change Again
As we already know, a natural greedy strategy for the change problem does not work correctly for any set of
denominations. For example, if the available denominations are 1, 3, and 4, the greedy algorithm will change
6 cents using three coins (4 + 1 + 1) while it can be changed using just two coins (3 + 3). Your goal now is
to apply dynamic programming for solving the Money Change Problem for denominations 1, 3, and 4.
Problem Description
Input Format. Integer money.
Output Format. The minimum number of coins with denominations 1, 3, 4 that changes money.
Constraints. 1 ≤ money ≤ 1e3.'''
def money_changes(m,coins):
change_array = [-1] * (m + 1)
change_array[0] = 0
# Run for all money from 0 to m:
for i in range(1,m+1):
# DP Step:
# Run for all coins & compute min changes:
min_change = m
for c in coins:
if i < c:
break
# DP Formula:
change = change_array[i-c] + 1
if change < min_change:
min_change = change
change_array[i] = min_change
return change_array[m]
def main():
coins = [1,3,4]
m = int(input())
n = money_changes(m,coins)
print(n)
if __name__ == '__main__':
main()
| true |
458c0bf0b0dd0d4230f3d3cde4f30ebad6f369c4 | Ricky-Millar/100-days-of-python | /CoffeeMachine/main.py | 2,791 | 4.15625 | 4 | from menu import MENU
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
# TODO 1 : Prompt user by asking “What would you like? (espresso/latte/cappuccino):”
def orderFunc():
order = input("What would you like? (espresso/latte/cappuccino):")
if order == "espresso" or order == "latte" or order == "cappuccino":
return order
elif order == "report":
resource()
orderFunc()
elif order == "off": # TODO 2: Turn off the Coffee Machine by entering “off” to the prompt
return "off"
else:
print("Sorry, Try Again.")
orderFunc()
def resource(): # TODO 3: Print report of resources
print('\nReport:')
print(
f'{resources["water"]} ml of water,\n{resources["milk"]} ml of milk, \n{resources["coffee"]} grams of coffee.\n ')
# TODO 4: Check if rescources are sufficiant
def checkResourceAvaliable(order):
currentResourceList = [float(resources["water"]), float(resources["coffee"]), float(resources["milk"])]
orderResorceList = [float(MENU[order]["ingredients"]["water"]), float(MENU[order]["ingredients"]["coffee"]),float(MENU[order]["ingredients"]["milk"])]
for i in range(3):
if currentResourceList[i] < orderResorceList[i]:
print("soz, no beannnnz")
return False
print("Resources Avaliabubble")
return True
# TODO 5: Proscess coins
# TODO 6:Check transaction successful?
# TODO 7: Make Coffee
def moneyCalc(order):
purchaseDone = False
while not purchaseDone:
price = MENU[order]["cost"]
quartNum = float(input('how many quarters?')) * 0.25
dimeNum = float(input('how many dimes?')) * 0.1
nickNum = float(input('how many nickles?')) * 0.05
penNum = float(input('how many pennies?')) * 0.01
totalCoins = quartNum + dimeNum + nickNum + penNum
if totalCoins == price:
print('Bang on Brotendo')
purchaseDone = True
elif totalCoins > price:
print(f'your change is ${totalCoins - price}')
purchaseDone = True
elif totalCoins < price:
print("you need to put in more money!")
machineon = True
while machineon:
order = orderFunc()
if order == "off":
print("goodnight")
machineon = False
elif checkResourceAvaliable(order):
print('\nTime to insert some coins!') # quarters = $0.25, dimes = $0.10, nickles = $0.05, pennies = $0.01
moneyCalc(order)
resources['water'] -= MENU[order]["ingredients"]['water']
resources['milk'] -= MENU[order]["ingredients"]['milk']
resources['coffee'] -= MENU[order]["ingredients"]['coffee']
resource()
else:
print('sorry we are out of resources, maybe try another drink')
| true |
e859bd0384a1d2e71d8ae14e00a66612e6f5bc0f | FightForDobro/itea_python_basics | /Basov_Dmytrii/03/Task_3_2_v3.py | 1,854 | 4.46875 | 4 | def custom_map(func, *arguments):
"""
This is the 2nd version of custom map function. It can handle with multiple input arguments.
:param func: Any input function.
:param arguments: iterable collections, where the 1st is the smallest.
:type func: class 'function'
:type arguments: type depends on input collection(string, list, tuple, etc)
:return: The function returns list of result items
:rtype: return type 'list'
"""
args_amount = len(arguments)
print(args_amount) # Not necessary to execute. Just for checking out
# Exception condition
if args_amount == 0:
print("No arguments")
return func()
# Body of function
result = [] # Initial empty resulting list
for i in range(len(arguments[0])): # Iterate on the 1st argument
arr_j = [] # Initial list for items with the same indexes in different arguments
for j in range(args_amount): # Iterate on input argument indexes
arr = arguments[j]
arr_j.append(arr[i]) # Add in list each i item every j argument
print('\nInput values to be handled by function', arr_j) # Not necessary to execute. Just for checking out
x = func(*arr_j) # Action on every item
result.append(x) # Filling of resulting list
print('Your result is: ', result)
return result
# Checking out with integer lists
my_list = [1, 2, 3, 4]
my_list_2 = [2, 4, 5, 8, 9]
result_int = custom_map(lambda x, y: float(x + y), my_list, my_list_2)
print(result_int)
# Checking out with string
my_str = input('\nThe 1st string argument: ')
my_str_2 = input('\nThe 2nd string argument: ')
result_str = custom_map(lambda s1, s2: s1 + s2, my_str, my_str_2)
| true |
f07aee08b4afa3f6dfdb34bf85f188989cf35c5f | FightForDobro/itea_python_basics | /Yurii_Kilochyk/Task3/3.1.py | 988 | 4.25 | 4 | '''
Task 3.1 Array difference
Implement a difference function, which subtracts one list from another and returns the result.
It should remove all values (all of its occurrences) from list a, which are present in list b.
Examples:
call: array_diff([1, 2], [1])
return: [2]
call: array_diff([1, 2, 2, 2, 3], [2])
return: [1,3]
Added by medviediev
'''
"""
This function removes all values (all of its occurrences) from list a, which are present in list b.
:param list_a: List, from which list_b elements will be removed
:type list_a: List
:param list_b: The list of values which will be removed from list_a
:type list_b: List
:return: Return is list which contains unique to list_a elements
:rtype: List
"""
def array_difference(list_a, list_b):
c = []
for i in list_a:
if i not in list_b:
c.append(i)
return c
a = [2, 4, 3, 5, 8]
b = [1, 2, 2, 2, 3, 7]
d = array_difference(a, b)
print('Array difference: ', d)
| true |
1f20e37e80a147a89140a3c7bb6ae6ff98cea609 | FightForDobro/itea_python_basics | /pavlenko_dmitryi/05/Task51.py | 813 | 4.15625 | 4 | def sum_function(first_input, second_input):
"""
This function sums two numbers or displays an error when entering text.
:param first_input: first input
:param second_input: second input
:type first_input: int
:type second_input int
:return: amount of inputs
:rtype: int
"""
try:
first_number = int(first_input)
second_number = int(second_input)
except ValueError:
return print("You made a mistake while entering")
else:
sum_of_numbers = first_number + second_number
return sum_of_numbers
first_input = input("Enter first number: ")
second_input = input("Enter second number: ")
sum_input = sum_function(first_input, second_input)
print(sum_input)
with open("test.txt", 'w') as f:
f.write(str(sum_input)+ "\n")
| true |
8f5e4f33fface4ac28119ac4af034baa40b17a3c | FightForDobro/itea_python_basics | /Aleksandr_Bondar/Task_3.2/map_func.py | 603 | 4.28125 | 4 |
def cmap(func,iterable):
"""
This function works like standard map function, with only difference that it
returns list instead of map object
:param func: function what need to be applied to iterable
:param iterable: iterable data, which need to be processed by function
:type func: function, known to interpreter
:type iterable: any iterable object
:return: list of iterable's items, processed by function
:rtype: list
"""
result = []
for i in iterable:
result.append(func(i))
return result
# For testing:
a = input('enter something: ')
print(cmap(lambda x: x*2, a))
| true |
d85c61e392efea8d08392b6bca1a2bd4bb10966f | cs-fullstack-2019-spring/python-review2-cw-cierravereen24-1 | /classwork.py | 1,346 | 4.375 | 4 | # Point of entry.
# The main function calls the problem fucntion within its scope.
def main():
problem1()
# Create a task list. A user is presented with the text below.
# Let them select an option to list all of their tasks,
# add a task to their list, delete a task, or quit the program.
# Make each option a different function in your program.
def problem1():
toDoList = [{"1. Do my laundry."},
{"2. Watch YouTube tutorials about Python."},
{"3. Vacuum Civi's floor."},
{"4. Feed YangYang amd Thalia."}
]
prompt = ""
prompt2 = ""
# A while loop that keeps iterating the user inputted value, until q is typed to quit.
while True:
prompt = int(input("Congratulations! You're running Cierra's Task List program.\nEnter what would you like to do next:\n1. List all tasks.\n2. Add a task to the list.\n3. Delete a task.\n0. To quit the program press '0'. "))
for goals in toDoList:
print(goals)
if prompt == 0:
break
elif prompt == 1:
print(toDoList)
elif prompt == 2:
prompt2 = input("Enter a task to add to the the list.")
toDoList.append(prompt2)
elif prompt == 3:
toDoList.remove([prompt3])
if __name__ == '__main__':
main() | true |
a1c9e3cd8625639caa1606f95aab95af8e3f50e9 | erikamaylim/Python-CursoemVideo | /ex018.py | 544 | 4.21875 | 4 | """Faça um programa que leia um ângulo qualquer e mostre na tela
o valor do seno, cosseno e tangente desse ângulo."""
from math import sin, cos, tan, radians
x = float(input('Digite o valor de um ângulo: '))
s = sin(radians(x))
c = cos(radians(x))
t = tan(radians(x))
print(f'O ângulo digitado foi {x}. Seu seno é {s:.2f}, seu cosseno é {c:.2f} e a sua tangente é {t:.2f}')
#x = int(input('Digite um grau qualquer:' ))
#print(f'O ângulo digitado foi {x}. Seu seno é {sin(x)}, seu cosseno é {cos(x)} e a sua tangente é {tan(x)}.')
| false |
8ed9194f2fc2856c6d799cfce900fc5ecfa214b3 | erikamaylim/Python-CursoemVideo | /ex063.py | 547 | 4.25 | 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"""
print('******** SEQUÊNCIA DE FIBONACCI ********')
n = int(input('Quantos termos da Sequência de Fibonacci deseja ver? '))
a, b, c = 0 , 1, 0
print(f'{a} ⇾ {b}', end='')
cont = 3 #Já estou exibindo os 2 primeiros números. Contador não precisa começar do 1
while cont <= n:
c = a + b
print(f' ⇾ {c}', end='')
a = b
b = c
cont += 1
| false |
668fbda91b2a8d2c6b14da25b19d0ef4b1d170ea | erikamaylim/Python-CursoemVideo | /ex079.py | 657 | 4.125 | 4 | """Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista.
o número já exista lá dentro, ele não será adicionado.
No final, serão exibidos todos os valores únicos digitados, em ordem crescente."""
num = list()
resp = 'S'
while resp in "Ss":
n = (int(input('Digite um valor: ')))
if n not in num:
num.append(n)
print('Valor adicionado.')
else:
print('Valor duplicado. Não vou adicionar.')
resp = str(input('Quer continuar? [S/N] '))
print('Programa finalizado')
num.sort()
print('Os números digitados em ordem crescente foram:', end=' ')
print(*num, sep=', ')
| false |
84ee78d244220d63a21e4fff640d6abc6e0eb810 | erikamaylim/Python-CursoemVideo | /ex044.py | 1,309 | 4.125 | 4 | """Elabore um programa que calcule o valor a ser pago por um produto,
considerando o seu preço normal e condição de pagamento:
– à vista dinheiro/cheque: 10% de desconto
– à vista no cartão: 5% de desconto
– em até 2x no cartão: preço formal
– 3x ou mais no cartão: 20% de juros"""
valor = float(input('Valor da compra: R$ '))
forma = int(input('''Forma de Pagamento:
[1] Dinheiro
[2] Cheque
[3] Cartão
Digite o nº da opção desejada: '''))
vezes = int(input('Em quantas vezes vai pagar? (Se for à vista, digite 1) '))
if (forma == 1 and vezes == 1) or (forma == 2 and vezes == 1):
print(f' No dinheiro ou cheque à vista você tem 10% de desconto.\nO valor a pagar é R$ {valor - (valor * (10 / 100)):.2f}.')
elif forma == 3 and vezes == 1:
print(f'No cartão à vista você tem 5% de desconto. O valor a pagar é R$ {valor - (valor * (5 / 100)):.2f}')
elif forma == 3 and vezes <= 2:
print(f'No cartão em até 2x não há desconto. O valor a pagar é R$ {valor:.2f}.')
elif forma == 3 and vezes >= 3:
print(f'Pagamentos no cartão com 3 ou mais parcelas têm 20% de juros.')
print(f'''Sua compra será parcelada em {vezes}x de R$ {(valor + (valor * (20 / 100))) / vezes:.2f}. Total R$ {valor + (valor * (20 / 100)):.2f}.''')
else:
print('Opção inválida')
| false |
791ede3242bf98d57360d3115d4de14b99dab6a2 | erikamaylim/Python-CursoemVideo | /ex036.py | 766 | 4.28125 | 4 | """Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado."""
casa = float(input('Qual o valor da casa? R$ '))
salario = float(input('Qual o seu salário? R$ '))
anos = int(input('Em quantos anos pretende pagar o valor total? '))
mes = anos * 12
prestacao = casa / mes
GREEN = "\033[1;32m"
RED = "\033[1;31m"
END = "\033[0m"
if prestacao <= salario * (30 / 100):
print(f'{GREEN}EMPRÉSTIMO APROVADO!{END} Você irá pagar R$ {prestacao:.2f} por mês.')
else:
print(f'{RED}EMPRÉSTIMO NEGADO!{END} O valor das prestações excedeu 30% do seu salário.')
| false |
7190cc8ca6ba51ff09e9cca528b88b749a93e5ec | leonardourbinati/Exam | /Exam/miscellaneous.py | 2,245 | 4.1875 | 4 | # miscellaneous.py
# For the following exercises, pseudo-code is not required
# Exercise 1
# Create a list L of numbers from 21 to 39
# print the numbers of the list that are even
# print the numbers of the list that are multiples of 3
print('exercise_1')
l= range(21,40)
print('l= %s' %l)
for i in l:
if i%2==0:
print('even numbers= %s' %i)
else:
print('odd numbers= %s' %i)
for i in l:
if i%3==0:
print('multiples of 3= %s' %i)
# Exercise 2
# Print the last two elements of L
print('\nexercise_2')
print('last 2 elements of l= %s' %(l[-2:]))
# Exercise 3
# What's wrong with the following piece of code? Fix it and
# modify the code in order to have it work AND to have "<i> is in the list"
# printed at least once
print('\nexercise_3')
L = [1, 2, 3]
print('L= %s' %L)
for i in range(10):
if i in L:
print('i=%s is in the list' %i)
else:
print('i=%s not found' %i)
# Exercise 4
# Read the first line from the sprot_prot.fasta file
# Split the line using 'OS=' as delimiter and print the second element
# of the resulting list
print('\nexercise_4')
f=open('sprot_prot.fasta', 'r')
def first_line_reader(f):
f=open('sprot_prot.fasta', 'r')
return(f.readline())
print(first_line_reader(f))
def header(f):
f=open('sprot_prot.fasta', 'r')
g= f.readline().split('OS=')[1]
return g
print header(f)
# Exercise 5
# Split the second element of the list of Exercise 4 using blanks
# as separators, concatenate the first and the second elements and print
# the resulting string
print('\nexercise_5')
s= header(f).split()
k= ' '.join(s[0:2])
print k
# Exercise 6
# reverse the string 'asor rosa'
print('\nexercise_6')
string_forward= 'asor rosa'
string_reverse= list(string_forward)[::-1]
string_reverse_2=''.join(string_reverse)
print ('string in reverse= %s' %string_reverse_2)
# Exercise 7
# Sort the following list: L = [1, 7, 3, 9]
print('\nexercise_7')
L= [1, 7, 3, 9]
L= sorted(L)
print('L_sorted= %s' %L)
# Exercise 8
# Create a new sorted list from L = [1, 7, 3, 9] without modifying L
print('\nexercise_8')
v= sorted(L)
print('new sorted list= %s' %v)
# Exercise 9
# Write to a file the following 2 x 2 table:
# 2 4
# 3 6
new_file= open('table.txt','w')
new_file.write('2\t4\n3\t6')
new_file.close()
| true |
5b990055d37e4cac6aec93806a9469ff6a202e58 | nabilatajrin/python-programs | /string-manipulation/check-string.py | 423 | 4.1875 | 4 | #String Length
a = "Hello, World!"
print(len(a))
#Check String
txt = "The best things in life are free!"
print("free" in txt)
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
#Check if NOT
txt = "The best things in life are free!"
print("expensive" not in txt)
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
| true |
e94a16f58f12fa20be718a4ce214111b995ddd93 | nabilatajrin/python-programs | /tuple/update-tuples.py | 560 | 4.40625 | 4 | #Change Tuple Values
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
#Add Items
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
#Remove Items
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
| false |
fe5c5486c8f38ca4515f94042bca534a5822e4cd | nabilatajrin/python-programs | /append-new-line.py | 470 | 4.3125 | 4 | x = 3
print(x) # Trailing comma suppresses newline in Python 2
print(x, end=" ") # Appends a space instead of a newline in Python 3
print(x, end=" ") # Appends a space instead of a newline in Python 3
y = 5, #',' keeps () in next prints
print(y) # Trailing comma suppresses newline in Python 2
print(y, end=" ") # Appends a space instead of a newline in Python 3
print(y, end=" ") # Appends a space instead of a newline in Python 3
| true |
4045918e2597ba940d9c680c87bfd82b80ab5a06 | nabilatajrin/python-programs | /string-manipulation/reverse-string.py | 2,875 | 4.3125 | 4 | class ReverseString:
#Solution 01: using for loop
#Time Complexity: O(n)
#Auxiliary Space: O(1)
def reverse(s):
str=""
for i in s:
str = i+str
return str
s = 'Geeks'
print('output: ', reverse(s))
# Solution 02: using for loop
#Pseudocode:
#run a loop from 'len(inputStr)-1' to 0
#one by one append characters from end to start in result string
#initialize an empty string:
inputStr = 'Hello'
result = ''
for i in range(len(inputStr)-1, -1, -1):
result = result + inputStr[i]
#peint reserved string:
print(result)
# Solution 03: using inbuilt reversed funtion of python
# Pseudocode:
#use inbuilt function reversed(), it will return list of character of input string in reversed order
inputStr = 'Geeks'
reversedChars = reversed(inputStr)
#now join list of chars without space
print(''.join(reversedChars)) #this join() concatenate function to form a string
# Solution 04: using extended slicing in python
# Time Complexity: O(n)
# Auxiliary Space: O(1)
#syntax: inputStr[start:end:step]
inputStr = 'Food'
print(inputStr[-1::-1]) #:: is for traverse by default from the endpoint to start point
#-1: is for starting backward from the end
# :-1 is for end at first index 0
#Or, in short:
def reverse(str):
str = str[::-1]
return str
s = 'Name'
print('output: ', reverse(s))
# Solution 05: using function call
# Time Complexity: O(n)
# Auxiliary Space: O(1)
# Pseudocode:
#function to reverse a string
#by converting string to list
#then reverse it and again convert it to string
def reverse(str):
str = list(str)
str.reverse()
return ''.join(str)
s = 'Nature'
print('output: ', reverse(s))
# Solution 06: using list comprehension()
#list comprehension creates the list of elements of a string in reverse
#order and then it's elements and joined using join().
#And then reversed order string is formed.
# Time Complexity: O(n)
# Auxiliary Space: O(1)
#function to reverse a string:
def reverse(string):
string = [string[i] for i in range(len(string)-1, -1, -1)]
return ''.join(string)
s = 'List'
print('output: ', reverse(s))
# Solution 07: using reverse method:
# Time Complexity: O(n)
# Auxiliary Space: O(1)
def reverse(str):
str = ''.join(reversed(str))
return str
s = 'ReversedMethod'
print('output: ', reverse(s))
# Solution 08: using recursion:
# Time Complexity: O(n)
# Auxiliary Space: O(n)
def reverse(s):
if len(s) == 0:
return s
else:
res = (s[1:])+s[0]
return res
str = 'recursion'
print('output: ', reverse(str))
| true |
860e06ea7ed1d0ec699c1821be2bc727a6db77bf | nabilatajrin/python-programs | /pythonprograms/break/Break_1.py | 331 | 4.1875 | 4 | #find out if any specific fruit exist in the list
fruits = ["apple", "orange", "banana", "jambura",
"mango", "cherry"]
found = "no"
for fruit in fruits:
if fruit == "jambura":
found = "yes"
print("found it!")
break
if found == "yes":
print ("we have jambura!")
else:
print ("sorry!") | true |
ffeca215bc70927a7820249363c077abde564c7f | cr0cK/algorithms | /MTF/mtf.py | 719 | 4.1875 | 4 | #!/bin/env python
# move to front
# http://en.wikipedia.org/wiki/Move-to-front_transform
def mtf(word):
letters = []
indexes = []
for c in word:
if c not in letters:
letters.append(c)
letters.sort()
for c in word:
i = letters.index(c)
indexes.append(i)
letters.insert(0, letters.pop(i))
letters.sort()
return (indexes, letters)
def reverse_mtf(tuple_):
indexes, letters = tuple_
word = []
for i in indexes:
word.append(letters[i])
letters.insert(0, letters.pop(i))
return ''.join(word)
r = mtf('bananaaa')
s = reverse_mtf(r)
print(r)
# ([1, 1, 2, 1, 1, 1, 0, 0], ['a', 'n', 'b'])
print(s)
# bananaaa
| false |
46abd7a77174d5dcfe53e20b355862ab97be2233 | gauriindalkar/function | /perfect number.py | 681 | 4.21875 | 4 | # 7.Write a function “perfect()” that determines if parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000.
# [An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
# def perfect(number):
# sum=0
# i=1
# while i<number:
# if number%i==0:
# sum=sum+i
# i=i+1
# if sum==number:
# print("it is perfect number")
# else:
# print("it is not perfect number")
# number=int(input("enter number"))
# perfect(number) | true |
da71efc825e82be0de6c34b84841308f9f702992 | isabellyfd/python_lessons | /fib.py | 276 | 4.125 | 4 | number = int(input("digite o numero a ser calculado o fib:\n"))
base = 1
resultado = 1
if number == 0 or number == 1:
print (base0)
else:
if
while number > 1:
resultado = resultado + base
base = resultado
number -= 1
print(resultado)
| false |
498df9ed5aa879aa666a015d15a18c5afdcdd06b | Mauricio1xtra/Revisar_Python_JCAVI | /class4_dictcomprehensions.py | 294 | 4.15625 | 4 | ##Dict Comprehensions
lista1 = [
('valor1', 10),
('valor2', 8),
('valor3', 30),
]
## Transformar os valores da lista em dicionário
d1 ={c:v for c,v in lista1}
print(d1)
d2 = {c:v*2 for c, v in lista1}
print(d2)
d3 = {c.upper():v for c,v in lista1}
print(d3) | false |
6dab29b52007232f5c9e8dafef441083576fa6b7 | joestone51/ff-scraper | /ff_scraper/output/output.py | 581 | 4.125 | 4 | def write_output(file_name: str, outputs: list) -> None:
""" Writes each row in :outputs to :file_name.csv as its own line
Will write the CSV of each row of outputs to the provided file name.
Args
file_name (str): The name you want the csv file to have
outputs (list): A list of lists to be written as comma separated values
per line to file_name
Returns
None
"""
with open(file_name + '.csv', 'w') as file:
for output in outputs:
if output:
file.write(','.join(output) + '\n')
| true |
d0ed761598e1a4fe63f3fd65054018927e14dfd0 | 18zgriffin/SoftwareDev | /Functions/Lists.py | 757 | 4.25 | 4 | def listsort(arg_list):
arg_list.sort()
listlen = len(arg_list)
print("The sorted list is", arg_list)
print("The largest value in the list is", arg_list[listlen-1])
def listreverse(or_list):
rlist = []
for i in or_list:
rlist.insert(0, i)
print("The reverse list is", rlist)
def eleminlist(in_list):
elem = int(input("What do you want to find in the list "))
if elem in in_list:
print("Yes that is in the list")
else:
print("No that is not in the list")
list = []
UI = "\n"
while (UI != ""):
UI = input("Enter a value for the list: ")
if (UI != ""):
list.append(int(UI))
print("The current values are: ")
print(list)
(listsort(list))
(listreverse(list))
(eleminlist(list)) | true |
2b3ef91cb4a5c6e35e0ec62686e3181b59c20342 | Michael-Zagon/ICS3U-Unit4-03-Python | /squared.py | 729 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Michael Zagon
# Created on: Oct 2021
# This program squares each number from 0 up to the users number
def main():
# This function squares each number from 0 up to the users number
counter = 0
answer = 0
# Input
integer_s = input("Enter an integer >= 0: ")
print("")
# Process and Output
try:
integer = int(integer_s)
if integer < 0:
print("You did not enter a positive integer.")
for counter in range(integer + 1):
answer = counter ** 2
print("{0}² = {1}² ".format(counter, answer))
except Exception:
print("Invalid input.")
print("\nDone.")
if __name__ == "__main__":
main()
| true |
adf9f035200be58fd6bc5b8e11b47686349afc5f | kloayza23/PythonLearning | /DataStructuresAndFunctions/assignments/Asgn3.2.py | 1,286 | 4.125 | 4 | def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply(a,b):
return a*b
def divide (a,b):
if(a == 0 or b== 0):
return "Not a number"
else:
return a/b
def calculator(choice, num1, num2):
operationList = [("Sum","+",add), ("Difference",'-', subtract), ("Product","*",multiply), ("Quotient","/",divide)]
for index, operation in enumerate(operationList,1):
if choice == index:
print( str(operation[0] + " of {} "+operation[1]+" {} is: {}").format(num1, num2, operation[2](num1,num2)))
def printSelection(choice):
selectionList = ["Addition","Subtraction","Multiplication","Division"]
for ind, selection in enumerate(selectionList,1):
if int(choice) == ind:
print("You have chosen {}".format(selection))
break
while True:
print("---------------------------------------------------------------------")
choice = input("Simple Calculator: Enter 1-Addition; 2-Subtraction; 3-Multiply; 4-Divide; 0-To Quit ")
if choice not in ['1','2','3','4']:
print("Exiting simple calculator...")
break
else:
printSelection(choice)
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
calculator(int(choice),n1,n2) | true |
780ad0c2f549d08738b4cd604e2e5adfb4d904b5 | SandipaniDey/FSSDP_2020 | /infinite.py | 461 | 4.125 | 4 | num_list = []
sum = 0
count = 0
while True:
num = input("Enter a Number: ")
if len(num) < 1:break
try:
num = int(num)
except:
print("Enter a valid number")
quit()
sum = sum + num
count += 1
num_list.append(num)
print("Sum of the given numbers are: ",sum)
print("Average of the given numbers are: ",sum/count)
print("Largest and Smallest of the given numbers are: ",max(num_list),min(num_list)) | true |
9ef6a3898f7072582e66d9d8c7eef4a48070da3c | abingham/project_euler | /python/src/euler/exercises/ex0009.py | 653 | 4.46875 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 2^5 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
from itertools import count
def pythagorean_triplets():
"Iterable of all Pythagorean triplets."
return ((a, b, c)
for c in count(3)
for b in range(2, c)
for a in range(1, b)
if a**2 + b ** 2 == c ** 2)
def main():
return next(a * b * c
for a, b, c
in pythagorean_triplets()
if a + b + c == 1000)
| false |
843538983ba4b999407bcb36183d66df6d375e40 | EneasCarranza/variables_python | /PRUEBA DE ENEAS.PY | 569 | 4.15625 | 4 |
print ("modulo 2 ejercicio profundizacion 1")
print ("ingrese un primer numero con 1 decimal")
numero_1 = float(input())
print("Ingrese segundo numero con 1 decimal")
numero_2 = float(input())
print("la suma de",numero_1, "y",numero_2 ,"es" ,numero_1+numero_2)
print("la resta de",numero_1, "y",numero_2 ,"es" ,numero_1-numero_2)
print("la multiplicacion de",numero_1, "y",numero_2 ,"es" ,numero_1*numero_2)
print("la division de",numero_1, "y",numero_2 ,"es" ,numero_1/numero_2)
print("la exponencializacion de ",numero_1, "y",numero_2 ,"es" ,numero_1**numero_2)
| false |
76efca6943bc0faba55e1afd00fba908ccd2f19e | lyndsiWilliams/Data-Structures | /test.py | 1,491 | 4.21875 | 4 | # Print out each element of the following array on a separate line:
# ["Joe", "2", "Ted", "4.98", "14", "Sam", "void *", "42", "float", "pointers", "5006"]
# You may use whatever programming language you'd like.
# Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process.
# list = ["Joe", "2", "Ted", "4.98", "14", "Sam", "void *", "42", "float", "pointers", "5006"]
# # for i in list:
# # print(i)
# print(*list, sep = "\n")
# Print out each element of the following array on a separate line, but this time the input array can contain arrays nested to an arbitrarily deep level:
# ['Bob', 'Slack', ['reddit', '89', 101, ['alacritty', '(brackets)', 5, 375]], 0, ['{slice, owned}'], 22]
# For the above input, the expected output is:
# Bob
# Slack
# reddit
# 89
# 101
# alacritty
# (brackets)
# 5
# 375
# 0
# {slice, owned}
# 22
# You may use whatever programming language you'd like.
# Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process.
liist = ['Bob', 'Slack', ['reddit', '89', 101, ['alacritty', '(brackets)', 5, 375]], 0, ['{slice, owned}'], 22]
# print(type(liist))
def print_list(lst):
# elist = []
for i in lst:
if type(i) is not type(list):
print(i)
else:
print_list(i)
print_list(liist)
# isinstance | true |
fff313fc54e07c39cb8abc51d2547c09b7db1ac6 | RajaomalalaSendra/a-byte-of-python | /input_output_python.py | 381 | 4.1875 | 4 | class Palindrome:
def __init__(self, text):
self.text = text
print("({} is created)".format(self.text))
def reverse(self):
return self.text[::-1]
def is_palindrome(self):
return self.text == self.text[::-1]
something = input("Enter text: ")
pal = Palindrome(something)
if pal.is_palindrome():
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome") | true |
efbb23813871276fc74bb653a37b88e863acc850 | someshj5/bridgelabz_programs | /Data structures/program1.py | 2,608 | 4.21875 | 4 | class Node: # creating a node class for linked list head
def __init__(self, value):
self.value = value
self.next = None
class LinkedList: # creating a class linked list
def __init__(self):
self.head = None # assigning the initial value of head as None
def append(self, new_value): # function defining to append a value in a linked list
newnode = Node(new_value)
newnode.next = self.head
self.head = newnode
def display(self): # function to display the values in the linked list
temp = self.head
while temp:
print (temp.value),
temp = temp.next
def search(self,wrd): # Function to search for the value in a linked list
temp = self.head
while temp:
if temp.value == wrd:
return True
temp = temp.next
return False
def remove(self,wrd): # function to remove a value from a linked list
prev = None
temp = self.head
while temp:
if temp.value == wrd:
if prev:
prev.next = temp.next
else:
self.head = temp.next
return True
prev = temp
temp = temp.next
return False
l = LinkedList() # assigning the object for the linked list
with open('file_word.txt','r') as file1: # opening the text file in read mode as file1
mylist = file1.read().split() # to split the words in the text file
for i in mylist:
l.append(i) # appending the words in a linked list
l.display()
User = input('Enter a name to search') # ask user for input to search a word
if l.search(User): # searching the word in the linked list
l.remove(User) # remove the word if found in the linked list
mylist.remove(User) # remove the word from the text file1
l.display()
print(mylist)
with open('file_word.txt','w+') as file1: # updating the text file1
for i in mylist:
file1.write(i)
else:
l.append(User) # add the word if not in the linked list
mylist.append(User) # add the word to the text file1
with open('file_word.txt','a+') as f1: # updating the text file
f1.write('\n')
f1.write(User)
| true |
dc00fc1e9c558b7367085c10415228d331662faf | someshj5/bridgelabz_programs | /Data structures/program3.py | 1,476 | 4.21875 | 4 | class Stack: # creating a class Stack
def __init__(self): # function to initialize the stack as empty
self.items = []
def is_empty(self): # function to check if the stack is empty
return self.items == []
def push(self, data): # function to push a value in to the stack
self.items.append(data)
def pop(self): # function to pop a value from a stack
return self.items.pop()
def size(self): # function for the length of a stack
len(self.items)
def peak(self): # function for the peak value in the stack
if self.is_empty():
return None
return self.items[-1]
stack = Stack() # assigning the stack as object
mydata = '(5+6)∗(7+8)/(4+3)(5+6)∗(7+8)/(4+3)' # expression to check for balanced parentheses
def balanced(mydata):
for i in mydata: # iterate through the expression in mydata
if i == '(':
stack.push('(') # push a value in stack
elif i == ')':
stack.pop() # pop the value from the stack
if stack.is_empty(): # check if the stack is empty and print the result
print ('the Expresseion has balanced parentheses')
else:
print('The expression is not balanced')
balanced(mydata) | true |
82ceaa2fd5fe09f74c05b52b79a3ed0714f03e76 | Samdayem/VirtualPetandCropClass | /VirtualPet.py | 2,055 | 4.125 | 4 | class VirtualPet:
"""An implementation of a virtual pet"""
def talk(self):
print("Hello, I am your new pet and i have been called {0}".format(self.name))
if self.hunger<50:
print("please feed me, I'm hungry")
def __init__(self,name):
self.name=name
self.hunger=50
def OptionMenu ():
print("*****WHAT WOULD YOU LIKE TO DO WITH YOUR PET*****")
print()
print("1.feed")
print("2.walk")
def OptionChoice(
def eat (self,hunger,food):
if food == "cookie":
self.hunger=self.hunger-8
print("my hunger is now {0}/100".fomat(self.hunger))
elif food == "raisin":
self.hunger=self.hunger-2
print("my hunger is now {0}/100".fomat(self.hunger))
elif food == "burger":
self.hunger=self.hunger-40
print("my hunger is now {0}/100".fomat(self.hunger))
elif food == "rib":
self.hunger=self.hunger-30
print("my hunger is now {0}/100".fomat(self.hunger))
elif food == "apple":
self.hunger=self.hunger-10
print("my hunger is now {0}/100".fomat(self.hunger))
elif food == "sausage":
self.hunger=self.hunger-25
print("my hunger is now {0}/100".fomat(self.hunger))
else:
print("unfortunately, your pet can't eat that, please choose something from the menu")
if self.hunger==100:
print("I am too full, I can't eat anymore")
print("that {0} was tasty".format(food))
def walk(self,places):
if __name__=="__main__":
name=input("What do you want to call your pet: ")
pet_one=VirtualPet(name)
pet_one.talk()
food=input("what would you like to eat (cookie, raisin, burger, rib, apple,sausage): ")
pet_one.eat(food)
places=input("where would you like to walk(park,petshop,the depths of hell): ")
pet_one.walk(places)
| true |
4e17d0c73a434316377993b19234a84e17decbfc | veronica001/python_learn | /yield.py | 1,063 | 4.125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*
# 该函数在运行中占用的内存会随着参数 n 的增大而增大,如果要控制内存占用,最好不要用 List
def fab(n):
a,b = 0,1
x = 0
L = []
while x < n:
a, b = b, a + b
L.append(a)
x += 1
return L
print(fab(6))
# yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,
# Python 解释器会将其视为一个 generator,调用 fab(5) 不会执行 fab 函数,而是返回一个
# iterable 对象!在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b
# 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数
# 的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。
def fab2(n):
a,b = 0,1
x = 0
while x < n:
a, b = b, a + b
yield a
x += 1
for n in fab2(6):
print(n) | false |
d9194911e933fefb1c4a6e4e3c418f7c6901aed5 | samuelhe83/collection | /sorts/Isort.py | 2,276 | 4.28125 | 4 | #Simple Sort #3: The Insertion Sort.
#Time-complexity: W [O(n^2)], Avg [O(n^2)], B [O(n)],
#Notes: While this sort does share the same time-complexities as bubble sort, it has some very unique attributes that make it actually useful (lol). The Worst case for this algorithm is an already-sorted-reversed list. The Best case for this algorithm is when the list is already sorted (just like bubble sort). The average case is anything inbetween those two. It should be noted that the Avg case time complexity is still quadratic (n^2), so this REALLY shouldn't be used on large lists. As I stated, there are some advantages over bubblesort that are notable: It's adaptive (good for "partially-sorted" lists) and it's reactive [Online] (it can insert newly crafted elements right into its sorting pattern, thus allowing it to be ran on a stream of incoming things).
#The idea: Start at the left hand side (recursion works in "reverse"), with our right_bound increasing "slicing" our list into small parts. Slide our right_bound toward the left until we identify where it needs to be inserted, and then swap. Then we increase our right_bound by 1 and do it again, and again, and again, and again, until the list is sorted.
#Simple recursive in-place insertion sort.
def Isort(some_list, right_idx):
if right_idx:
right_val = some_list[right_idx]
right_idx -= 1
Isort(some_list, right_idx)
while right_idx >= 0 and some_list[right_idx] > right_val: #Sliding pointer and swap all the way to the left.
some_list[right_idx + 1] = some_list[right_idx]
right_idx -= 1
some_list[right_idx + 1] = right_val
#For the iterative version, since we don't have a nice reduction-way to control our right_bound like recursion, we start at the left with our right-bound increasing effectively "slicing" our list. Then we perform the same idea: slide our pointer to the left and insert our value where it needs to go.
#Simple iterative in-place insertion sort.
def itIsort(some_list):
right_bound = len(some_list)
for idx in range(1, right_bound):
insertion_val = some_list[idx]
while idx > 0 and some_list[idx - 1] > insertion_val:
some_list[idx] = some_list[idx - 1]
idx -= 1
some_list[idx] = insertion_val
| true |
c882ca4b68e66d01348947c361c1993fb30c134a | enxicui/Python | /PythonAssignments/p15/p15p1.py | 576 | 4.1875 | 4 | '''
give f(n) a definition
if n == 1:
return 2
elif n > 1:
return n+f(n-1)
prompt the user input a number
for i in range (1, n+1)
print( f(i)
'''
def f(n):
#Take n as input and calculate nth value and print it and return
if n == 1:
return 2
elif n > 1:
return n + f(n-1)
while True:
n = int(input("Please enter a positive number:" ))
if n>=1:
for i in range (1, n+1):
print( f(i),end=" ")
print()
if n<1:
print("finished")
break
| false |
a4d273cf5688e43ae2bf75c229711c0fe8e5b6b9 | enxicui/Python | /PythonAssignments/p9/p9p3.py | 416 | 4.28125 | 4 |
'''
pseudocode
Prompt the user for an integer as x
if x==0:
fa==1
elif:
fa==1
elif x<0:
fac = 1
for every integer between 1 and x
fa = fa * i
print(fa)
'''
x=int(input('please enter a number:'))
fa=0
if x==0:
fa==1
elif x==1:
fa==1
elif x<0:
print('sorry, the number must greater than 0')
else:
fa=1
for i in range(1, x+1):
fa=fa*i
print('factorial of', x, 'is', fa)
| true |
3b48e9e911278d26a0b2971d98a8ef34efdcba20 | IlyaNazaruk/python_courses | /HW/6/task_6_6.py | 1,027 | 4.25 | 4 | # Задан целочисленный массив. Определить количество участков массива,
# на котором элементы монотонно возрастают (каждое следующее число
# больше предыдущего). [02-4.1-ML27]
list_of_numbers = [5, 1, 2, 3, 4, 3, 5, 7, 9, 5, 4, 3, 12, 13, 14, -2, 3, 4]
list_of_rows = []
rows = []
i = 1
len_list = len(list_of_numbers)
while i <= len_list:
if list_of_numbers[i] > list_of_numbers[i-1] :
rows.append(list_of_numbers[i-1])
j = i
# print(j)
while list_of_numbers[j-1] < list_of_numbers[j]:
rows.append(list_of_numbers[j])
# print(rows)
j += 1
if j == len_list:
break
i = j
list_of_rows.append(rows)
else:
i += 1
if i == len_list :
break
rows = []
print(list_of_rows)
print(len(list_of_rows), '- количество последовательностей') | false |
9c42f6cce9f1884e71139088f3d52c8b7bab48ff | jjjchens235/daily_leetcode_2021 | /arrays/intersection_of_two_arrays.py | 1,263 | 4.125 | 4 |
def intersect(nums1, nums2):
return set.intersection(set(nums1), set(nums2))
def intersect(nums1, nums2):
"""
two pointer solution
i corresponds to nums1 index
j corresponds to nums2 index
if nums1[i] > nums2[j], then j+=1
elif nums1[i] < nums2[j], then i+=1
else: it's an intersection, increment both i and j
"""
nums1 = sorted(nums1)
nums2 = sorted(nums2)
results = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] > nums2[j]:
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
if nums1[i] not in results:
results.append(nums1[i])
i += 1
j += 1
return results
def intersect(nums1, nums2):
'''
This is a Facebook interview question.
They ask for the intersection, which has a trivial solution using a hash or a set.
Then they ask you to solve it under these constraints:
O(n) time and O(1) space (the resulting array of intersections is not taken into consideration).
You are told the lists are sorted.
'''
pass
if __name__ == '__main__':
nums1 = [1, 2, 3, 4]
nums2 = [0, 2, 3]
res = intersect(nums1, nums2)
print(f'\nres: {res}')
| true |
08d22c74ba9070c07eebf9e3240b334ba305c509 | jcorn2/Project-Euler | /prob19.py | 463 | 4.125 | 4 | from datetime import timedelta,date
#date durations used to calculate number of Sundays
week = timedelta(days=7)
dayDuration = timedelta(days=1)
begin = date(1901,1,1)
day = begin
end = date(2000,12,31)
#find first Sunday after begin
while(day.weekday() != 6):
day = day + dayDuration
count = 0
#loops through every sunday between begin and end
while(day < end):
#sunday begins on first of month
if(day.day == 1):
count += 1
day += week
print(count)
| true |
f1e65032c653aeb6b6a9a1e9af1f99403504e217 | sametypebonus/Basic-Python-Codes | /loancalc.py | 521 | 4.1875 | 4 | # Get the loan details from the user
money_owed=float(input("How much money do you owe?\n"))
apr = float(input("What is the yearly percentage rate?\n"))
monthly = float(input("What is the monthly payment amount?\n"))
months = int(input("How many months do you want to see the results for?\n"))
monthlyapr = apr/1200
for i in range(months):
interestpermonth = monthlyapr*money_owed
money_owed = money_owed + interestpermonth
money_owed = money_owed - monthly
print("Money owed is",money_owed) | true |
70e6329bd7d5bd4edc268b859b6287cec9ec190a | tea0911/PythonWorkSpace | /1027/multiplication.py | 231 | 4.1875 | 4 | multiplication = [i*j for i in range(1, 3) for j in range(1, 10)]
print(multiplication)
multiplication = []
for i in range(1,3):
for j in range(1,10):
multiplication.append(i * j)
print(multiplication) | false |
30e432d3fde4e13f1e65d8e867a1ba600fcdfbd0 | ghoshmithun/problem_solving | /permutation.py | 1,656 | 4.25 | 4 | # Write an algorithm for permutation of digits of a number
from typing import List
# def permutation_number(number:int)-> List[str]:
# if not isinstance(number,int):
# try:
# number=int(number)
# except ValueError:
# return 'input is not a number'
# else:
# digits=list(str(number))
# result = permute_digits(digits)
# return result
# def permute_digits(digits:List[str])->List[str]:
# permutations=[]
# if len(digits) == 1:
# return digits
# else:
# for j in range(len(digits)):
# permutations.extend(digits[0] + i for i in permute_digits(digits[1:]))
# permutations.extend( i + digits[0] for i in permute_digits(digits[1:]))
# permutations.extend(i + digits[j] for i in permute_digits(digits[0:j]+ digits[j:]))
# return permutations
# Python program to print all permutations using
# Heap's algorithm
# Prints the array
def printArr(a, n):
for i in range(n):
print(a[i], end=" ")
print()
# Generating permutation using Heap Algorithm
def heapPermutation(a, size, n):
# if size becomes 1 then prints the obtained
# permutation
if (size == 1):
printArr(a, n)
return
for i in range(size):
heapPermutation(a, size - 1, n);
# if size is odd, swap first and last
# element
# else If size is even, swap ith and last element
if size & 1:
a[0], a[size - 1] = a[size - 1], a[0]
else:
a[i], a[size - 1] = a[size - 1], a[i]
# Driver code
a = [1, 2, 3, 4 ]
n = len(a)
heapPermutation(a, n, n) | true |
825539b1a7af02d131ff4ae7fe0a7309648ec977 | taiyrbegeyev/Advanced-Programming-In-Python | /Assignment 5/2/appropiparam.py | 1,393 | 4.125 | 4 | # JTSK-350112
# appropiparam.py
# Taiyr Begeyev
# t.begeyev@jacobs-university.de
from graphics import *
from random import randrange
from sys import *
def main():
print("Enter the length of the window")
d = int(input())
if d > 1000:
print("Window size shouldn't exceed 1000")
sys.exit()
print("Enter the numbers of points to be generated")
n = int(input())
if n < 0:
print("Should be natural number")
sys.exit()
# create a square window with the side length of d (400x400).
win = GraphWin("Approximate Pie", d, d)
# repeatedly create and draw 10000 random points
counter = 0
for i in range(1, n + 1):
# random number generator
x = randrange(0, d)
y = randrange(0, d)
if i % 100 == 0:
# ratio of the points inside the circle and the total number of points and * 4
ratio = counter / i * 4
# print the value on the screen
print("Pie = {}".format(ratio))
elif ((x - d / 2) ** 2) + ((y - d / 2) ** 2) <= (d ** 2) / 4:
# if generated point is inside the circle
win.plotPixelFast(x, y, "red")
counter += 1
else:
win.plotPixelFast(x, y, "blue")
# use the plotPixel() method to plot at least one pixel to actually show results
win.plotPixel(100, 100, "green")
win.getMouse()
win.close()
main() | true |
bb7074f0a55d7383a219547cabc75aad08d12fad | ehsansaira/GirlsWhoCode | /Jigsaw.py | 208 | 4.125 | 4 | #a = [1, 2, 3, 4, 5, 6]
#a[1:4]
#[2, 3, 4]
numeros = [5,13,19,23,29,37]
slice = slice(-1,-4, -1)
print("List the numeros before the slice")
print("The List after negative values for slice:" ,numeros[slice])
| true |
d894f135576324d87077a1cb5cb181ea726cc89a | andreylrr/PythonDeveloperHW3 | /variables.py | 978 | 4.25 | 4 | import datetime
"""
Модуль 1 для домашнего задания к третьему вебинару курса Python Developer
В этом модуле будет описан объект ИГРУШКА с помощью средств Python
"""
# Название игрушки
name = str("кукла")
# Вес грушки в кг
weight = 0.5
# Является ли эта игрушка детской
is_for_kids = True
# Рекомендуем возраст детей
kids_age = 3
# Дата производства
manufacturing_date = datetime.date(2019, 10, 5)
print("Тип переменной name - ", type(name), sep="")
print("Тип переменной weight - ", type(weight), sep="")
print("Тип переменной is_for_kids - ", type(is_for_kids), sep="")
print("Тип переменной kids_age - ", type(kids_age), sep="")
print("Тип переменной manufacturing_date - ", type(manufacturing_date), sep="")
| false |
9f00445153fcb93da59ea44e25a94d818d97cf84 | bhardwajaditya113/python | /multipleStringFormatting.py | 201 | 4.125 | 4 | name = input("Enter your name:")
surname = input("Enter your surname:")
when = "today"
#message = "Hello! %s %s" % (name, surname)
message = f"Hello! {name} {surname}. What's up {when}?"
print(message) | true |
c3398477a1496b6e2b46976ddbec19d54b2612b3 | reymon359/machine-learning | /2 - Regression/1 Simple linear regression/simple_linear_regression.py | 2,340 | 4.375 | 4 | # Simple Linear Regression
# Importing the libraries
import numpy as np # To work with mathematical numbers.
import matplotlib.pyplot as plt # To work with plots
import pandas as pd # To import and manage datasets
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
# We separate the dependent and the independent variables
X = dataset.iloc[:, :-1].values # Independent
y = dataset.iloc[:, 1].values # Dependent
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
# Feature Scaling (values in same scale for no dominant variable)
# test set no fit because it is already done in the training one
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)"""
# We will no t need it for this so I left it commented
# Fitting Simple Linear Regression to the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression() # Creating an object of that class
regressor.fit(X_train, y_train) # Fits the regressor object to the trainning set
# Now our Simple Linear Regressor has 'learnt' the correlations and can predict
# Predicting the Test set results.
# vector of predictions of the dependent variable
y_pred = regressor.predict(X_test) # Method that makes the predictions
# Visualizing the Training set results
# We will use the matplotlib
plt.scatter(X_train, y_train, color = 'red')
# We want the predictions of the train set to compare
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Training set)') # Title of plot
plt.xlabel('Years of experience') # x label
plt.ylabel('Salary')# y label
plt.show() # To expecify that is the end of the plot and want to show it
# Visualizing the Test set results
# We will use the matplotlib
plt.scatter(X_test, y_test, color = 'red')
# We want the predictions of the train set to compare
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Test set)') # Title of plot
plt.xlabel('Years of experience') # x label
plt.ylabel('Salary')# y label
plt.show() # To expecify that is the end of the plot and want to show it | true |
2ad7d9a66e33dd105970de44152471f32d15c145 | luhn/pizzeria | /pizzeria.py | 2,662 | 4.125 | 4 | import math
import pickle
import os.path
def add_pizza(pizzas):
"""Gather user input and add pizza to list"""
print 'Enter a pizza'
dm = input('Diameter (inches): ')
price = input('Price: $')
notes = raw_input('Notes (brand, toppings, etc.): ')
pizzas.append(Pizza(dm, price, notes))
def print_results(pizzas):
"""Sort pizzas by price/sq. in. and output in a fancy table."""
pizzas.sort(key=lambda pizza: pizza.price_per_sq_inch()) #Sort pizza by
#price per square inch.
print ''
print 'Pizzas, sorted by value from best to worst'
print ''
print 'Price | Diameter | $/sq. in. | Notes'
print '========================================='
for pizza in pizzas:
pizza.print_row()
def save_data(pizzas):
"""Pickles the pizzas list, and stores it in file"""
fn = raw_input('Enter filename: ')
with open(fn, 'w') as f:
pickle.dump(pizzas, f)
print 'Data saved to '+fn
def read_data(pizzas):
"""Reads in pickled data """
fn = raw_input('Enter filename: ')
if not os.path.exists(fn):
print 'Error: No such file.'
return
cuke = []
with open(fn, 'r') as f:
cuke = pickle.load(f)
print 'Pizzas loaded.'
pizzas.extend(cuke)
class Pizza(object):
def __init__(self, dm, price, notes):
"""Create a yummy pizza"""
self.dm = dm
self.price = price
self.notes = notes
def price_per_sq_inch(self):
"""Calculate price per square inch"""
area = (self.dm / 2) ** 2 * math.pi
return round(self.price / area, 4)
def print_row(self):
"""Print pizza as a row in the table"""
print ('${0:5g} | {1:8g} | ${2:8g} | '+self.notes).format(
self.price,
self.dm,
self.price_per_sq_inch(),
)
def main():
pizzas = []
print 'Pizzeria'
print '=========='
print 'Find the best pizza for the best price by comparing price / sq. '+\
'inch.'
while True:
print ''
print ''
print 'What would you like to do?'
print 'a = add a pizza'
print 'p = print results'
print 's = save data'
print 'r = read data'
print 'q = quit'
choice = raw_input('Choice: ')
if choice=='q':
break
elif choice=='a':
add_pizza(pizzas)
elif choice=='p':
print_results(pizzas)
elif choice=='s':
save_data(pizzas)
elif choice=='r':
read_data(pizzas)
print_results(pizzas)
if __name__=='__main__':
main()
| true |
178a8ad116a5e813e64490e829947f32d4ac09d0 | ManishBhojak/Python-Projects | /password_validity(prac 24).py | 644 | 4.25 | 4 | #Check Validity of a Password
import re
p=input("Enter your Password ")
x=True
while x:
if(len(p)<6 or len(p)>12):
break
elif not re.search("[a-z]",p):
break
elif not re.search("[A-Z]",p):
break
elif not re.search("[0-9]",p):
break
elif not re.search("[$#@]",p):
break
elif re.search("\s",p):
break
else:
print("Password you enter have [a-z],[A-Z],[0-9],[$#@] so, it is valid Password")
x=False
break
if x:
print("Password does not contain [a-z],[A-Z],[0-9],[$#@] so, it is invalid Password")
#Program Ended
| true |
e5d9ef664c58c91d581cf01bc9157d75034e8256 | AshZhang/2016-GWC-SIP-projects | /python/pygame/doc_scaven_hunt_2.py | 2,696 | 4.15625 | 4 | """
Pygame base template for opening a window
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_983kUMc
"""
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (127, 127, 127)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
# initialize the pygame class
pygame.init()
# Set the width and height of the screen [width, height]
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Set the title of the window
pygame.display.set_caption("DocScaven")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
class Circle():
def __init__ (self, color, mouse_position, x_speed, y_speed, radius):
self.x_pos = mouse_position[0]
self.y_pos = mouse_position[1]
self.x_speed = x_speed
self.y_speed = y_speed
self.color = color
self.radius = radius
def draw(self):
pygame.draw.circle(screen, self.color, (self.x_pos, self.y_pos), self.radius)
def move(self):
# move circle by x and y speed
# if circle reaches window edge, turn speed around
self.x_pos += self.x_speed
self.y_pos += self.y_speed
if self.x_pos > SCREEN_WIDTH or self.x_pos < 0:
self.x_speed *= -1
if self.y_pos > SCREEN_HEIGHT or self.y_pos < 0:
self.y_speed *= -1
circle_list = []
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
mouse_pos = pygame.mouse.get_pos()
if pygame.mouse.get_pressed()[0]:
print("Here!")
# color, mouse position, random x speed, random y speed, radius
my_circle = Circle(CYAN, mouse_pos, random.randint(-10, 10), random.randint(-10, 10), 20)
circle_list.append(my_circle)
# random.randint(0, 255),
# random.randint(20, 80)
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# If you want a background image, replace this clear with blit'ing the
# background image.
# --- Drawing code should go here
screen.fill(WHITE)
for i in circle_list:
i.draw()
i.move()
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Close the window and quit.
pygame.quit()
exit() # Needed when using IDLE
| true |
010c3949f762aca30451e7a93486c3e17df83254 | Joycrown/Wave4 | /match_flower_name.py | 1,330 | 4.4375 | 4 | #For the following practice question you will need to write code in Python in the workspace below. This will allow you to practice the concepts discussed in the Scripting lesson, such as reading and writing files. You will see some older concepts too, but again, we have them there to review and reinforce your understanding of those concepts.
#Question: Create a function that opens the flowers.txt, reads every line in it, and saves it as a dictionary. The main (separate) function should take user input (user's first name and last name) and parse the user input to identify the first letter of the first name. It should then use it to print the flower name with the same first letter (from dictionary created in the first function).
#Sample Output:
#>>> Enter your First [space] Last name only: Bill Newman
#>>> Unique flower name with the first letter: Bellflower
# Write your code here
# HINT: create a dictionary from flowers.txt
# HINT: create a function
def open_read():
with open('flowers.txt') as flower:
dictionary= {}
for n in flower:
(key, value) = n.split(':')
dictionary[key]= value[:-1]
name= input('Enter your name: ').upper()
index = name[0]
print(f'Unique flower name with the first letter: {dictionary[index]}')
open_read()
| true |
5f2190b522a2829703180911d43d66960ca257c4 | vskemp/madlib | /madlib.py | 715 | 4.4375 | 4 | # Prompt the user for the missing words to a Madlib sentence using the input function. You will make up your own Madlib sentence, but here's an example:
# ____(name)____'s favorite subject in school is ____(subject)____.
# With the above given sentence, this is what a user session might look like:
# $ python madlib.py
# Please fill in the blanks below:
# ____(name)____'s favorite subject in school is ____(subject)____.
# What is name? Marty
# What is subject? math
# Marty's favorite subject in school is math.
print("Please fill in the blanks below:")
mad_name = input("What is name? ")
mad_subject = input("What is subject? ")
print((mad_name) + "'s favorite subject in school is " + (mad_subject) + ".")
| true |
f79a9a78c00c472d98526460096c022ad0ebbc79 | zjj421/daily_coding | /coding_interviews/10_fibonacci.py | 958 | 4.125 | 4 | import datetime
# 递归
def fibonacci_recursive(n):
if n == 0:
return 0
if n == 1:
return 1
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
# 遍历
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
fib_1 = 1
fib_2 = 0
fib_n = -1
for i in range(2, n + 1):
fib_n = fib_1 + fib_2
fib_2 = fib_1
fib_1 = fib_n
return fib_n
def test_fibonacci():
n = 100
starttime = datetime.datetime.now()
fib_n = fibonacci_recursive(n)
duration = (datetime.datetime.now() - starttime).microseconds
print('fibonacci_recursive({}) = {}, time: {} us'.format(n, fib_n, duration))
starttime = datetime.datetime.now()
fib_n = fibonacci(n)
duration = (datetime.datetime.now() - starttime).microseconds
print('fibonacci({}) = {}, time: {} us'.format(n, fib_n, duration))
if __name__ == '__main__':
test_fibonacci()
| false |
bd58b4661743f116fbdd4c7ec7851dc5a4bea621 | MMGit64/Anagram | /Anagram.py | 948 | 4.34375 | 4 | def Anagram(str1, str2):
count1 = [0] * 26 #To count frequency of each character
count2 = [0] * 26
i = 0
while i < len(str1): #Counts frequency of each character for str1
count1[ord(str1[i])-ord('a')] += 1 # 'ord' refers to the unicode value for each respective character
i += 1
i =0
while i < len(str2):
count2[ord(str2[i])-ord('a')] += 1 #Count frequency of each character for str2
i += 1
result = 0 #Transverses the count arrays to find and remove the character
for i in range(26): #from both strings until they are anagrams.
result += abs(count1[i] - count2[i])
return result
# Driver program to run the case
if __name__ == "__main__":
str1 = "bcadeh"
str2 = "hea"
print(Anagram(str1, str2))
| true |
c3d1e0a7b00ea851fb30caa67b0e688ac35f9066 | MrChrisLia/Udemy_Learning | /milestone_2_self_written/utils/database.py | 1,801 | 4.3125 | 4 | import json
"""
Concerned with storing and retrieving books from a list.
"""
books = []
def add_book(title, author):
for b in books:
if title == b['Title'] and author == b['Author']: #check if the book is already in the list
print('This book already exists!')
break
else:
books.append({'Title': title, 'Author': author, 'Read': False}) #adds book to the list and creates the 'template' that other functions will run on
print("Your book has been added!")
def list_books():
for book in books:
#print(f"book:{book}")
print(f"Title: {book['Title']}, Author: {book['Author']}, Read: {book['Read']}") #lists all of the books
def prompt_read_book(book_name):
for b in books:
if book_name == b['Title']: #checks if a book is in the list by object name
b['Read'] = True #changes 'Read' status to True
print(f"You've read {b['Title']} now!")
break
else:
print("This book doesn\'t exist.")
def prompt_delete_book(book_name):
for b in books:
if book_name == b['Title']: # checks if a book is in the list by object name
books.remove(b) #deletes the book
print(f"You've deleted {b['Title']} now!")
break
else:
print("This book doesn\'t exist.")
def save_book_list():
with open("books_list.json", "w") as booksfile: #save to a file in json format
book_contents = json.dump(books, booksfile)
print("Book list saved!")
return book_contents
def load_book_list():
with open('books_list.json', 'r') as booksfile: #loads the file in json format
book_contents = json.load(booksfile)
for b in book_contents:
books.append(b)
print("Book list loaded!")
| true |
144c8e706e8f6e67e48b4b60f85ed46492931c01 | luchang59/leetcode | /246_Strobogrammatic_Number.py | 737 | 4.28125 | 4 | # A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
# Write a function to determine if a number is strobogrammatic. The number is represented as a string.
# Example 1:
# input: "69"
# output: True
# Example 2:
# input: "962"
# output: False
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
dic = {"0":"0", "1":"1", "6":"9", "8":"8", "9":"6"}
start, end = 0, len(num) - 1
while start <= end:
if num[start] not in dic or num[end] not in dic:
return False
if num[start] != dic[num[end]]:
return False
start += 1
end -= 1
return True | true |
074779d4cdaa2081db1f1c1edb69269a5d167d97 | luchang59/leetcode | /998_Maximum_Binary_Tree_II.py | 998 | 4.21875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
"""
for recursion, if no root or root.val < val, create a new node. and the node.left is root
else, root.right uses the function again, the arguments is the root.right and val.
untill find the suitable node.
"""
if not root or root.val < val:
node = TreeNode(val)
node.left = root
return node
root.right = self.insertIntoMaxTree(root.right, val)
return root
# use While-Loop
# prev, cur = None, root
# while cur and cur.vasl > val:
# prev, cur = cur, cur.right
# node = TreeNode(val)
# node.left = cur
# if prev: prev.right = node
# return root if root.val > val else node | true |
1b35b26ef297c197aa3c48efb7fa03de88c538bb | pyladieshki/workshops | /unicode_basics.py | 1,295 | 4.34375 | 4 | #-*- coding: utf-8-*-
#!!!we talk only about Python2 in these examples!!!
# two types that deal with text:
#---->str
#---->unicode
#for example:
str_type = 'some text'
print type(str_type)
unicode_type = u'some text'
print type(unicode_type)
#print them
print str_type
print unicode_type
#are these equal?
'some text' == u'some text'
###############################################################
#decode bytes
print 'decoded bytes from ascii:', 'some text'.decode('ascii')
print 'decoded bytes from utf-8:', 'some text'.decode('utf-8')
print 'decoded bytes from utf-8:', u'some text: ÅÅÅ'.encode('utf-8')
#this works
print 'some str stuff'
#this works too
print u'some unicode stuff: ÅÅÅÅ'
###############################################################
#writing to a file requires bytes
with open ('test', 'w') as f:
f.write('ÄÄÄÄ')
f.write(u'ÖÖÖ'.encode('utf-8'))
#text read from the file is in bytes -> str
with open('test', 'r') as f:
res = f.readline()
print 'type:', type(res)
unicode_res = res.decode('utf-8')
print unicode_res.encode('utf-8'), type(unicode_res)
#writing to a file without encoding it
#error, because print tries to encode into 'ascii'
#with open('test', 'a+') as f:
#f.write(u'ÅÅÅÅ')
print u'ÅÅÅÅ'.encode('utf-8')
| false |
95adac0322f95d99e2b2c19a2413778750c6a501 | DanFreemantle/code-club | /2019-08-21/a-square-loop.py | 672 | 4.28125 | 4 | '''
Task: "A square loop"
Difficulty: Intermediate
Description: Write a program that asks the user to input an integer between 2 and 20.
Output every number squared up to and including the number they entered. Each square should be on a separate line.
For instance, if the user enters "5" the expected output will be the numbers 0, 1, 2, 3, 4 and 5 squared:
0
1
4
9
16
25
'''
square = input("Please enter an integer between 2 and 20: ")
try:
maximum = int(square)
if maximum < 2 or maximum > 20:
raise ValueError()
for i in range(0, maximum + 1):
print(i * i)
except ValueError:
print("Please enter a valid number in the range 2 to 20") | true |
7c8351f67b3b715babd4b7981338c3c849eafbb6 | JakeNat/cos125 | /labs/lab01/task04.py | 1,173 | 4.1875 | 4 | # File: task04.py
# Author: Jake Natalizia
# Date: September 17th, 2019
# Section: B
# Email: jacob.natalizia@maine.edu
# Description: Calculates your distance from home and your average walking speed, based on the distance of your two paths.
# Collaboration: I did not collaborate with anyone.
pathOne = input("How far is your first path, in meters?")
pathTwo = input("How far is your second path, in meters?")
totalPath = pow((pow(float(pathOne), 2) + pow(float(pathTwo), 2)), 0.5)
totalPath = round(totalPath, 2)
print("You are currently " + str(totalPath) + " meters from home.")
# For step 3, rather than adding an additional calculation, you can
# just add 2.7 km to your original 3.6 km distance, since they're both westward.
# Now you get a total of 6.3 kilometers (6300 meters) west, which can be pathOne.
# Same concept for the time taken. Direction is superfluous. You only need the total time.
timeTaken = input("How long did it take to complete your journey, in hours?")
averageWalkingSpeed = (float(totalPath) / float(timeTaken)) / 1000
averageWalkingSpeed = round(averageWalkingSpeed, 2)
print("Your average walking speed was " + str(averageWalkingSpeed) + " kilometers per hour.") | true |
4bc44618c0101e0e64e7fb33c1124a64a85009b7 | JakeNat/cos125 | /homework/hw05/hw5a.py | 1,426 | 4.53125 | 5 | # File: hw5a.py
# Author: Jake Natalizia
# Date: October 30th, 2019
# Section: B
# Email: jacob.natalizia@maine.edu
# Description: Simulates up and down movement of a hailstone in a storm.
# Collaboration: I did not collaborate with anyone.
def oddHeight(height):
# While height is odd
while height % 2 != 0 and height != 1:
# Multiply height by 3, add 1, print height
height = (height * 3) + 1
print("Hail is currently at height " + str(height))
# If height is even
if height % 2 == 0:
evenHeight(height)
def evenHeight(height):
# While height is even
while height % 2 == 0:
# Divide height by 2, print height
height = height // 2
print("Hail is currently at height " + str(height))
# If height is odd, and isn't 1
if height % 2 != 0 and height != 1:
oddHeight(height)
elif height == 1:
print("The hailstone has stopped at height 1.")
def main():
height = int(input("Enter the starting height of the hailstone:"))
if height != 1:
print("Hail is currently at height " + str(height))
# If height is even
if height % 2 == 0:
evenHeight(height)
# If height is odd
elif height % 2 != 0 and height != 1:
oddHeight(height)
else:
print("The hailstone has stopped at height 1.")
main() | true |
b62cff0179162c2956b701bcf28c4b7bad307aac | ntapacTest/PythonForDataScience | /20191121/lesson02_set.py | 734 | 4.25 | 4 | my_set={1,2,3,4,5,5}
# Добавление
my_set.add(6)
# Если значение существует, то оно не добавляется
my_set.add(6)
# Удаление
my_set.remove(6)
# Проверка существования в сете
print(3 in my_set)
print(30 in my_set)
set1={1,2,3,4,5}
set2={1,3,5,6,7,8}
# Объеденение сетов
set3=set1.union(set2)
# Пересечение сетов
set4=set1.intersection(set2)
# Вичитание элементов которые входят в сет 1 и 2, остаются только уникальные
set5=set1.difference(set2)
# Проверка входит ли сет 2 в сет 1 как сабсет
result=set.issubset(set2)
| false |
8b25ed749a2bd930259f8cecf2bab4e1411bd9a2 | psamvatsar/Mathematics-Machine-Learning-Linear-Algebra-Codes | /Echelon form.py | 1,190 | 4.21875 | 4 | def fixRowTwo(A) :
# Insert code below to set the sub-diagonal elements of row two to zero (there are two of them).
A[2] = A[2]- A[2,0]*A[0]
A[2] = A[2]- A[2,1]*A[1]
# Next we'll test that the diagonal element is not zero.
if A[2,2] == 0 :
# Insert code below that adds a lower row to row 2.
A[2] = A[2]+A[3]
# Now repeat your code which sets the sub-diagonal elements to zero.
A[2] = A[2]- A[2,0]*A[0]
A[2] = A[2]- A[2,1]*A[1]
if A[2,2] == 0 :
raise MatrixIsSingular()
# Finally set the diagonal element to one by dividing the whole row by that element.
A[2] = A[2] / A[2,2]
return A
def fixRowThree(A) :
# Insert code below to set the sub-diagonal elements of row three to zero.
A[3] = A[3] - A[3,0] * A[0]
A[3] = A[3] - A[3,1] * A[1]
A[3] = A[3] - A[3,2] * A[2]
# Complete the if statement to test if the diagonal element is zero.
if A[3,3] == 0 :
raise MatrixIsSingular()
# Transform the row to set the diagonal element to one.
A[3] = A[3] / A[3,3]
return A
| true |
5f8a3007076b1a517fe0c6a14e54e25ee228a6fe | webdevajf/Learn-Python-The-Hard-Way | /ex33.py | 2,126 | 4.28125 | 4 | # This line creates var 'i' and give it a value of
# int 0.
i = 0
# This line creates var 'numbers' and gives it a value
# of an empty braket "[]"
numbers = []
# This line creates a while loop and give it the
# condition that it's code will run as long as the
# value of var 'i' is less than int 6.
while i < 6:
# This line prints a formated string with a
# placeholder that takes the value of var
# 'i'
print(f"At the top i is {i}")
# This line appends the value of var 'i' to
# the list object which is the value of var
# 'numbers'.
numbers.append(i)
# This line adds the value of int 1 to the value
# of var i. Another way to write this is "i += 1".
i = i + 1
# This line prints a string and then prints the
# value of var 'numbers'
print("Numbers now: ", numbers)
# This line prints a formated string with a
# placeholder that takes the value of var 'i'.
# Note: the key here is that the value of var 'i'
# has changed as it passed throught the function
# and it will now be different then it was at the
# top of the function (in the while loops first
# print statement).
print(f"At the bottom i is {i}")
# Because it is in a while loop the computer will,
# at this point, return to the top of the while loop
# and evaluate it's condition. If the condition
# evaluates to true the while loop will run again.
# If the condition evaluates to false it will move
# on to the first line in the script that
# follows the while loops code. The loop will run
# 6 times.
# This line prints a string.
print("The numbers: ")
# This line creates a for loop that reads var 'numbers'
# and passes it's value into the loop's arg 'num'.
# Since the value of var 'numbers' is a list object it
# will pass the elements from the list into the arg of
# the loop, one at a time, reading the for loop and
# running its code each time. It will run 6 times.
for num in numbers:
# This line prints the value that has been passed
# into arg 'num' with each particular running of
# the for loop.
print(num)
| true |
852f3829c188f6f1158b7ee7a4fde58c094e2696 | cotrat/UBUNTU-FILES | /pyprac/prac.py | 366 | 4.125 | 4 | shoppinglist = [] # empty list
item = input("Enter an item or type -1 to exit ")
while item != -1:
shoppinglist.append(item) # put the item in the array
item = input("Enter an item or type -1 to exit ") # reprompt the user
print ("The customer needs to purchase ")
print (len(shoppinglist))
print ("items, these items are")
print (shoppinglist) | true |
09f7f06234cb9a745c837fae051255c2ab1163a6 | addy96/edx | /MITx/6.00.1x/Week-6/Lecture-12/genPrimes.py | 561 | 4.125 | 4 | """Prime number generator"""
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def genPrimes():
'''
Generate prime numbers, one at the time
Use the next() method to get the next prime number
:return: Increasing sequence of prime numbers
'''
primes = []
number = 2
isPrime = True
while True:
for prime in primes:
if number % prime == 0:
isPrime = False
break
if isPrime:
primes.append(number)
yield number
number += 1
isPrime = True | true |
c0f1837e8e8f8a2904a6ac96bd8d57dd56ea2c70 | addy96/edx | /MITx/6.00.1x/Week-2/Lecture-3/dec2bin.py | 1,252 | 4.15625 | 4 | """Convert decimal numbers - integer or fractional - to binary"""
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def dec2bin(x):
"""
Convert a decimal number - integer or fractional inside the interval [-1, 1] - to binary
:param x: Decimal number (integer or fractional inside the interval [-1, 1])
:return: Binary number
"""
# If x is a float number outside the interval [-1, 1], STOP
value = abs(x)
if type(x) != type(1) and value > 1:
return None
result = ''
if value == 0:
return '0'
elif value < 1:
# Fractional number inside the interval [-1, 1]
power = 0
while value*(2**power)%1 != 0:
power += 1
value = int(value*(2**power))
# Convert <value> in binary and save to <result>
while value > 0:
result = str(value%2) + result
value = value/2
# If <x> is negative, prefix the '-' (minus) sign
if x < 0:
result = '-' + result
# If <x> is a fractional number inside the interval [-1, 1], right shift of p-len(result) position
if abs(x) < 1:
for i in range(power - len(result)):
result = '0' + result
result = result[0:-power] + '.' + result[-power:]
return result | true |
88b31c61a9a618cba66dc7e62fba7337a7b7cb6e | Pradhvan/assignment | /problem.py | 2,028 | 4.21875 | 4 | """
Write a function that takes an array of integers given a string
as an argument and returns the second max value from the input array.
If there is no second max return -1.
1. For array ["3", "-2"] should return "-2"
2. For array ["5", "5", "4", "2"] should return "4"
3. For array ["4", "4", "4"] should return “-1”
(duplicates are not considered as the second max)
4. For [] (empty array) should return “-1”.
"""
import sys
import unittest
def secondMaxValue(numbers):
"""
Function that returns the secondMaxValue from the array list of strings.
"""
if len(numbers) == 0:
return "-1"
else:
size = len(numbers)
# Setting the placeholders to the min value and index to zero.
largest, secondLargest, index = -sys.maxsize - 1, -sys.maxsize - 1, 0
# Iterating over the array list to check the secondMaxValue
while index < size:
# Adding initial largest and second largest value
if int(numbers[index]) > largest:
secondLargest = largest
largest = int(numbers[index])
# Comparing the cuurent index number
elif int(numbers[index]) > secondLargest and \
int(numbers[index]) != largest:
secondLargest = int(numbers[index])
index += 1
if largest == int(numbers[index - 1]):
return "-1"
else:
return str(secondLargest)
class Test(unittest.TestCase):
array1 = ["3", "-2"]
array2 = ["5", "5", "4", "2"]
array3 = ["4", "4", "4"]
array4 = []
def test_secondMaxValue(self):
"""
Class to test the secondMaxValue function
"""
result = secondMaxValue(self.array1)
self.assertEqual("-2", result)
result = secondMaxValue(self.array2)
self.assertEqual("4", result)
result = secondMaxValue(self.array3)
self.assertEqual("-1", result)
result = secondMaxValue(self.array4)
self.assertEqual("-1", result)
if __name__ == '__main__':
unittest.main()
| true |
137b8462db6ebccb0a52726b0a9991190bc06718 | jaytparekh7121994/PythonProjects | /DataStructure_nestedList.py | 1,392 | 4.125 | 4 | combs = []
for i in [1, 2, 3]:
for j in [3, 2, 1]:
combs.append((i, j))
# combs.append(i,j) shows error that append can take only one argument.
# Add parantheses to i,j -> (i,j) ,it makes it a tuple.
# Hence, its just one object passed in append()
print(combs)
print("looping list within list and printing the tuple which is in ()")
print(40 * "-")
"""-------------------------------------------------------------------------"""
""" Nested List Example :"""
matrix = [
["Sunday", "Saturday"],
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
["Holi", "Diwali", "Eid", "Christmas", "Lohri"]
]
print([[row[i] for row in matrix]for i in range(2)])
print("End of Single line transpose")
print(40 * "-")
""" ------------------------------------------------------------------------"""
transposed = []
for i in range(2):
print("i = ", i)
# the following 3 lines implement the nested listcomp
transposed_row = []
for row in matrix:
print("Row", row, "of", i, "is", row[i])
# for i=0 each rows first element will be returned
# for i=1 each rows second element will be returned
transposed_row.append(row[i])
transposed.append(transposed_row)
print("transposed =", transposed)
print("End of multiple looping transpose", '\n', 40 * "-")
| true |
50cf7e665eb97396300d7997e05409f2088f6f8c | Babkock/python | /6 - Functions/Module6/more_functions/string_functions.py | 640 | 4.3125 | 4 | #!/usr/bin/python3
"""
Tanner Babcock
October 1, 2019
Module 6, topic 3: Function parameters
"""
"""
This function multiples the string 'message' 'n' number of times,
and returns the resulting string
:param message: The message to be multiplied
:param n: Number of times to be multiplied
:returns: 'message' multiplied 'n' times
:raises ValueError: If message or n are invalid
"""
def multiply_string(message, n):
if (isinstance(message, str) != True):
raise ValueError
if (isinstance(n, int) != True):
raise ValueError
x = 0
total = ""
while x < n:
total += message
x += 1
return total
| true |
e6d075f3d7d81ded2c68623ce11a0ff9f5a17609 | Babkock/python | /3 - Strings, Basic IO, Operators/io/average_scores/average_scores.py | 814 | 4.21875 | 4 | #!/usr/bin/python3
"""
Tanner Babcock
September 10, 2019
Module 3, topic 2: Basic input and output
"""
def average():
# get 3 scores from the user
score1 = input("Enter the first score: ")
score2 = input("Enter the second score: ")
score3 = input("Enter the third score: ")
# convert all input strings to floats, then compute
total = (float(score1) + float(score2) + float(score3)) / 3;
return total
if __name__ == '__main__':
# get first name, last name, and age
first_name = input("First name: ")
last_name = input("Last name: ")
age = input("Age: ")
# get average
average_scores = average()
# print average_scores with only 2 decimal places
print("{0}, {1} age: {2} average grade: {3:.2f}".format(first_name, last_name, age, average_scores))
exit(0)
| true |
322273e2bc3695a8506040d40255fa38f479a503 | Babkock/python | /13 - Database/number_guess/number_guess.py | 1,820 | 4.28125 | 4 | #!/usr/bin/python3
"""
Tanner Babcock
November 19, 2019
Module 13, topic 1: GUI and Data Visualization
"""
import tkinter
import random
class NumberGuesser:
def __init__(self):
self.guessed_list = []
self.the_number = random.randint(1,8)
def add_guess(self, guess):
self.guessed_list.append(guess)
def is_winner(self):
if self.guessed_list[-1] == self.the_number:
return True
else:
return False
def button_press(which):
guesser.add_guess(which)
if guesser.is_winner():
label.config(text="You win!")
else:
label.config(text="That's not the number")
if __name__ == "__main__":
m = tkinter.Tk()
m.title("Guess The Number")
guesser = NumberGuesser()
label = tkinter.Label(m, text="Guess a Number!")
label.grid(row=0)
button1 = tkinter.Button(m, text="1", width=5, command = lambda: button_press(1)).grid(row=1, column=0)
button2 = tkinter.Button(m, text="2", width=5, command = lambda: button_press(2)).grid(row=1, column=1)
button3 = tkinter.Button(m, text="3", width=5, command = lambda: button_press(3)).grid(row=1, column=2)
button4 = tkinter.Button(m, text="4", width=5, command = lambda: button_press(4)).grid(row=1, column=3)
button5 = tkinter.Button(m, text="5", width=5, command = lambda: button_press(5)).grid(row=2, column=0)
button6 = tkinter.Button(m, text="6", width=5, command = lambda: button_press(6)).grid(row=2, column=1)
button7 = tkinter.Button(m, text="7", width=5, command = lambda: button_press(7)).grid(row=2, column=2)
button8 = tkinter.Button(m, text="8", width=5, command = lambda: button_press(8)).grid(row=2, column=3)
exit_button = tkinter.Button(m, text="Exit", width=20, command=m.destroy).grid(row=3, column=1)
m.mainloop()
| true |
2935bf734f69cb2977468eeeb25cf390717b9ef6 | EdsonRodrigues1994/Mundo-2-Python | /desafio066.py | 461 | 4.125 | 4 | '''Crie um programa que leia varios numeros inteiros pelo teclado.
O prograsma só vai parar quando o usuário digitar o valor 999, que é a condição de parada.
No final mostre quantos números foram digitados e qual foi a soma entre eles.'''
soma = 0
count = 0
while True:
num = int(input("Digite um número: "))
if num == 999:
break
soma += num
count += + 1
print(f"Você digitou {count} número(s) e a soma entre eles é {soma}.") | false |
e4601c9a25c8da6e922020a1053e299dd7de7fba | EdsonRodrigues1994/Mundo-2-Python | /desafio064.py | 508 | 4.125 | 4 | '''Crie um programa que leia varios números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999, qe é a condicao de parada. No final
mostre quantos números foram digitados e qual foi a soma entre eles.'''
num = 0
count = 0
soma = 0
while num != 999:
num = int(input("Digite números, para sair digite '999': "))
if num != 999:
count += + 1
soma += + num
else:
print("Você digitou {} números e a soma entre eles é {}.".format(count, soma)) | false |
bb7100d826b86cbaf1723886492e8bbd839a914a | DanielDavisCS/SYSNETIIPROJ | /MyPython/compute_stats.py | 2,038 | 4.4375 | 4 | #!/usr/bin/env python
'''
Name: Thomas Cole Amick
Course:COP3990C
Assignment:hw03
Run: python compute_stats.py <file_name.csv>
Description: Takes in input from a csv file and calculates the mean, and variance of each line.
For each line of the input file, the mean, variance and number of columns are writen to the output file
'''
#import librarys
import sys
#define functions
def calc_mean(num_list):
"""Calculates mean; The parameter should be a list to perform calculation correctly"""
num = 0.0
for i in num_list:
num += float(i)
return num/len(num_list)
def calc_variance(num_list):
"""Calculate variance; The parameter should be a list to perform the calculation correctly"""
num = 0.0
for i in num_list:
num += float(i)**2
return (num/len(num_list)) - calc_mean(num_list)**2
#check for proper command line arguments"""
if len(sys.argv) != 3:
print 'Incorrect number of command line arguments'
print 'python compute_stats.py <csv_file.csv> <some_output_file.csv>'
sys.exit()
if sys.argv[1][-3:] != 'csv' or sys.argv[2][-3:] != 'csv':
print 'Incorrect file extensions'
print 'python compute_stats.py <csv_file.csv> <some_output_file.csv>'
sys.exit()
#define variables
csv_data = {}
mean = variance = col_count = 0.0
#open csv files
argv_list = sys.argv
csv_file_in = open(argv_list[1],'r')
csv_file_out = open(argv_list[2], 'w')
#create outfile header
header = '# of columns,mean,variance\n'
csv_file_out.write(header)
#calculates csv file statistics by reading data line by line from the input file. Writes # of columns, mean, and variance to out_put file in csv format"""
print "Calculating on " + argv_list[1] + "..."
lines = csv_file_in.readlines()
for line in lines:
line = line.strip().split(',')
mean = calc_mean(line)
variance = calc_variance(line)
row = str(len(line)) + ',' + str(mean) + ',' + str(variance) + '\n'
csv_file_out.write(row)
print "Writing to " + argv_list[2] + "..."
#close files
csv_file_in.close()
csv_file_out.close()
| true |
a7cbac6baff8a617eec8b53ab63253c3526dd547 | codevscolor/codevscolor | /python/python-count-words-characters-string/example1.py | 381 | 4.1875 | 4 | # https://codevscolor.com/python-count-words-characters-string
# 1
word_count = 0
char_count = 0
# 2
usr_input = input("Enter a string : ")
# 3
split_string = usr_input.split()
# 4
word_count = len(split_string)
# 5
for word in split_string:
# 6
char_count += len(word)
# 7
print("Total words : {}".format(word_count))
print("Total characters : {}".format(char_count)) | true |
77b61cb90bd030381599fc3c629fc5a7d1244355 | codevscolor/codevscolor | /python/python-print-even-odd-index-characters-string/example1.py | 374 | 4.21875 | 4 | # https://codevscolor.com/python-print-even-odd-index-characters-string
given_string = input('Enter a string: ')
even_chars = []
odd_chars = []
for i in range(len(given_string)):
if i % 2 == 0:
even_chars.append(given_string[i])
else:
odd_chars.append(given_string[i])
print(f'Odd characters: {odd_chars}')
print(f'Even characters: {even_chars}') | false |
c133cabdc9492f1d449e4d0bbd83ccb041d60bcf | AnaBVA/pythonCCG_2021 | /Tareas/PYTHON_2021-[2] Busqueda del Codón inicial y secuencia transcrita-2553/Rodrigo Daniel Hernandez Barrera_8772_assignsubmission_file_/busqueda_codon_secuencia.py | 1,676 | 4.21875 | 4 | '''
NAME
Busqueda del Codón inicial y secuencia transcrita
VERSION
1.0
AUTHOR
Rodrigo Daniel Hernández Barrera
DESCRIPTION
Find the start codon and the transcribed sequence
CATEGORY
Genomic sequence
INPUT
Read a DNA sequence entered by the user
OUTPUT
Returns as output the start and end positions of the sequence
to be transcribed and its nucleotide sequence
EXAMPLES
Input
dna = 'AAGGTACGTCGCGCGTTATTAGCCTAAT'
Output
El codon AUG empieza en la posicion 4 y termina en 19, tomando en cuenta el 0 como
la posicion del primer nucleotido.
Fragmento de RNA que es transcrito representado en DNA es: TACGTCGCGCGTTAT
Fragmento de RNA que es transcrito representado en RNA es: UACGUCGCGCGUUAU
'''
print('Introduzca la secuencia de DNA de interes:')
dna = input() # La secuencia input se almacena en la variable dna
codon_inicio = 'TAC'
codon_termino = 'ATT'
'''El metodo str.find() devuelve el índice más bajo en el que se encuentre
el codon de inicio, aplicado tambien para encontrar la posicion del codon de termino'''
inicio = dna.find(codon_inicio)
final = dna.find(codon_termino)
'''Se corta la secuencia para obtener la secuencia transcrita y se suma 2 para
incluir el codon de paro completo en el output'''
transcrito = dna[inicio:final + 2]
print('El codon AUG empieza en la posicion ' + str(inicio) + ' y termina en ' + str(final + 2) + ', tomando en cuenta el 0 como la posicion del primer nucleotido.')
print('Fragmento de RNA que es transcrito representado en DNA es: ' + transcrito)
print('Fragmento de RNA que es transcrito representado en RNA es: ' + transcrito.replace('T', 'U'))
| false |
f5e70061ea969230ca0b72d43acc5459c548cee9 | AnaBVA/pythonCCG_2021 | /Tareas/PYTHON_2021-[9] Regiones ricas en AT-2984/Daianna González Padilla_10042_assignsubmission_file_/AT_regions.py | 2,086 | 4.28125 | 4 | '''
NAME
AT_regions.py
VERSION
[1.0]
AUTHOR
Daianna Gonzalez Padilla <daianna@lcg.unam.mx>
DESCRIPTION
This programs gets a dna sequence and returns the AT rich regions of it.
CATEGORY
DNA sequence analysis
USAGE
None
ARGUMENTS
None
INPUT
The dna sequence given by the user
OUTPUT
Those regions of the dna sequence that are AT rich
EXAMPLES
Example 1: gets CTGCATTATATCGTACGAAATTATACGCGCG and returns ATTATAT
AAATTATA
GITHUB LINK
https://github.com/daianna21/python_class/blob/master/scripts/AT_regions.py
'''
import re
class AmbiguousBaseError(Exception):
pass
def AT_rich_seq(dna):
'''
This function receives a dna sequence and returns the AT rich regions (the ones with 5 to 15 A or T
nucleotides). It also evaluates that the sequence has only A,T.C or G.
'''
#Look up the characters that are not A,T,G or C in the sequence
matches = re.finditer(r"[^ATGC]", dna)
# If the sequence has only A,T,G or C, the regions that have 5 to 15 A or T are printed, otherwise
# an error is raised and the non allowed characters and their positions are printed
if not re.search(r"[^ATGC]", dna):
regions = re.finditer(r'((A|T){5,15})', dna)
empty=False
print("AT rich regions:")
for region in regions:
if region.group():
empty=True
print(region.group())
# If there are not AT rich regions, a message is printed
if empty==False:
print("No AT rich regions found")
else:
for m in matches:
base = m.group()
pos = m.start()
print(base, " found at position ", pos)
raise AmbiguousBaseError()
try:
#Ask for the dna sequence and call the function
dna = input("Insert the dna sequence, use capital letters:\n")
AT_seq = AT_rich_seq(dna)
except AmbiguousBaseError:
print('Error: Ambiguous bases found in the dna sequence') | true |
e841af2b2db3fc2f7a91c8ae267ceae7268eb141 | NeelimaNeeli/Python3 | /own_functions.py | 777 | 4.4375 | 4 | #function = this executes the block of code only WHEN IT IS CALLED .....
#this is a very logical concept....see below example.
def weapon(knife): #Here,weapon is a function that i have created.and knife inside the weapon brackets will acts as a variable like
print(knife) #its acts an empty variable.so if we print knife it shows nothing coz its an empty variable. THE OWN CREATED
weapon("axe") #FUCNTION ONLY EXECUTES WHEN ITS CALLED.So here axe acts as knife = axe ..knife is an empty variable so axe is beed added.
#def hello(first_name , last_name):
# print("hii " + first_name + " " + last_name)
#hello('gokul','neeli') #-->this is calling
#def neeli(): #---> creaing own function
# print("gokul")
#neeli() #--> this is calling
| true |
17827795eec9743900550ffb86737cb29db1fc49 | NeelimaNeeli/Python3 | /nested_func.py | 614 | 4.46875 | 4 | #nested function calls = function calls inside other functions
# innermost function calls are resolved first
# returned value is used as argument for the next outer function
# for example:
#num = input("enter the whole positive number : ")
#num = float (num)
#num = int (num)
#num = round (num)
#num = abs (num)
#print(num)
#now The above example can be created in nested fucntion calls :
print(round(abs(int(float(input("enter the whole positive number : "))))))
#6 lines of code can be printed in single line of code.... this is nested function calls. | true |
861cf4d4ee03100efd8836bcd7b661d0ca235100 | Nefariusmag/python_scripts | /learn_python/lesson2/age.py | 1,749 | 4.15625 | 4 | # Попросить пользователя ввести возраст при помощи input и положить результат в переменную
# Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: учиться в детском саду, школе, ВУЗе или работать
# Вызвать функцию, передав ей возраст пользователя и положить результат работы функции в преременную
# Вывести содержимое переменной на экран
def what_age():
age = input('Сколько полных лет?')
while True:
try:
age = int(age)
return age
except ValueError:
age = input('На этот раз введи просто целые числа своего возраста!!\n')
def where_to_go(age):
if age >= 22:
return 'Go to work!'
elif 18 <= age <= 21:
return 'Пора на занятия'
elif 6 <= age <= 17:
return 'Звонок для учителя..'
else:
return 'Агу агу'
# Чужое интересное решение с return
# def user_age(age):
# if age < 0 or age > 100:
# return "Неправильный возраст"
# return {
# 0 < age < 3: 'Ясли',
# 3 <= age < 7: 'Детский сад',
# 7 <= age < 17: 'Школа',
# 17 <= age < 22: 'Институт',
# 22 <= age: 'Работа'
# }[True]
def main():
age = what_age()
print(where_to_go(age))
if __name__ == '__main__':
main()
| false |
25cf94797599d2066238c175a0e9298e0713296f | jakeportra/python-challenge | /PyBank/main.py | 1,219 | 4.15625 | 4 | #Import modules
import pandas as pd
#Read CSV file, put in dataframe
bank_data = "../../../ClassRepo6/UofM-STP-DATA-PT-11-2019-U-C/03-Python/Homework/PyBank/Resources/budget_data.csv"
bank_df = pd.read_csv(bank_data)
#The total number of months included in the dataset
total_months = len(bank_df.index)
#The net total amount of "Profit/Losses" over the entire period
profit_loss = bank_df['Profit/Losses'].sum()
#The average of the changes in "Profit/Losses" over the entire period
#The greatest increase in profits (date and amount) over the entire period
greatest_increase = bank_df['Profit/Losses'].max()
#The greatest decrease in losses (date and amount) over the entire period
greatest_loss = bank_df['Profit/Losses'].min()
#Print Analysis
print("Financial Analysis")
print("----------------------------")
print(f"Total Months: {total_months}")
print("Total Profit (+) / Loss (-): $", "{:0,.2f}".format(float(profit_loss)))
print("Average Change: ")
print("Greatest Increase in Profits: ", "{:0,.2f}".format(float(greatest_increase)))
print("Greatest Decrease in Profits: ", "{:0,.2f}".format(float(greatest_loss)))
#Export text file
bank_df.to_csv("Output/bank_df.csv", index=False, header=True)
| true |
fb05fa518fe13a29d05e6b14340a28f82dd1fd45 | TechClubPro/Tasks | /SouthIndiaStateInfo/SouthStateInfo.py | 906 | 4.5625 | 5 | """ Program to Display Info about States in South India"""
#Info of States
"""
"kerala": "God's own Creation, Full of Natural beauty",
"karnataka": "It has India's biggest IT Hub",
"Tamilnadu":"It is rich in cultural heritage, beautiful temples",
"Andhra Pradesh":"It is known for Kuchipudi Dance",
"Telangana":"It is famous for Hydrabadi Pearls"
"""
#Storing Info in Dictionary
stateInfo={"Kerala":"God's own Creation, Full of Natural beauty",
"Karnataka":"It has India's biggest IT Hub",
"TamilNadu":"It is rich in cultural heritage, beautiful temples",
"Andhra Pradesh": "It is known for Kuchipudi Dance",
"Telangana":"It is famous for Hydrabadi Pearls"}
#Take the user Input
state= input("Please enter the state name: ")
if state in stateInfo.keys():
print(stateInfo[state])
else:
print("State not in South India")
| false |
e4a240b0eadc6a6674bc13051d07a539413ea3b5 | LoriImbesi/learning-python | /ex8.py | 709 | 4.3125 | 4 | # This is function called "formatter". It is assigned four {} which will turn
# the formatter variable into four strings.
formatter = "{} {} {} {}"
# Take the formatter string defined on line 3 and call its format function.
# Pass the four arguments, 1, 2, 3, 4 to it.
# The result of calling format on formatter is a new string that has
# the {} replaced with the four variables. Print will print these out.
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"I am",
"not afraid,",
"Toad said",
"to Frog."
)) | true |
75f877520d5b9b707bbad5c806c4a89cdbc8ae79 | realpython/materials | /python-self-type/accounts_string.py | 1,632 | 4.15625 | 4 | import random
from dataclasses import dataclass
@dataclass
class BankAccount:
account_number: int
balance: float
def display_balance(self) -> "BankAccount":
print(f"Account Number: {self.account_number}")
print(f"Balance: ${self.balance:,.2f}\n")
return self
def deposit(self, amount: float) -> "BankAccount":
self.balance += amount
return self
def withdraw(self, amount: float) -> "BankAccount":
if self.balance >= amount:
self.balance -= amount
else:
print("Insufficient balance")
return self
@dataclass
class SavingsAccount(BankAccount):
interest_rate: float
@classmethod
def from_application(
cls, deposit: float = 0, interest_rate: float = 1
) -> "SavingsAccount":
# Generate a random seven-digit bank account number
account_number = random.randint(1000000, 9999999)
return cls(account_number, deposit, interest_rate)
def calculate_interest(self) -> float:
return self.balance * self.interest_rate / 100
def add_interest(self) -> "SavingsAccount":
self.deposit(self.calculate_interest())
return self
account = BankAccount(account_number=1534899324, balance=50)
(
account.display_balance()
.deposit(50)
.display_balance()
.withdraw(30)
.display_balance()
)
savings = SavingsAccount.from_application(deposit=100, interest_rate=5)
(
savings.display_balance()
.add_interest()
.display_balance()
.deposit(50)
.display_balance()
.withdraw(30)
.add_interest()
.display_balance()
)
| true |
2bfd0586871bba39fc96587898e04f7dee2d7098 | realpython/materials | /python-eval-mathrepl/mathrepl.py | 2,317 | 4.1875 | 4 | #!/usr/bin/env python3
"""MathREPL, a math expression evaluator using Python's eval() and math."""
import math
__version__ = "1.0"
__author__ = "Leodanis Pozo Ramos"
ALLOWED_NAMES = {
k: v for k, v in math.__dict__.items() if not k.startswith("__")
}
PS1 = "mr>>"
WELCOME = f"""
MathREPL {__version__}, your Python math expressions evaluator!
Enter a valid math expression after the prompt "{PS1}".
Type "help" for more information.
Type "quit" or "exit" to exit.
"""
USAGE = f"""
Usage:
Build math expressions using numeric values and operators.
Use any of the following functions and constants:
{', '.join(ALLOWED_NAMES.keys())}
"""
def evaluate(expression):
"""Evaluate a math expression."""
# Compile the expression eventually raising a SyntaxError
# when the user enters an invalid expression
code = compile(expression, "<string>", "eval")
# Validate allowed names
for name in code.co_names:
if name not in ALLOWED_NAMES:
raise NameError(f"The use of '{name}' is not allowed")
# Evaluate the expression eventually raising a ValueError
# when the user uses a math function with a wrong input value
# e.g. math.sqrt(-10)
return eval(code, {"__builtins__": {}}, ALLOWED_NAMES)
def main():
"""Main loop: Read and evaluate user's input."""
print(WELCOME)
while True:
# Read user's input
try:
expression = input(f"{PS1} ")
except (KeyboardInterrupt, EOFError):
raise SystemExit()
# Handle special commands
if expression.lower() == "help":
print(USAGE)
continue
if expression.lower() in {"quit", "exit"}:
raise SystemExit()
# Evaluate the expression and handle errors
try:
result = evaluate(expression)
except SyntaxError:
# If the user enters an invalid expression
print("Invalid input expression syntax")
continue
except (NameError, ValueError) as err:
# If the user tries to use a name that isn't allowed
# or an invalid value to a given math function
print(err)
continue
# Print the result if no error occurs
print(f"The result is: {result}")
if __name__ == "__main__":
main()
| true |
ba0411d1ae1c613c1fc873874b1f5ad75b21b178 | realpython/materials | /python-interview-problems-parsing-csv/full_code/test_weather_v1.py | 2,189 | 4.25 | 4 | #!/usr/bin/env python3
""" Find the day with the highest average temperature.
Write a program that takes a filename on the command line and processes the
CSV contents. The contents will be a CSV file with a month of weather data,
one day per line.
Determine which day had the highest average temperature where the average
temperature is the average of the day's high and low temperatures. This is
not normally how average temperature is computed, but it will work for our
demonstration.
The first line of the CSV file will be column headers:
Day,MxT,MnT,AvT,AvDP,1HrP TPcn,PDir,AvSp,Dir,MxS,SkyC,MxR,Mn,R AvSLP
The day number, max temperature, and min temperature are the first three
columns.
Write unit tests with Pytest to test your program.
"""
import pytest
import weather_v1 as wthr
@pytest.fixture
def mock_csv_data():
return [
"Day,MxT,MnT,AvT,AvDP,1HrP TPcn,PDir,AvSp,Dir,MxS,SkyC,MxR,Mn,R AvSLP",
"1,88,59,74,53.8,0,280,9.6,270,17,1.6,93,23,1004.5",
"2,79,63,71,46.5,0,330,8.7,340,23,3.3,70,28,1004.5",
]
@pytest.fixture
def mock_csv_file(tmp_path, mock_csv_data):
datafile = tmp_path / "weather.csv"
datafile.write_text("\n".join(mock_csv_data))
return str(datafile)
def test_no_lines():
no_data = []
for _ in wthr.get_next_day_and_avg(no_data):
assert False
def test_trailing_blank_lines(mock_csv_data):
mock_csv_data.append("")
all_lines = [x for x in wthr.get_next_day_and_avg(mock_csv_data)]
assert len(all_lines) == 2
for line in all_lines:
assert len(line) == 2
def test_mid_blank_lines(mock_csv_data):
mock_csv_data.insert(1, "")
all_lines = [x for x in wthr.get_next_day_and_avg(mock_csv_data)]
assert len(all_lines) == 2
for line in all_lines:
assert len(line) == 2
def test_get_max_avg(mock_csv_file):
assert wthr.get_max_avg(mock_csv_file) == (1, 73.5)
def test_get_next_day_and_avg(mock_csv_data):
reader = wthr.get_next_day_and_avg(mock_csv_data)
assert next(reader) == (1, 73.5)
assert next(reader) == (2, 71)
with pytest.raises(StopIteration):
next(reader)
| true |
cf0c6eac330dc5b8e938af95ead9798ef79d7053 | realpython/materials | /name-main-idiom/echo_args.py | 356 | 4.15625 | 4 | import sys
def echo(text: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in range(repetitions, 0, -1):
echoed_text += f"{text[-i:]}\n"
return f"{echoed_text.lower()}."
def main() -> None:
text = " ".join(sys.argv[1:])
print(echo(text))
if __name__ == "__main__":
main()
| false |
c2af030947a610011b70f6dcb06e0f17e9e291e7 | MabelOlivia/Python-projects | /variable/even and odd.py | 316 | 4.1875 | 4 | x = 3
y = 24
i = x
print("Here are odd numbers between 3 and 24:")
if i % 2 == 0:
i += 1
while i <= y:
print(i)
i += 2
print("Here are even numbers between 3 and 24:")
for num in range(x, y):
if num % 2 == 0:
print(num)
for num in range(x, y):
if num % 2 != 0:
print(num)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.