blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
af32739412f82b395268bf8a13e89b42184a8bb8 | ton4phy/hello-world | /Python/59. Cycles.py | 817 | 4.125 | 4 | # Exercise
# Implement the is_arguments_for_substr_correct predicate function, which takes three arguments:
# the string
# index from which to start extraction
# extractable substring length
# The function returns False if at least one of the conditions is true:
# Negative length of the extracted substring
# Negative given index
# The specified index extends beyond the entire line.
# The length of the substring in the amount with the specified index extends beyond the boundary of the entire line.
# Otherwise, the function returns True.
def is_arguments_for_substr_correct(string, index, length):
if index < 0:
return False
elif length < 0:
return False
elif index > len(string) - 1:
return False
elif index + length > len(string):
return False
return True
| true |
967788a456b5c57b5b5e48a71c2b70fafec26114 | patilsakshi123/python.fun | /fibonacci sequence.py | 379 | 4.28125 | 4 | nterms= int(input("how many terms:"))
n1,n2= 0,1
count=0
if nterms <=0:
print("please enter a positive integer:")
elif nterms ==1:
print("Fibonacci sequence upto", nterms ,":")
else:
print("Fibonacci sequence :")
while count < nterms :
print(n1)
nth =n1+n2
n1=n2
n2=nth
count+=1
| false |
bd152a5e10c36bfc628bcd88b405966b3741c0c2 | Chriskoka/Kokanour_Story | /Tutorials/mathFunctions.py | 557 | 4.28125 | 4 | """
Math Functions
"""
#Variables
a = 3
b = -6
c = 9
#Addition & Subtraction
print(a+b)
print(a-b)
#Multiplication & Division
print(a * b)
print(a / b)
#exponents
print(a ** b) # Notice ** means to the power of
print(b ** a)
#Square Root & Cube Root
print(c ** (1/3))
print(c ** (1/2))
#Modulus (% symbol is used) -- Only returns the remainder after division
print(c % a) #Said as c mod a
print(c%4)
"""In order to do advanced math like sine, cosine, etc, you have to inport math and add .math to the function"""
import math
print(math.sin(a)) | true |
20ffa4780a571b56cd17304dde237f4a4fb7eed5 | Chriskoka/Kokanour_Story | /Tutorials/addSix.py | 233 | 4.3125 | 4 | """
This program will take the input of the user and return that number plus 6 in a print statement
"""
numb = int(input ('Choose an integer from 1 to 10. Input: '))
print ('The number ' + str(numb) + ' plus six = ' + str(numb + 6)) | true |
0838e7bca4295999e847c41b218bd1b5b928e6c1 | josandotavalo/OSSU | /001-Python-for-Everyone/Exercise-9.5.py | 814 | 4.15625 | 4 | # Exercise 5: Write a program to read through the mail box data and when you find line that starts
# with “From”, you will split the line into words using the split function. We are interested in who
# sent the message, which is the second word on the From line.
# You will parse the From line and print out the second word for each From line, then you will also
# count the number of From (not From:) lines and print out a count at the end.
file_name = input("Enter file name: ")
if len(file_name) < 1 : file_name = "mbox-short.txt"
file_hand = open(file_name)
count = 0
for line in file_hand :
if line.startswith("From:") :
aux = line.split()
email = aux[1]
print(email)
count = count + 1
print("There were", count, "lines in the file with From as the first word") | true |
40626631a907c84562a9cb5d4fc47b0aab78da5f | Edward-Lengend/python | /PycharmProjects/11面向对象/py_18_类属性.py | 1,178 | 4.4375 | 4 | """
类属性就是类对象所拥有的属性,它被该类的所有实例对象所共有。
类属性可以使用类对象或实例对象访问。
类属性的优点
·记录的某项数据始终保持一致时,则定义类属性。
·实例属性要求每个对象为其单独开辟一份内存空间来记录数据,
而类属性为全类所共有,仅占用一份内存,更加节省内存空间。
"""
# 1.定义类, 定义类属性
class Dog(object):
tooth = 10
# 2.创建对象
wangcai = Dog()
xiaoqi = Dog()
# 3.访问类属性和类对象
print(Dog.tooth) # 类属性可以通过类访问
print(wangcai.tooth)
print(xiaoqi.tooth) # 类属性可以通过对象访问
# 4.修改类属性
"""
类属性只能通过类对象修改,不能通过实例对象修改
如果通过实例对象修改类属性,表示的是创建了一个实例属性。
"""
Dog.tooth = 20
print(f'Dog.tooth = {Dog.tooth}')
xiaoqi.tooth = 30
print(f'Dog.tooth = {Dog.tooth}')
print(f'xiaoqi.tooth = {xiaoqi.tooth}') # 实例属性屏蔽类属性, 是新创建的属性
print(f'wangcai.tooth = {wangcai.tooth}') # 修改一个实例属性, 其他实例属性不变
| false |
7ae4b8e3485df6a76e0fbd3a931c119e698e04f0 | Palmerlxp/lxf_learn | /s2.py | 562 | 4.125 | 4 | height=input('身高:')
weight=input('体重:')
h=float(height)
w=float(weight)
bmi=w/(h*h) #bmi=w/h**2 另一种平方的写法
if bmi<18.5:
print('过轻')
elif bmi>18.5 and bmi<25:
print('正常')
elif bmi>25 and bmi<28:
print('过重')
elif bmi>28 and bmi<32:
print('肥胖')
else:
print('严重肥胖')
#other way
height=1.75
weight=80.5
BMI=weight/height/height
if BMI<18.5:
print('过轻')
elif BMI<25:
print('正常')
elif BMI<28:
print('过重')
elif BMI<32:
print('肥胖')
else:
print('严重肥胖')
| false |
7b9277b29346c58baf1e8c15068bb2894ab4043d | mohit-singh4180/python | /datatypes/Dictionary.py | 1,085 | 4.59375 | 5 | #Dictionary holds key:value pair.
# Creating an empty Dictionary
Dict = {}
Dict1={"Name": "Mohit", "EMPID":122333, "test_values":[1,2,3,4,5,6,7,8,9,10]}
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict3 = dict([(1, 'Name'), (2, 'Age')])
print(Dict)
# Creating a Nested Dictionary
# as shown in the below image
Dict2 = {1: 'Test', 2: 'abc',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Python'}}
#ADD/Update
Dict5={}
Dict5[0]="Name"
Dict5[1]="age"
Dict5[2]="company"
Dict5[3]="Address"
Dict5['Mul_val'] = 2, 3, 4
print(Dict5)
#Update
Dict5[2]="address"
print(Dict5)
#access
print(Dict5[2])
print(Dict5['Mul_val'])
print(Dict5.get(3))
#Nested dictionary
# Creating a Dictionary
Dict6 = {'Dict1': {1: 'Python'},
'Dict2': {'Name': 'Lang'}}
#Accessing nested dictionary
print(Dict6['Dict2']['Name'])
#DEL
del Dict5[2]
print(Dict5)
del Dict6['Dict1'][1]
print(Dict6)
#Using pop() method with index/key
Dict5.pop(3)
print(Dict5)
# Deleting an arbitrary key
# using popitem() function
pop_ele = Dict5.popitem()
print(Dict5)
Dict5.clear()
print(Dict5)
| false |
ce6840467ee5ec0a8cb7748bd7441527b6fad2da | mohit-singh4180/python | /string operations/StringLogical operation.py | 645 | 4.3125 | 4 | stra=''
strb='Singh'
print(repr(stra and strb))
print(repr(stra or strb))
stra='Mohit'
print(repr(stra and strb))
print(repr(strb and stra))
print(repr(stra or strb))
print(repr(not stra))
stra=''
print(repr(not stra))
# A Python program to demonstrate the
# working of the string template
from string import Template
# List Student stores the name and marks of three students
Student = [('Ram',90), ('Ankit',78), ('Bob',92)]
# We are creating a basic structure to print the name and
# marks of the students.
t = Template('Hi $name, you have got $marks marks')
for i in Student:
print (t.substitute(name = i[0], marks = i[1])) | true |
ea291fcdc704b8133b4b0ef66f3883c251776399 | gonegitdone/MITx-6.00.2x | /Week 5 - Knapsack and optimization/L9_Problem_2.py | 1,897 | 4.15625 | 4 | # ==============L9 Problem 2 =================
'''
L9 PROBLEM 2 (10 points possible)
Consider our representation of permutations of students in a line from Problem 1. In this case, we will consider a
line of three students, Alice, Bob, and Carol (denoted A, B, and C). Using the Graph class created in the lecture,
we can create a graph with the design chosen in Problem 1. To recap, vertices represent permutations of the students
in line; edges connect two permutations if one can be made into the other by swapping two adjacent students.
We construct our graph by first adding the following nodes:
nodes = []
nodes.append(Node("ABC")) # nodes[0]
nodes.append(Node("ACB")) # nodes[1]
nodes.append(Node("BAC")) # nodes[2]
nodes.append(Node("BCA")) # nodes[3]
nodes.append(Node("CAB")) # nodes[4]
nodes.append(Node("CBA")) # nodes[5]
g = Graph()
for n in nodes:
g.addNode(n)
Add the appropriate edges to the graph.
Hint: How to get started?
Write your code in terms of the nodes list from the code above. For each node, think about what permutation is
allowed. A permutation of a set is a rearrangement of the elements in that set. In this problem, you are only
adding edges between nodes whose permutations are between elements in the set beside each other .
For example, an acceptable permutation (edge) is between "ABC" and "ACB" but not between "ABC" and "CAB".
'''
from graph import *
nodes = []
nodes.append(Node("ABC")) # nodes[0]
nodes.append(Node("ACB")) # nodes[1]
nodes.append(Node("BAC")) # nodes[2]
nodes.append(Node("BCA")) # nodes[3]
nodes.append(Node("CAB")) # nodes[4]
nodes.append(Node("CBA")) # nodes[5]
g = Graph()
for n in nodes:
g.addNode(n)
g.addEdge(Edge(nodes[0], nodes[1]))
g.addEdge(Edge(nodes[0], nodes[2]))
g.addEdge(Edge(nodes[1], nodes[4]))
g.addEdge(Edge(nodes[2], nodes[3]))
g.addEdge(Edge(nodes[3], nodes[5]))
g.addEdge(Edge(nodes[4], nodes[5]))
| true |
38829c600a52bf5e486d20efb568254283f46f36 | patezno/ejercicios-propuestos | /ejercicio06.py | 865 | 4.25 | 4 | # Escribe un programa que pida por teclado dos valores de tipo numérico
# que se han de guardar en sendas variables. ¿Qué instrucciones
# habría que utilizar para intercambiar su contenido? (es necesario utilizar
# una variable auxiliar). Para comprobar que el algoritmo ideado es correcto,
# muestra en pantalla el contenido de las variables una vez leídas, y vuelve
# a mostrar su contenido una vez hayas intercambiado sus valores.
num1 = eval(input("Introduce el primer número entero: "))
num2 = eval(input("Introduce el segundo número entero: "))
auxiliar = num1
print ("El primer número introducido es " + str(num1))
print ("El segundo número introducido es " + str(num2))
num1 = num2
num2 = auxiliar
print ("Al intercambiarse, el primer número es " + str(num1))
print ("Al intercambiarse, el segundo número es " + str(num2))
| false |
a05b26542169a4cb883d87c62baee613856ece9d | CallieCoder/TechDegree_Project-1 | /01_GuessGame.py | 938 | 4.125 | 4 | CORRECT_GUESS = 34
attempts = [1]
print("Hello, welcome to the Guessing Game! \nThe current high score is 250 points.")
while True:
try:
guess = int(input("Guess a number from 1 - 100: "))
except ValueError:
print("Invalid entry. Please enter numbers as integers only.")
else:
if guess < 1 or guess > 100:
print("This number is outside of the specified range. Stay between 1 - 100.")
elif guess < CORRECT_GUESS:
print("Sorry, {} is too low. Try a higher number.".format(guess))
attempts.append(guess)
elif guess > CORRECT_GUESS:
print("Sorry, {} is too high. Try a lower number.".format(guess))
attempts.append(guess)
elif guess == CORRECT_GUESS:
print("That's the correct guess!!")
print("You guessed {} times.".format(len(attempts)))
play_again = input("would you like to play again? (yes/no): ")
if play_again == "no":
break
print("Thanks for playing today. Goodbye!")
| true |
28b749e2ea944bcd4e56112453fd2b9836da0cca | amrfekryy/daysBetweenDates | /daysBetweenDates.py | 1,800 | 4.375 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
def isLeapYear(year):
"""returns True if year is leap. otherwise, False"""
# a leap year is a multiple of 4 (EXCEPT all hundreds BUT including multiples of 400)
if year % 400 == 0:
return True
if year % 100 == 0:
return False
if year % 4 == 0:
return True
else:
return False
def daysInMonth(year,month):
"""returns the number of days in a given month, taking leap years into account"""
if isLeapYear(year) and month == 2:
return 29
daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return daysOfMonths[month - 1]
def nextDay(year,month,day):
"""returns the date of the day next to year-month-day"""
day += 1
if day > daysInMonth(year,month):
day = 1
month += 1
if month > 12:
month = 1
year += 1
return year, month, day
def dateIsBefore(year1,month1,day1,year2,month2,day2):
"""returns True if year1-month1-day1 is before year2-month2-day2. otherwise, False"""
if (year1 < year2) or (year1 == year2 and month1 < month2) or (year1 == year2 and month1 == month2 and day1 < day2):
return True
return False
def daysBetweenDates(year1,month1,day1,year2,month2,day2):
"""returns number of days between two dates"""
# assert date1 is before date2
assert not dateIsBefore(year2,month2,day2,year1,month1,day1)
# assert date1 is valid in the Gregorian calendar
assert not dateIsBefore(year1,month1,day1,1582,10,15)
days = 0
while dateIsBefore(year1,month1,day1,year2,month2,day2):
days += 1
year1,month1,day1 = nextDay(year1,month1,day1)
return days
| true |
b1545d03a2ae61fa8c7858f14183f60ff9ff4493 | joshp123/Project-Euler | /4.py | 460 | 4.21875 | 4 | def isPalindrome(string):
if string == string[::-1]:
return 1 # string reversed = string
else:
return 0 # not a palindrome
palindromes = []
for num1 in xrange(999, 100, -1):
for num2 in xrange(999, 100, -1):
product = num1 * num2
if isPalindrome(str(product)) == 1:
palindromes.append(product)
print 'The largest palindrome from the product of 2 three digit numbers is: ' + repr(max(palindromes))
| true |
5da058b165afd4f385ade8342eaaa56e00c19e77 | sfvitor/monitoria | /processo_selecao/prova/q1.py | 2,375 | 4.1875 | 4 | # Prova de Monitoria para Fundamentos da Computacao
# Questao #1
# Aluno: Vitor Fernandes
# caso o numero seja triangular, retorna os 3 inteiros positivos
# consecutivos que, multiplicados, sao iguais ao numero informado
# caso contrario, retorna None
def numero_triangular(numero):
# loop percorrendo todos os inteiros, a partir do 3 ate o numero informado
for i in range(3, numero+1):
# verifica se os 3 inteiros i, i-1 e i-2 multiplicados eh igual ao numero informado
if i*(i-1)*(i-2) == numero:
# caso o numero seja triangular, retorna os inteiros que o tornam triangular
return [i-2, i-1, i]
# caso o loop encerre sem retornar nada, o numero nao eh triangular
return None
# pede ao usuario que informe um numero inteiro nao-negativo e retorna o mesmo
def ler_numero():
# bloco try-except para validar se o numero eh inteiro
try:
# pede ao usuario o numero
numero = input('Digite um numero para validar se eh triangular ou nao: ')
# tenta converter o valor digitado em um inteiro
# caso nao seja um valor inteiro, ira lancar uma excecao,
# caindo no bloco except abaixo
inteiro = int(numero)
# o inteiro deve ser nao-negativo
# caso seja negativo, pede novamente ao usuario que digite um valor
# utilizamos recursao para manter o codigo mais limpo
if inteiro < 0:
print('O inteiro deve ser nao-negativo')
return ler_numero()
return inteiro
except:
# bloco de excecao
# caso o valor digitado nao seja um numero inteiro, exibe a mensagem de erro
print('O valor deve ser um numero inteiro nao-negativo')
# pede-se novamente ao usuario que digite um valor, utilizando recursao
return ler_numero()
# le o numero e recupera os fatores que o fazem ser triangular
numero = ler_numero()
fatores = numero_triangular(numero)
if fatores is None:
# caso o numero nao seja triangular, o valor de "fatores" sera "None"
print('O numero', numero, 'nao eh triangular')
else:
# caso o numero seja triangular, a variavel "fatores"
# ira conter os numeros que, multiplicados, sao iguais ao numero informado
print('O numero', numero, 'eh triangular')
print('Seus fatores sao:', fatores, 'pois', fatores[0], '*', fatores[1], '*', fatores[2], '=', numero)
| false |
e805d017fb69438e5cf968288dfd77488a00246f | zjuKeLiu/PythonLearning | /GUI.py | 1,306 | 4.21875 | 4 | import tkinter
import tkinter.messagebox
def main():
flag = True
#change the words on label
def change_label_text():
nonlocal flag
flag = not flag
color, msg = ('red', 'Hello, world!')\
if flag else ('blue', 'Goodbye, world')
label.conflg(text = msg, fg = color)
#quit
def confirm_to_quit():
if tkinter.massageboc.askokcancel('notice', 'are you sure to quit?'):
top.quit()
#create the top window
top = tkinter.Tk()
#set the size of window
top.geometry('240*160')
#set the title of window
top.title('Game')
#create the label and add it to the top window
label = tkinter.Label(top, text = 'Hello, world!', font = 'Arial -32', fg = 'red')
label.pack(expand=1)
#create a container to contain the button
panel = tkinter.Frame(top)
#create a button , attach it to the container, use the parameter of command to attach it to the function
button1 = tkinter.Button(panel, text='change', command=change_label_text)
button1.pack(side='left')
button2 = tkinter.button(panel, text='quit', command=confirm_to_quit)
button2.pack(side='right')
panel.pack(side='bottom')
#start the main loop of issue
tkinter.mainloop()
if __name__ == '__main__':
main()
| true |
1603adb378d36caaba42ea862482e4810f3591b2 | igusia/python-algorithms | /binary_search.py | 452 | 4.125 | 4 | import random
#searching for an item inside a search structure
def binary_search(search, item):
low = 0
high = len(search)-1
while low <= high:
mid = (low + high)//2 #if odd -> returns a lower number
guess = search[mid]
if guess < item:
low = mid+1 #it's not mid, so we don't take it
elif guess > item:
high = mid-1 #as with low
else:
return mid
return None
| true |
cd70df45ab8f7635e3e4d4ae38fed02e8bab4e51 | oluyalireuben/python_workout | /session_one.py | 1,398 | 4.25 | 4 | # getting started
print("Hello, World!")
# syntax
if 5 > 2:
print("Five is greater than two")
# Variables
x = 23
y = 45
print(x + y)
a = "python "
b = "is "
c = "awesome"
print(a + b + c)
u = "I like "
j = "Codding "
k = "with python language"
print(u + j + k)
# python numbers and strings
h = "Welcome to eMobilis College"
s = 2
d = 2.8
y = 3j
print(type(s))
print(type(d))
print(type(y))
# Counting of the characters in a statement
print(len(h))
# To print all the characters on lower case and upper case
print(h.lower())
print(h.upper())
# Working with Operators
peter = 23 + 23
jack = 46
print(jack is peter)
o = ["Ian", "Dylan","Andrew", "Kevin"]
print("Paul" in o)
thistuple = tuple(("apple", "banana", "cherry" ))
print(len(thistuple))
# Conditional statements
zulu = 45
south = 45
if zulu < south:print("zulu is less than south")
elif zulu == south:
print("zulu and south are equal")
else:print("south is greater than zulu")
# While loops (While loops and for loops)
peter = 1
while peter < 23:
print(peter)
peter +=1
jack < 5
while jack < 5:
jack +=1
print(jack)
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
# for loop
noise_makers = ["Ian","Zeff" , "Paul" , "Peter" , "Reuben" , "Kevin" , "Chairman" , "Temmy"]
for n in noise_makers:
print(n)
# done to print a lis tof decimal numbers
for s in range(4):
print(s)
| true |
090435b9cf27a02233288045250d90f4181f4b9b | Maciejklos71/PythonLearn | /Practice_python/palidrom.py | 635 | 4.4375 | 4 | #Ask the user for a string and print out whether this string is a palindrome or not.
# (A palindrome is a string that reads the same forwards and backwards.)
def palidrom(string):
string = string.lower().replace(" ","")
for i in range(0,len(string)):
if string[i]==string[-i-1]:
if i == len(string)-1:
print("This string is palidrom!")
continue
if string[i]!=string[-i-1]:
print("This string isn't palidrom")
exit()
print("This string is palidrom!")
palidro = "a tu mam mamuta".lower().replace(" ","")
palidrom(palidro)
| true |
692d14e3fea32a798eb19731e5d2b214fa40dcdc | robado/automate-the-boring-stuff-with-python | /2. Flow Control/5. If, Else, and Elif Statements.py | 1,216 | 4.1875 | 4 | # if statement
name = 'Alice'
if name == 'Alice':
print('Hi Alice')
print('Done')
# Hi Alice
# Done
# if name is other than Alice than the output will beDone
# else statement
password = 'swordfish'
if password == 'swordfish':
print('Access granted.')
else:
print('Wrong password.')
# If password is swordfish then output is Access granted but if not then the output is Wrong password
name = 'Bob'
age = 3000
if name == 'Alice':
print('Hi Alice')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')
# Unlike you, Alice is not an undead, immortal vampire.
# Truthy and Falsey Values
print('Enter a name.')
name = input()
if name: # better option would be to use name != ''
print('Thank you for entering a name.')
else:
print('You did not enter a name')
# Blank string is falsey all others are truthy
# for int 0 and 0.0 are falsey, all others are truthy
print(bool(0)) # False
print(bool(42)) # True
print(bool('Hello')) # True
print(bool('')) # False
# Resources
# https://automatetheboringstuff.com/chapter2/
# http://pythontutor.com/
| true |
dd109d0231382f4680d93159ac106fe0f9d2e0b0 | scarletgrant/python-programming1 | /p9p1_cumulative_numbers.py | 593 | 4.375 | 4 | '''
PROGRAM
Write a program that prompts the user for a positive integer and uses a
while loop to calculate the sum of the integers up to and including that number.
PSEUDO-CODE
Set and initialize number to zero
Set and initialize total to zero
Prompt user for first positive integer
While number => 0:
total += number
print total
Prompt user for a new positive integer
'''
number = 0
total = 0
number = int(input("Please enter a positive number: "))
while number >= 0:
total += number
print("Total is:", total)
number = int(input("Please enter a positive number: "))
| true |
340b1481b39b4ed272b3bd09ad648f933570e7de | scarletgrant/python-programming1 | /p8p3_multiplication_table_simple.py | 415 | 4.3125 | 4 | '''
PROGRAM p8p3
Write a program that uses a while loop to generate a simple multiplication
table from 0 to 20.
PSEUDO-CODE
initialize i to zero
prompt user for number j that set the table size
while i <= 20:
print(i, " ", i*j)
increment i+=1
print a new line with print()
'''
i = 0
j = int(input("Please enter a number: "))
while i <= 20:
print(i, " ", i*j)
i+=1
print()
| true |
3bfb8410e8a4e2b498ed3387833a74ed905088e3 | scarletgrant/python-programming1 | /p10p1_square_root_exhaustive_enumeration.py | 1,305 | 4.25 | 4 | '''
PROGRAM
Write a program that prompts the user for an integer and performs exhaustive
enumeration to find the integer square root of the number. By “exhaustive enumeration”,
we mean that we start at 0 and succcessively go through the integers, checking whether
the square of the integer is equal to the number entered.
If the number is not a perfect square, the program should print out a
message to that effect. The program should exit when a negative number
is entered.
PSEUDO-CODE
# Prompt user for a positive integer (number) to calculate the square root for
number = int(input("Please enter a (whole) number that you like to calculate the square root for: "))
If number >= 0
Initialize square_root to zero
While square_root ** 2 < number:
square_root += 1
if square_root ** 2 == number:
print("Square root of", number, "is", square_root)
else:
print(number, "is not a perfect square.")
'''
number = int(input("Please enter a (whole) number that you like to calculate the square root for: "))
if number >= 0:
square_root = 0
while square_root ** 2 < number:
square_root += 1
if square_root ** 2 == number:
print("Square root of", number, "is", square_root)
else:
print(number, "is not a perfect square.")
| true |
707e0ea61e1f821b44b7225c5e287a6645a04815 | LucaDev13/hashing_tool | /hashing/hash_text.py | 1,252 | 4.1875 | 4 | from algoritms import sha1_encryption, sha224_encryption, sha256_encryption, sha512_encryption, md5_encryption, \
sha3_224_encryption
print("This program works with hashlib library. It support the following algorithms: \n"
"sha1, sha224, sha256, sha512, md5, sha3_224\n")
print("In order to use this program choose an algorithm from the above list \n"
"and then insert the string to be hashed with the chosen algorithm. \n")
print('When done press q + Enter to stop the program. \n')
while True:
chosen_algorithm = input("Choose the encryption algorithm to be used: \n")
print('\n' + f'Enter string to hash in {chosen_algorithm} algorithm: ' + '\n')
string = input()
if string == "q":
print('See you next time!')
break
else:
if chosen_algorithm == 'sha1':
sha1_encryption(string)
if chosen_algorithm == 'sha224':
sha224_encryption(string)
if chosen_algorithm == 'sha256':
sha256_encryption(string)
if chosen_algorithm == 'sha512':
sha512_encryption(string)
if chosen_algorithm == 'sha3_224':
sha3_224_encryption(string)
if chosen_algorithm == 'md5':
md5_encryption(string)
| true |
97d524a37d3d43918209824c6601eb58d1a0d723 | tripaak/python | /Practice_Files/closestPowerTo2.py | 533 | 4.25 | 4 | # closest power to 2: find number greter than or equal to n whose submission make closest number to power of 2
# input = 3
# output = 5 because 3 + 5 = 8 = 2 power to 3
# 3 --> 3 + 4 --> 7 check if mod with 2 is 0 --> if yes return 4 else --> 3 + 5 --> check 8 % 2 == 0
def closestPowerToTwo(n):
closest_num = n + 1
for i in range(0,n+1):
x = pow(2, i)
if x < closest_num:
continue
else:
closest_num += 1
print(closestPowerToTwo(5)) | false |
47208a23d4ea29f0ad4cf605d0ded3aa4c4ca495 | tripaak/python | /Practice_Files/cube_finder.py | 638 | 4.1875 | 4 | # Execercise
# Define a Function that takes a number
# return a dictionary containing cubes of number from 1 to n
# example
# cube_finder(3)
# {1:1, 2:8, 3:27}
####### First approach
# def cube_finder(input_number):
# dNumb = {}
# for j in range(1,input_number + 1):
# vCube = 1
# for i in range(1,4):
# vCube = vCube * j
# dNumb[j] = vCube
# return dNumb #print(vCube, end=" ")
####### Second approach
def cube_finder(n):
cubes = {}
for i in range(1,n+1):
cubes[i] = i**3 # Without using FOR loop
return cubes
print(cube_finder(10)) | true |
e8f93243c5fdb8b236abf3defd638a338884ca14 | vibhor-shri/Python-Basics | /controlflow/Loops.py | 400 | 4.34375 | 4 | separator = "============================"
print("Loops in python")
print("There are 2 types of loops in python, for loops and while loop")
print(separator)
print()
print()
print("A for loop, is used to iterate over an iterable. An iterable is an object which returns one of it's elements "
"at a time")
cities = ["Delhi", "Mumbai", "Chennai", "Kolkata"]
for city in cities:
print(city)
| true |
87ad826d00f46ec7c95d21c87b3387bb42f60f21 | Uncccle/learning-python1 | /2.注释&输出.py | 546 | 4.21875 | 4 | #python的注释分为两类
#单行和多行
#单行
#
#多行
"""
"""
#dsmfsd
"""
sdkf
"""
#注释解释器是不运行的
#---------------------------------------#
# 打印输出 #
a="啦啦啦啦"
b=22222
c=1.1
#第一种:
print(a)
print(b)
print(c)
#第二种:
print(f'{a}')
print(f'{b}')
print(f'{c}')
#第三种:
print("%s" % a) #当为字符串时,应该用s
print("%d" % b) #当为整型时,应该用d
print("%f" % c) #当为浮点数时,应该用f
| false |
8d271335108f2e82d4cd1bb0643710deba3caaaf | vids2397/vids2397 | /Day 1/exercise4.py | 376 | 4.25 | 4 | n1 = int(input("Enter 1st number: "))
n2 = int(input("Enter 2nd number: "))
n3 = int(input("Enter 3rd number: "))
if n1 > n2 and n1 > n3:
print('%d is the biggest number.' % n1)
elif n2 > n1 and n2 > n3:
print('%d is the biggest number.' % n2)
elif n3 > n2 and n3 > n1:
print('%d is the biggest number.' % n3)
else:
print("Any two of the three numbers are the same.")
| false |
3817df8619e45824b2a425b5e2768bd6d8989b40 | curtisjm/python | /personal/basics/functions.py | 1,210 | 4.46875 | 4 | # declare a function
def my_function():
print("Hello from a function")
# call a function
my_function()
# arbitrary arguments
# if you do not know how many arguments that will be passed into your function,
# add a * before the parameter name in the function definition
# this way the function will receive a tuple of arguments
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
# keyword arguments with key = value syntax
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
# arbitrary keyword arguments
# if you do not know how many keyword arguments that will be passed into your function,
# add two asterisk: ** before the parameter name in the function definition.
# this way the function will receive a dictionary of arguments
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
# default parameter value
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function()
# return values
def my_function(x):
return 5 * x
print(my_function(5))
| true |
7de2665bd9b5d91fab286fd7b09c4172d85363ad | curtisjm/python | /personal/basics/inheritance.py | 1,890 | 4.5625 | 5 | # create a parent class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
# to create a class that inherits the functionality from another class,
# send the parent class as a parameter when creating the child class
class Student(Person):
pass
# use the Student class to create an object,
# and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
# the child's __init__() function overrides the inheritance of the parent's __init__() function:
class Student(Person):
def __init__(self, fname, lname):
x = 1
# add properties etc
# to keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
# super() function will make the child class inherit all the methods and properties from its parent:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
# add a property called graduationyear to the Student class:
self.graduationyear = 2019
# add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
# add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
# if you add a method in the child class with the same name as a function in the parent class,
# the inheritance of the parent method will be overridden. | true |
ea5f66e0cb2fc04de9dfa1b1e7ab64f34698c6ce | Rokuzz/conversion-de-unidades-longitud | /operacions.py | 2,070 | 4.1875 | 4 | def programa():
pregunta_inicial = input("Escriba que operación matematica que usted quiera utilizar: ")
if pregunta_inicial == "+":
sum1 = int(input("Escribe el primer numero que quieras sumar: "))
sum2 = int(input("Ahora escribe el otro numero que quieras sumar: "))
print("La suma de los dos numeros es: ", sum1 + sum2)
final1 = input("Quieres hacer otra operación? ")
if final1 == "Si" or final1 == "si":
programa()
else:
print("Gracias por utilizar mi programa. Adios.")
if pregunta_inicial == "-":
rest1 = int(input("Escribe el primer numero que quieras restar: "))
rest2 = int(input("Ahora escribe el numero por el cual el anterior sera restado: "))
print("La suma de los dos numeros es: ", rest1 - rest2)
final2 = input("Quieres hacer otra operación? ")
if final2 == "Si" or final2 == "si":
programa()
else:
print("Gracias por utilizar mi programa. Adios.")
if pregunta_inicial == "*":
multi1 = int(input("Escribe el primer numero que quieras multiplicar: "))
multi2 = int(input("Ahora escribe el otro numero que quieras multiplicar: "))
print("La suma de los dos numeros es: ", multi1 * multi2)
final3 = input("Quieres hacer otra operación? ")
if final3 == "Si" or final3 == "si":
programa()
else:
print("Gracias por utilizar este programa. Adios.")
if pregunta_inicial == "/":
div1 = int(input("Escribe el numero que quieras dividir: "))
div2 = int(input("Ahora escribe el numero por el cual lo quieres dividir: "))
print("La suma de los dos numeros es: ", div1 / div2)
final4 = input("Quieres hacer otra operación? ")
if final4 == "Si" or final4 == "si":
programa()
else:
print("Gracias por utilizar este programa. Adios.")
| false |
f0c27da11efe0dfda2bc81b296bedfdc64303b2b | chettayyuvanika/Questions | /Easy/Pascals_Triangle_Problem.py | 1,236 | 4.28125 | 4 | # Problem Name is Pascals Triangle PLEASE DO NOT REMOVE THIS LINE.
"""
/*
** The below pattern of numbers are called Pascals Triangle.
**
** Pascals Triangle exhibits the following behaviour:
**
** The first and last numbers of each row in the triangle are 1
** Each number in the triangle is the sum of the two numbers above it.
**
** Example:
** 1
** 1 1
** 1 2 1
** 1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
**
** Please Complete the 'pascal' function below so that given a
** col and a row it will return the value in that positon.
**
** Example, pascal(1,2) should return 2
**
*/
"""
def pascal(col, row):
if col==0 or row==0 or row==col:
return 1
else:
return pascal(col-1,row-1)+pascal(col,row-1)
def doTestPass():
""" Returns 1 if all tests pass. Otherwise returns 0. """
doPass = True
pascalColRowValues={(0,0):1,(1,2):2,(5,6):6,(5,5):1}
for key, val in pascalColRowValues.items():
if pascal(key[0],key[1]) != val:
doPass = False
print("Failed for {} and {} \n", format(key, val))
if doPass:
print("All tests pass\n")
return doPass
if __name__ == "__main__":
doTestPass() | true |
0311c673ba64df27b3acf07c4ade56ebbc823a87 | chettayyuvanika/Questions | /Medium/Best_Average_grade_Problem.py | 1,820 | 4.1875 | 4 | # Problem Name is &&& Best Average Grade &&& PLEASE DO NOT REMOVE THIS LINE.
"""
Instructions:
Given a list of student test scores, find the best average grade. Each student may have more than one test score in the list.
Complete the bestAverageGrade function in the editor below. It has one parameter, scores, which is an array of student test scores. Each element in the array is a two-element array of the form [student name, test score] e.g. [ "Bobby", "87" ]. Test scores may be positive or negative integers.
If you end up with an average grade that is not an integer, you should use a floor function to return the largest integer less than or equal to the average. Return 0 for an empty input.
Example:
Input:
[ [ "Bobby", "87" ],
[ "Charles", "100" ],
[ "Eric", "64" ],
[ "Charles", "22" ] ].
Expected output: 87
Explanation: The average scores are 87, 61, and 64 for Bobby, Charles, and Eric, respectively. 87 is the highest.
"""
""" Find the best average grade. """
def bestAverageGrade(scores):
""" Returns true if the tests pass. Otherwise, returns false """
# TODO: implement more test cases
d=dict()
for i in scores:
if i[0] in d:
d[i[0]].append(int(i[1]))
else:
d[i[0]]=[int(i[1])]
avg=0
for i in d:
avg1=sum(d[i])//len(d[i])
if avg1>avg:
avg=avg1
return avg
def doTestsPass():
""" Returns true if the tests pass. Otherwise, returns false """
# TODO: implement more test cases
tc1 = [ [ "Bobby", "87" ], [ "Charles", "100" ], [ "Eric", "64" ], [ "Charles", "22" ] ];
return bestAverageGrade(tc1)==87
if __name__ == "__main__":
result = doTestsPass()
if result:
print("All tests pass\n");
else:
print("Tests fail\n");
| true |
ec304864d363af08d7245df034c786523674b85d | kornel45/basic_algorithms | /quick_sort.py | 533 | 4.15625 | 4 | #!/usr/bin/python
import random
def quick_sort(lst):
"""Quick sort algorithm implementation"""
if len(lst) < 2:
return lst
pivot = lst[random.randint(0, len(lst) - 1)]
left_list = []
right_list = []
for val in lst:
if val < pivot:
left_list.append(val)
elif val > pivot:
right_list.append(val)
return quick_sort(left_list) + [pivot] + quick_sort(right_list)
if __name__ == '__main__':
ar = [1, 5, 2, 0, 3, 7]
assert sorted(ar) == quick_sort(ar)
| true |
a7faa8c5043ecf8405c113f3ef1b7e21bc690dc9 | TarSen99/python3 | /lab7_3.py | 1,163 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def UI_input_string() -> str:
'''Function input string'''
checkString = input("Enter some string ")
return checkString
def UI_print_result(result: bool):
'''Print result'''
if result:
print("String is correct")
else:
print("String is NOT correct")
def remove_characters(checkString: str) -> str:
'''Remove all characters except brackets'''
brackets = ['(', ')', '{', '}', '[', ']', '<', '>']
for _ in checkString:
if _ not in brackets:
checkString = checkString.replace(_, "")
return checkString
def check_brackets(checkString: str) -> str:
'''check if correct couples of brackets exist'''
print(checkString)
brackets = ['()', '{}', '[]', '<>']
while len(checkString) > 0:
startLen = len(checkString)
for _ in brackets:
if _ in checkString:
checkString = checkString.replace(_, "")
if len(checkString) == 0:
return True
if startLen == len(checkString):
break
return False
UI_print_result(check_brackets(remove_characters(UI_input_string()))) | true |
875bb31378cf1de15998763dc39d985c906bd6d3 | TarSen99/python3 | /lab8_2.py | 758 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
def set_size() -> int:
'''inputs size'''
size = int(input("Enter size of list "))
return size
def print_sorted(currList: list):
'''print sorted list'''
print(currList)
def generate_list(size: int) -> list:
'''generate list'''
currList = [random.randint(1,30) for currList in range(size)]
return currList
def sort_list(currList: list) -> list:
'''sort list'''
for _ in range(len(currList)-1,0,-1):
for i in range(_):
if currList[i]>currList[i+1]:
temp = currList[i]
currList[i] = currList[i+1]
currList[i+1] = temp
return currList
print_sorted(sort_list(generate_list(set_size()))) | true |
a51cbcf803b13929c0737ba36c30c2a189ec650b | TarSen99/python3 | /lab52.py | 552 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
print('Enter 2 dimensions of the door')
width = int(input())
height = int(input())
print('Enter 3 dimensions of the box')
a = int(input())
b = int(input())
c = int(input())
exist = False
if (width > a and height > b) or (width > b and height > a):
exist = True
elif (width > a and height > c) or (width > c and height > a):
exist = True
elif (width > b and height > c) or (width > c and height > b):
exist = True
else:
print('box doesnt exist')
if exist:
print('box exist')
| true |
9a1ddd72238f9b770e0e6754f82a6d1348ab757a | SakiFu/sea-c28-students | /Students/SakiFu/session03/pseudocode.py | 991 | 4.3125 | 4 |
#!/usr/bin/env python
This is the list of donors
donor_dict = {'Andy': [10, 20, 30, 20], 'Brian': [20, 40, 30],
'Daniel': [30, 40,10, 10, 30]}
prompt the user to choose from a menu of 2 actions: 'Send a Thank You' or 'Create a Report'.
If the user chose 'Send a Thank You'
Prompt for a Full Name.
name = raw_input("What is the donor's full name?")
if name is 'list', show the list of the donor names and re-prompt
if name in the list, move on.
if name in the list, add that name to the list.
Prompt for the amount of donation.
amount = raw_input("How much is the donation?")
if amount is not digit, re-prompt.
if amount is digit, add the amount to the list.
Compose an email thanking the donor for their generous donation.
If the user chose 'Create a Report'
Create a report, including Donor Name, total donated, number of donations and average donation amount as values in each row
Print the report and return to the original report.
| true |
ad43d34ca563c60c7987d0a02de482407b558d99 | liberdamj/Cookbook | /python/ShapesProject/shape/circle.py | 948 | 4.1875 | 4 | # Circle Class
import math
class Circle:
# Radius is passed in when constructor called else default is 5
def __init__(self, radius=5):
self.radius = radius
self.circumference = (2 * (math.pi * self.radius))
self.diameter = (radius * 2)
self.area = (math.pi * (radius * radius))
def getRadius(self):
return self.radius
def getDiameter(self):
return self.diameter
def getCircumference(self):
return self.circumference
def getArea(self):
return self.area
if __name__ == '__main__':
print()
print("This is the Circle Class within the shape package.")
print("##################################################")
print("Authored by Malachi Liberda")
print("E-Mail: liberdamj@gmail.com")
print()
print("Creation syntax:")
print("circle.Circle(radius)")
print("Available methods:")
print("getRadius, getDiameter, getCircumference, getArea")
| true |
ff46a43fbb377a07fc38ecf781220c6cf1cad33d | klbinns/project-euler-solutions | /Solutions/Problem09.py | 546 | 4.25 | 4 | from math import floor
'''
Problem 9:
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 = 25 = 5**2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
s = 1000
a = 3
for a in range(3, floor((s-3)/3)):
for b in range(a+1, floor((s-1-a)/2)):
c = s-a-b
if c*c == a*a + b*b:
print(a, b, c)
print ('Product: ' + str(a*b*c)) # 31875000
| true |
cf178e7555cc8328e34236a426827dca48c0d61f | klbinns/project-euler-solutions | /Solutions/Problem19.py | 1,600 | 4.21875 | 4 | '''
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4,
but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
'''
def is_sunday(date):
return date[2] == 1
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def get_days_of_month(month, year):
if month in [4, 6, 9, 11]:
return 30
elif month in [1, 3, 5, 7, 8, 10, 12]:
return 31
else:
return 29 if is_leap_year(year) else 28
def advance_day_of_week(date):
month, year, day_of_week = date
days_to_advance = get_days_of_month(month, year) % 7
if day_of_week + days_to_advance <= 7:
return day_of_week + days_to_advance
else:
return (day_of_week + days_to_advance) - 7
def advance_month_and_year(date):
month, year, day_of_week = date
if(month < 12):
month += 1
else:
month = 1
year += 1
return (month, year)
def advance_date_one_month(date):
day_of_week = advance_day_of_week(date)
month, year = advance_month_and_year(date)
return (month, year, day_of_week)
date = (1, 1901, 1)
sunday_count = 0
while date[1] < 2001:
if is_sunday(date):
sunday_count += 1
date = advance_date_one_month(date)
print(sunday_count)
| false |
00069652dcb1d3adab681230ee43147a97f8b831 | nmasamba/learningPython | /23_list_comprehension.py | 819 | 4.5 | 4 |
"""
Author: Nyasha Masamba
Based on the lessons from Codecademy at https://www.codecademy.com/learn/python
This Python program is an example of Python's expressiveness. Less is more when it
comes to true Pythonic code, and list comprehensions prove that. A list comprehension
is an easy way of automatically creating a list in one line of code. In this example,
we use a list comprehension to create a list, cubes_by_four. The comprehension
should consist of the cubes of the numbers 1 through 10 only if the cube is evenly
divisible by four. Finally, we print that list to the console. Note that in this
case, the cubed number should be evenly divisible by 4, not the original number.
Example output:
[8, 64, 216, 512, 1000]
"""
cubes_by_four = [n**3 for n in range(1,11) if (n**3)%4 == 0]
print cubes_by_four | true |
2c0d1241ef7354776f28dbf02587b1c3ef705942 | nmasamba/learningPython | /22_iteration.py | 1,121 | 4.5 | 4 |
"""
Author: Nyasha Pride Masamba
Based on the lessons from Codecademy at https://www.codecademy.com/learn/python
This Python program shows a way to iterate over tuples, dictionaries and strings.
Python includes a special keyword: in. You can use in very intuitively, like below.
In the example, first we create and iterate through a range, printing out 0 1 2 3 4.
Next, we create a dictionary and iterate through, printing out age 26 name Eric.
Dictionaries have no specific order. Finally, we iterate through the letters of a
string, printing out E r i c.
Example output:
0 1 2 3 4 age 26 name Eric E r i c
"""
for number in range(5):
print number,
d = { "name": "Eric", "age": 26 }
for key in d:
print key, d[key],
for letter in "Eric":
print letter, # note the comma!
#Note that the trailing comma ensures that we keep printing on the same line.
| true |
e88c2d3097b8f1eda62acb39223f4c5e2848a96b | nmasamba/learningPython | /14_anti_vowel.py | 849 | 4.25 | 4 |
"""
Author: Nyasha Pride Masamba
Based on the lessons from Codecademy at https://www.codecademy.com/learn/python
This Python program is an example of modularity, encapsulation and algorithmic thinking.
It is simply a function that takes a string text as input. It will then return that string
without any vowels. Note that it does not count Y as a vowel.
Example input and output:
anti_vowel("Hey You!") should return "Hy Y!"
"""
def anti_vowel(text):
no_vowels = []
for l in text:
if l not in "aeiouAEIOU":
no_vowels.append(l)
return "".join(no_vowels) | true |
c1e5a23c822dc77349e3ffd91817d59e71dd62f8 | nmasamba/learningPython | /20_remove_duplicates.py | 589 | 4.25 | 4 |
"""
Author: Nyasha Pride Masamba
Based on the lessons from Codecademy at https://www.codecademy.com/learn/python
This Python program is an example of modularity, encapsulation and algorithmic thinking.
It is simply a function that takes in a list of integers. It will then remove elements
of the list that are the same.
Example input and output:
remove_duplicates([1,1,2,2]) should return [1,2].
"""
def remove_duplicates(numbers):
unduplicated = []
for num in numbers:
if num not in unduplicated:
unduplicated.append(num)
return unduplicated
| true |
2f7babc6a8534a696d89cbb073d307f9b7eef0fb | amitagrahari2512/PythonBasics | /Sorting/BubbleSort.py | 282 | 4.28125 | 4 | def bubbleSort(list):
for i in range(len(list)-1,0,-1):
for j in range(i):
if(list[j] > list[j+1]):
list[j],list[j+1] = list[j+1],list[j]
list = [2,1,3,89,43,90,66]
print("Unsorted List : ",list)
bubbleSort(list)
print("Sorted List : ",list) | false |
46d1f70fb0f3f02d4b4c89c091dd669a6126644b | amitagrahari2512/PythonBasics | /ForLoopBasics.py | 675 | 4.40625 | 4 | print("Iterate List")
x = [2, 4, 'Amit']
for i in x:
print(i)
print("Iterate String")
x = 'Amit'
for i in x:
print(i)
print("Initialize List direct in for loop iteration")
for i in [2,4 , 'PPPP'] :
print(i)
print("Initialize String direct in for loop iteration")
for i in 'Amit':
print(i)
print("We can use range also in for loop")
print("range(endNo(exclusive))")
print("range(startNo,endNo(exclusive),gap)")
print("range(10)")
for i in range(10):
print(i)
print("range(11,21,1)")
for i in range(11,21,1):
print(i)
print("range(11,21,2)")
for i in range(11,21,2):
print(i)
print("range(20,10,-1)")
for i in range(20,10,-1):
print(i)
| false |
248a46e01c23a9a818ca88afc3e78b0f9e85269b | amitagrahari2512/PythonBasics | /Numpy_Array_ShallowAndDeepCopy.py | 1,376 | 4.21875 | 4 | from numpy import *
print("Copy of array")
arr1 = array([1,2,3,4,5])
arr2 = arr1
print(arr1)
print(arr2)
print("Both address is same")
print(id(arr1))
print(id(arr2))
print("------------------------------Shallow Copy------------------------------------------------")
print("So we can use view() method , so it will gives new address, But this is shallow Copy")
arr1 = array([1,2,3,4,5])
arr2 = arr1.view()
print(arr1)
print(arr2)
print("Both address is different")
print(id(arr1))
print(id(arr2))
print("But this is a shallow copy, means if I change any value in arr1 it will reflect to arr2 as well")
arr1[1] = 100
print(arr1)
print(arr2)
print("------------------------------------------------------------------------------")
print("------------------------------Deep Copy------------------------------------------------")
print("So if we don't want this , we need to use copy() function, so it will create deep copy of array")
print("so in this time actual array and copy Array are not interlinked")
arr1 = array([1,2,3,4,5])
arr2 = arr1.copy()
print(arr1)
print(arr2)
print("Both address is different")
print(id(arr1))
print(id(arr2))
print("But this is a deep copy, means if I change any value in arr1 it will not reflect to arr2")
arr1[1] = 100
print(arr1)
print(arr2)
print("------------------------------------------------------------------------------")
| true |
c388cc4fb91fd3b4e4d568f9b8dcfebdffc9319e | ryanhake/python_fundamentals | /02_basic_datatypes/2_strings/02_09_vowel.py | 533 | 4.3125 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
def isvowel(c):
return (c == "a") or (c == "e") or (c == "i") or (c == "o") or (c == "u")
input_string = input("Enter sentence: ")
vowel_count = 0
for ch in input_string:
if isvowel(ch):
vowel_count +=1
print("Total vowel count : {}".format(vowel_count)) | true |
16d8884b52f368d613c1c75b7965f116678001ae | ryanhake/python_fundamentals | /10_testing/10_02_tdd.py | 1,171 | 4.375 | 4 | '''
Write a script that demonstrates TDD. Using pseudocode, plan out a couple simple functions. They could be
as simple as add and subtract or more complex such as functions that read and write to files.
Instead of writing out the functions, only provide the tests. Think about how the functions might
fail and write tests that will check and prevent failure.
You do not need to implement the actual functions after writing the tests but you may.
'''
import unittest
class TDDExample(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_calc_add_method(self):
calc = Calculator()
result = calc.add(2, 2)
self.assertEqual(result, 4)
def test_calculator_returns_error_message_if_both_args_not_numbers(self):
self.assertRaises(ValueError, self.calc.add, 'two', 'three')
def test_calculator_returns_error_message_if_x_arg_not_number(self):
self.assertRaises(ValueError, self.calc.add, 'two', 3)
def test_calculator_returns_error_message_if_y_arg_not_number(self):
self.assertRaises(ValueError, self.calc.add, 2, 'three')
if __name__ == '__main__':
unittest.main()
| true |
4c0960015e4ebfe69e5e06a30c0c0c0223f7979d | DesireeMcElroy/hacker_rank_challenges | /python_exercises.py | 2,383 | 4.21875 | 4 | # Python exercises
# If-Else
# Task
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
# Input Format
# A single line containing a positive integer, .
# Constraints
# Output Format
# Print Weird if the number is weird. Otherwise, print Not Weird.
def check_number(n):
if n > 0 and n < 101:
if n % 2 == 1:
print('Weird')
elif n % 2 == 0 and n in range(2, 6):
print('Not Weird')
elif n % 2 == 0 and n in range(6, 21):
print('Weird')
elif n % 2 == 0 and n > 20:
print('Not Weird')
else:
print("Invalid")
check_number(4)
# Loops
# Task
# The provided code stub reads and integer, , from STDIN. For all non-negative integers , print .
# Constraints
# 0 <= n <= 20
n = int(input())
for i in range(0, n):
if i > -1 and i < 21:
print(i**2)
# Division
# Task
# The provided code stub reads two integers, and , from STDIN.
# Add logic to print two lines. The first line should contain the
# result of integer division, // . The second line should contain
# the result of float division, / .
a = int(input())
b = int(input())
print(a//b)
print(a/b)
# outputs
# 0
# 0.6
# Arithmetic Operators
# Task
# The provided code stub reads two integers from STDIN, and . Add code to print three lines where:
# The first line contains the sum of the two numbers.
# The second line contains the difference of the two numbers (first - second).
# The third line contains the product of the two numbers.
# Constraints
# 1 <= a <= 10**10
# 1 <= b <= 10**10
a = int(input("Enter a number between 1 and 10**10: "))
b = int(input("Enter a number between 1 and 10**10: "))
if 1 <= a <= 10**10 and 1 <= b <= 10**10:
print(a+b)
print(a-b)
print(a*b)
# Print Function
# The included code stub will read an integer, , from STDIN.
# Without using any string methods, try to print the following:
# 123.....n
# Note that "" represents the consecutive values in between.
# Constraints
# 1 <= n <= 150
n = int(input("Please enter a number between 1 and 150: "))
if 1 <= n <= 150:
number = range(1,n+1)
print(*number)
| true |
c535f20a9f7bc234840dc7d97db6a8e00b5b7ff3 | Boris-Rusinov/BASICS_MODULE | /Nested Loops/Ex03-Sum_Prime_Non_Prime.py | 858 | 4.1875 | 4 | prime_nums_sum = 0
non_prime_nums_sum = 0
curr_num = 0
no_remainder_divisions = 0
while True:
command = input()
no_remainder_divisions = 0
if command == "stop":
break
else:
curr_num = int(command)
if curr_num == 0:
continue
elif curr_num == 1:
non_prime_nums_sum += curr_num
elif curr_num < 0:
print("Number is negative.")
else:
for curr_divisor in range(1, curr_num + 1):
if curr_num % curr_divisor == 0:
no_remainder_divisions += 1
if no_remainder_divisions == 2:
prime_nums_sum += curr_num
else:
non_prime_nums_sum += curr_num
print(f"Sum of all prime numbers is: {prime_nums_sum}")
print(f"Sum of all non prime numbers is: {non_prime_nums_sum}") | false |
f069c3a13efd9d60c94023a1331701083f9f7b35 | jjeong723/Study_note | /12000026/04/Link.py | 1,276 | 4.1875 | 4 | class Node : # Ʈ ϴ data+
def __init__(self, data, next=None) :
self.data = data
self.next=next
def init() : # Ʈ Ѵ. node 1~node 4
global node1
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.next = node2
node2.next = node3
node3.next = node4
def delete(del_data) : # Ʈ , Ѵ.
global node1
pre_node = node1
next_node = pre_node.next
if pre_node.data == del_data :
node1 = next_node
del pre_node
return
while next_node :
if next_node.data == del_data:
pre_node.next = next_node.next
del next_node
break
pre_node = next_node
next_node = next_node.next
def insert(ins_data) : # Ʈ ߰Ѵ.
global node1
new_node = Node(ins_data)
new_node.next=node1
node1 = new_node
def print_list() : # Ʈ Ѵ.
global node1
node = node1
while node:
print (node.data)
node=node.next
print()
def LinkedList() :
init();
delete(2)
insert("9")
print_list()
LinkedList() # LinkedList ϶.
| false |
f8cd504dd44ff54de0c85010baced9f3b202c051 | prathameshkurunkar7/common-algos-and-problems | /Math and Logic/Prime Number/Prime.py | 378 | 4.21875 | 4 | def isPrime(number):
if number == 1 or number == 0:
return False
limit = (number // 2) + 1
for i in range(2, limit):
if number % i == 0:
return False
return True
if __name__ == "__main__":
number = int(input("Enter a number: "))
print("Entered number is", "a prime." if isPrime(number) == True else "not a prime.") | true |
5f3def601254e9e873f48b1ec47153f6d1abc00e | seige13/SSW-567 | /HW-01/hw_01_chris_boffa.py | 1,044 | 4.3125 | 4 | """
# equilateral triangles have all three sides with the same length
# isosceles triangles have two sides with the same length
# scalene triangles have three sides with different lengths
# right triangles have three sides with lengths, a, b, and c where a2 + b2 = c2
"""
def classify_triangle(side_a, side_b, side_c):
"""
Classifies the triangle based on the sides given
"""
intersection = {side_a, side_b, side_c} & {side_a, side_b, side_c}
is_right_triangle = side_a ** 2 + side_b ** 2 == side_c ** 2
triangle_classification = 'Invalid Triangle'
if side_a <= 0 or side_b <= 0 or side_c <= 0:
return triangle_classification
if is_right_triangle:
triangle_classification = 'right'
elif len(intersection) == 1:
triangle_classification = 'equilateral'
elif len(intersection) == 2:
triangle_classification = 'isosceles'
else:
triangle_classification = 'scalene'
return triangle_classification
if __name__ == '__main__':
classify_triangle(3, 3, 1)
| true |
308e92c4dc6f53a773e2e8320463fdb7eb0925b4 | manpreet1994/topgear_python_level2 | /q5.py | 2,347 | 4.5625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 12:16:54 2020
@author: manpreet
python assignment level 2
Level 2 assignment:
-------------------
program 1:
write a python program using regex or by any other method to check
if the credit card number given is valid or invalid. your python program should read the credit card number from input
A valid credit card number from xyz Bank has the following rules
It must start with 3,4,5
It must contain exactly 16 digits
It must only consist of digits (0-9)
It may have digits in groups of , separated by one hyphen "-"
It must NOT use any other separator like ' ' , '_', etc
It must NOT have 4 or more consecutive repeated digits
Examples:
input:
4253625879615786
output:
valid
input:
5122-2368-7954-3214
output:
valid
input:
42536258796157867
output:
invalid - #17 digits in card number is not allowed
input:
4424444424442444
output:
invalid #Consecutive digits are repeating 4 or more times not allowed
input:
5122-2368-7954 - 3214
output:
invalid: #Separators other than '-' not allowed
program 2:
write a python program to output the following
look and say sequence of numbers. It should print
up to 10 numbers
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
program 3
convert the given roman number in to decimal number.
The syntax of roman number is given below
write the python program using functools
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
example:
input: XL
output: 40
program 4
write a python proram to count the occurences of string two in
string one. your python program should read the strings from input
example:
input:
stringone = "KSCDCDC"
stringtwo = "CDC"
output: 2
program 5
write a python program to reverse the words in a given sentence as given below. your python program should read the sentence from input
example:
input: "python programming is awesome"
output: "awesome is programming python"
"""
def program5(inputstring):
temp_list = inputstring.split(" ")
temp_list = list(reversed(temp_list))
return temp_list
print("write a python program to reverse the words in a given sentence as given below. your python program should read the sentence from input")
print("Enter your string :")
inputstr = input()
print("output = ",program5(inputstr))
| true |
211e3d01f7c4d681e95d270d2d7ba2130f08394a | bkabhilash0/Python-Beginners-Projects | /16_Leap_Year.py | 1,985 | 4.375 | 4 | import sys
print("***********************************Leap Year Finder*******************************************")
print("Enter a Year to check if it is a leap year or Not?")
leap_years = [2004, 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060, 2064, 2068,
2072, 2076, 2080, 2084, 2088, 2092, 2096]
def leap_checker(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"{year} is a Leap Year!!")
return year
else:
print(f"{year} is not a Leap Year!!")
else:
print(f"{year} is a Leap Year!!")
return year
else:
print(f"{year} is not a Leap Year!!")
def leap_checker_range(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return year
else:
return year
while True:
print("Welcome to Leap Year Calculater")
print("1. Check an year for a leap year.")
print("2. Check leap year for a range of years.")
print("3. Exit")
print("Enter you choices:")
choice = int(input(">> "))
if choice == 1:
try:
print("Enter the year to be checked: ")
year = int(input(">> "))
leap_checker(year)
except:
print("Enter a Valid Year!")
elif choice == 2:
try:
x = int(input("Enter the starting range for the year: "))
y = int(input("Enter the ending range for the year: "))
print(f'The list of Leap years in the range {x} to {y} are:')
results = map(leap_checker_range,range(x,y))
final_leap_years = [x for x in list(results) if x]
print(final_leap_years)
except:
print("Enter a Valid Input")
elif choice == 3:
print("Thank You for Using!")
sys.exit()
else:
print("Enter a Valid choice!")
continue
| false |
4b3860beff600e1652754a3d467e8e0814c7b3c2 | peleduri/baby-steps | /baby steps/Learn_py/ex9.py | 361 | 4.3125 | 4 | days = "Mon Tue Wed Thu Fri Sat Sun"
# now we will learn how to drop one line with n
months = "Jan\nFeb\nMar\nApr\nJun\nJul\nAug"
# we will now just gonna print out the days and months
print("Here are the days: ", days)
print("Here are the months:", months)
# we will learn that we can use """" to keep on typing
print("""
We can type as much as we like
""") | false |
191d92772eb8464c5fa2a9e37298ae1911b2c2f2 | cnastoski/Data-Structures | /Hybrid Sort/HybridSort.py | 2,482 | 4.65625 | 5 | def merge_sort(unsorted, threshold, reverse):
"""
Splits a list in half until it cant anymore, then merges them back together in order
:param unsorted: the unsorted list
:param threshold: if the list size is at or below the threshold, switch to insertion sort
:param reverse: sorts the list in descending order if True
:return: A sorted list
"""
size = len(unsorted)
if size < 2:
return unsorted
mid = size // 2
first = unsorted[:mid]
second = unsorted[mid:]
if mid <= threshold:
first = insertion_sort(first, reverse)
second = insertion_sort(second, reverse)
merged = merge(first, second, reverse)
return merged
else:
first = merge_sort(first, threshold, reverse)
second = merge_sort(second, threshold, reverse)
merged = merge(first, second, reverse)
return merged
def merge(first, second, reverse):
"""
non-recursive part of merge_sort. takes two lists and merges them together in the right order
:param first: first part of list
:param second: second part of list
:param reverse: sorts the list in descending order if True
:return: the correctly merged list
"""
temp = [0] * len(first + second)
i = j = 0
if reverse is False:
while i + j < len(temp):
if j == len(second) or (i < len(first) and first[i] < second[j]):
temp[i + j] = first[i]
i += 1
else:
temp[i + j] = second[j]
j += 1
else:
while i + j < len(temp):
if j == len(second) or (i < len(first) and first[i] > second[j]):
temp[i + j] = first[i]
i += 1
else:
temp[i + j] = second[j]
j += 1
return temp
def insertion_sort(unsorted, reverse):
"""
Sorts a list using insertion sort
:param unsorted: the list to sort
:param reverse: true if list is to be sorted backwards
:return: the sorted list
"""
for i in range(1, len(unsorted)):
j = i
if not reverse:
while j > 0 and unsorted[j] <= unsorted[j - 1]:
unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j]
j -= 1
else:
while j > 0 and unsorted[j] >= unsorted[j - 1]:
unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j]
j -= 1
return unsorted
| true |
a83cb5b5cab2973aa697cab221e20aaf3bea570e | ksemele/coffee_machine | /coffee_machine.py | 2,235 | 4.125 | 4 | class CoffeeMachine:
def __init__(self):
self.water = 400
self.milk = 540
self.beans = 120
self.cups = 9
self.money = 550
def status(self):
print("\nThe coffee machine has:")
print(str(self.water) + " of water")
print(str(self.milk) + " of milk")
print(str(self.beans) + " of coffee beans")
print(str(self.cups) + " of disposable cups")
print("$"+str(self.money) + " of money")
def reduce_resources(self, water_, milk_, beans_, cost):
if self.water - water_ < 0:
print("Sorry, not enough water!")
return False
elif self.milk - milk_ < 0:
print("Sorry, not enough milk!")
return False
elif self.beans - beans_ < 0:
print("Sorry, not enough beans!")
return False
elif self.cups - 1 < 0:
print("Sorry, not enough cups!")
return False
else:
self.water -= water_
self.milk -= milk_
self.beans -= beans_
self.cups -= 1
self.money += cost
return True
def buy(self):
order = input("\nWhat do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: \n")
res = False
if order == '1':
res = self.reduce_resources(250, 0, 16, 4)
elif order == '2':
res = self.reduce_resources(350, 75, 20, 7)
elif order == '3':
res = self.reduce_resources(200, 100, 12, 6)
elif order == 'back':
return
if res:
print("I have enough resources, making you a coffee!")
def fill(self):
self.water += int(input("Write how many ml of water do you want to add: \n"))
self.milk += int(input("Write how many ml of milk do you want to add: \n"))
self.beans += int(input("Write how many grams of coffee beans do you want to add: \n"))
self.cups += int(input("Write how many cups do you want to add: \n"))
def take(self):
print("I gave you $" + str(self.money) + '\n')
self.money = 0
def ft_user_input(machine):
while True:
command = input("\nWrite action (buy, fill, take, remaining, exit): \n")
if command == "buy":
machine.buy()
elif command == "fill":
machine.fill()
elif command == "take":
machine.take()
elif command == "remaining":
machine.status()
elif command == "exit":
exit(0)
if __name__ == '__main__': # something like main() in C
machine = CoffeeMachine()
ft_user_input(machine)
| true |
2ca25165a87b7a7360d35e86b519469f9606da1f | Mahiuha/RSA-Factoring-Challenge | /factors | 1,887 | 4.34375 | 4 | #!/usr/bin/python3
"""
Factorize as many numbers as possible into a product of two smaller numbers.
Usage: factors <file>
where <file> is a file containing natural numbers to factor.
One number per line
You can assume that all lines will be valid natural numbers\
greater than 1
You can assume that there will be no empy line, and no space\
before and after the valid number
The file will always end with a new line
Output format: n=p*q
one factorization per line
p and q don’t have to be prime numbers
See example
You can work on the numbers of the file in the order of your choice
Your program should run without any dependency: You will not be ablei\
to install anything on the machine we will run your program on
Time limit: Your program will be killed after 5 seconds\
if it hasn’t finish
Push all your scripts, source code, etc… to your repository
"""
# library to get arguments
import sys
# fn unpack number factorial
def fc():
"""
function fc to search file to convert number and format n=p*q
"""
try:
revfile = sys.argv[1]
with open(revfile) as f:
for revnumber in f:
revnumber = int(revnumber)
if revnumber % 2 == 0:
print("{}={}*{}".format(revnumber, revnumber // 2, 2))
continue
i = 3
while i < revnumber // 2:
if revnumber % i == 0:
print("{}={}*{}".format(revnumber, revnumber // i, i))
break
i = i + 2
if i == (revnumber // 2) + 1:
print("{}={}*{}".format(revnumber, revnumber, 1))
except (IndexError):
pass
# autostart
fc()
| true |
1a7ef6b488b6ce7e7a592d8dbeac6625547ea0fc | rdasxy/programming-autograder | /problems/CS101/0035/solution.py | 350 | 4.21875 | 4 | # Prompt the use to "Enter some numbers: "
# The user should enter a few numbers, separated by spaces, all on one line
# Sort the resulting sequence, then print all the numbers but the first two and the last two,
# one to a line.
seq = raw_input("Enter some numbers: ")
seq = [int(s) for s in seq.split()]
seq.sort()
for s in seq[2:-2]:
print s | true |
f3213933c26dc79928dfb3be5323cec7977b2884 | dasdachs/smart | /08/python/to_lower.py | 384 | 4.28125 | 4 | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
"""Return the input text in lower case."""
import argparse
parser = argparse.ArgumentParser(description='Transforms text to lower case.')
parser.add_argument('text', type=str, nargs="+", help='Text that will be transformed to lower case.')
args = parser.parse_args()
if __name__ == "__main__":
print " ".join(args.text).lower()
| true |
715df80224d4637c68ccf079bf8903df7c50206e | dasdachs/smart | /10/python/game.py | 867 | 4.125 | 4 | def main():
country_capital_dict = {"Slovenia": "Ljubljana", "Croatia": "Zagreb", "Austria": "Vienna"}
while True:
selected_country = country_capital_dict.keys()[0]
guess = raw_input("What is the capital of %s? " % selected_country)
check_guess(guess, selected_country, country_capital_dict)
again = raw_input("Would you like to continue this game? (yes/no) ")
if again == "no":
break
print "END"
print "_________________________"
def check_guess(user_guess, country, cc_dict):
capital = cc_dict[country]
if user_guess == capital:
print "Correct! The capital of %s is indeed %s." % (country, capital)
return True
else:
print "Sorry, you are wrong. The capital of %s is %s." % (country, capital)
return False
if __name__ == "__main__":
main()
| true |
244caeca775b8de42eb502a37da16fed80f23796 | iPedriNNz/Exercicios | /ex022.py | 608 | 4.46875 | 4 | # Exercício Python 022: Crie um programa que leia o nome completo de uma pessoa e mostre:
# - O nome com todas as letras maiúsculas e minúsculas.
# - Quantas letras ao #odo (sem considerar espaços).
# - Quantas letras tem o primeiro nome.
name = str(input('Digite seu nome completo: '))
print('Seu nome com as letras minúsculas ficaria assim : {}'
'\nCom as letras maiúsculas ficaria assim: {}'.format(name.lower(), name.upper()))
print('Ao todo seu nome tem {} letras.'.format(len(name.replace(' ', ''))))
namel = name.split()
print('O seu primeiro nome tem {} letras.'.format(len(namel[0])))
| false |
338e2b7085fa942cabb25a3b273814bf13faa1f7 | iPedriNNz/Exercicios | /ex019.py | 527 | 4.125 | 4 | # Exercício Python 019: Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que
# ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.
from random import choice
student1 = input('Nome do primeiro aluno ')
student2 = input('Nome do segundo aluno ')
student3 = input('Nome do terceiro aluno ')
student4 = input('Nome do quarto aluno ')
lista = [student1, student2, student3, student4]
escolhido = choice(lista)
print('O aluno escolhido foi {}'.format(escolhido))
| false |
ad6fb4595aeadbb1e5fd4c9b2cda5273d0f8df7f | iPedriNNz/Exercicios | /ex036.py | 783 | 4.3125 | 4 | # Exercício Python 036: 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.
home = float(input('Qual o valor da casa: R$ '))
salary = float(input('Qual o seu salário: R$ '))
months = int(input('Em quantos anos você gostaria de pagar ? ')) * 12
portion = home / months
if portion <= (salary / 100) * 30:
print('Para pegar um casa de R$ {} a prestação será de {:.2f} '
'\nEmpréstimo APROVADO!'.format(home, portion))
else:
print('Para pegar um casa de R$ {} a prestação será de {:.2f} '
'\nEmpréstimo NEGADO!'.format(home, portion))
| false |
6ecbbd21bb3a7ff477c7223ae2ea8d2d820d8f7c | magnuskonrad98/max_int | /FORRIT/python_verkefni/byrjendanamskeid/verkefni_day_2/while_verkefni/verkefni__02.py | 217 | 4.21875 | 4 | low = int(input("Enter an integer: "))
high = int(input("Enter a higher integer: "))
while low <= high:
a = low % 2
if a!=0:
print(low)
low=low+2
else:
low=low+1
print("Done!") | false |
f1337838af3d2dafe14302b84ac07870d7409029 | magnuskonrad98/max_int | /FORRIT/timaverkefni/27.08.19/prime_number.py | 341 | 4.15625 | 4 | n = int(input("Input a natural number: ")) # Do not change this line
# Fill in the missing code below
divisor = 2
while divisor < n:
if n % divisor == 0:
prime = False
break
else:
divisor += 1
else:
prime = True
# Do not changes the lines below
if prime:
print("Prime")
else:
print("Not prime") | true |
8fa2839f5c02e9c272f21e437caa8e2ab7f4f2c9 | TedYav/CodingChallenges | /Pramp/python/flatten_dict.py | 1,137 | 4.125 | 4 | """
Time Complexity: O(n) based on number of elements in dictionary
1. allocate empty dictionary to store result = {}
2. for each key in dictionary:
call add_to_output(key,value,result)
add_to_output(prefix,value,result)
- if value is dict:
for each key in dict, call add_to_output(prefix + '.' + key, value[key])
- else:
result[prefix + '.' + key] = value
3. return result
{} ==> {}
{'a': 1} ==> {'a': 1}
Example:
{
'Key1': '1',
'Key2': {
'a' : '2',
'b' : '3',
'c' : {
'd' : '3',
'e' : '1'
}
}
}
Result:
{
'Key1': '1',
'Key2.a': // it works
}
"""
def flatten_dict(input):
if input is None or len(input) == 0: return {}
else:
result = {}
stack = [('',input)]
while stack:
prefix,target = stack.pop()
if isinstance(target, dict): # check this
for key in target:
stack.append((prefix + '.' + key, target[key]))
else:
result[prefix] = target
return result | true |
0d890a36cebce9c9bb058c2cff8a06ab54eb82cc | ozMoreira/Python_Exercises | /CheckPoint1/Tarefa1_Exercicio2.py | 2,146 | 4.21875 | 4 | print("")
print("------------------------------------------------------------------------------------------------------------------")
print("| Este eh o exercicio 02 da Lista de CheckPoint #1, da disciplina de Computational Thinking do Curso de Analise |")
print("| e Desenvolvimento de Sistemas da FIAP - Turma 1TDSR 2021 |")
print("------------------------------------------------------------------------------------------------------------------")
print("\nNeste exemplo iremos somar uma dada quantidade de MESES, a uma Idade/Periodo qualquer, ambos dados pelo usuario")
entrada = int(input("\nInforme um numero qualquer que represente um periodo de ANOS (Ex. 1 ano, 2 anos, 3 anos....) >>> "))
ano = entrada
entrada = int(input("Insira agora uma quantidade de MESES, que nao ultrapasse o periodo de 11 meses >>> "))
mes = entrada
calculaAno = 0
pegaMesRestante = 0
mesAdicional = 0
periodoValido = True
if ano < 0 or mes > 11:
periodoValido = False
else:
print("\n>>> ATENCAO <<< Voce informou o periodo de", ano, "ano e", mes,"meses!")
entrada = int(input("\nQuantos MESES voce quer adicionar ou Subtrair ao periodo informado? (Ex. 13 meses, -27 meses, 53 meses...) >>> "))
mesAdicional = entrada
if mesAdicional > 0:
calculaAno = ano
pegaMesRestante = ((ano * 12)+mes) + mesAdicional
if pegaMesRestante == 12:
calculaAno += int(pegaMesRestante / 12)
pegaMesRestante = 0
elif pegaMesRestante > 12:
calculaAno = int(pegaMesRestante / 12)
pegaMesRestante %= 12
else:
calculaAno = ano
pegaMesRestante = ((ano * 12)+mes) + mesAdicional
if pegaMesRestante == 12:
calculaAno += int(pegaMesRestante / 12)
pegaMesRestante = 0
elif pegaMesRestante > 12:
calculaAno = int(pegaMesRestante / 12)
pegaMesRestante %= 12
if periodoValido == True:
print("\nA nova idade eh de", calculaAno, "ano(s) e ", pegaMesRestante,"mes(es)!")
else:
print("\n\n>>> ATENCAO<<< --- ERRO!!! --- Ano informado foi negativo ou o primeiro período de meses foi superior a 11 meses!") | false |
d65f38aa4d1a9715b7579bd9b6ac02b34bfa82c2 | ozMoreira/Python_Exercises | /CheckPoint1/Tarefa1_Exercicio3.py | 1,111 | 4.125 | 4 | import math
print("")
print("------------------------------------------------------------------------------------------------------------------")
print("| Este é o exercicio 01 da Lista de CheckPoint #1, da disciplina de Computational Thinking do Curso de Analise |")
print("| e Desenvolvimento de Sistemas da FIAP - Turma 1TDSR 2021 |")
print("------------------------------------------------------------------------------------------------------------------")
print("\nNeste exercicio iremos o valor final de uma conta de luz!\n\n")
consumoMensal = int(input("Digite o valor do consumo mensal em kWh: "))
if consumoMensal < 51:
valorConsumo = 14
else:
valorConsumo = 14 + consumoMensal * 0.25
print("\nO valor do consumo é: R$ %.2f" % valorConsumo)
if consumoMensal <= 99:
icms = 0
elif consumoMensal >= 100 and consumoMensal <= 200:
icms = valorConsumo * 13/100
else:
icms = valorConsumo * 33/100
valorFinal = valorConsumo + icms
print("O valor do ICMS é: R$ %.2f" % icms)
print("O total da conta é: R$ %.2f" % valorFinal)
| false |
b600abf744c3dbb8abbaa694f1df0516847b1cab | lucianopereira86/Python-Examples | /examples/error_handling.py | 661 | 4.15625 | 4 | # Division by zero
x = 1
y = 0
try:
print(x/y)
except ZeroDivisionError as e:
print('You must NOT divide by zero!!!')
finally:
print('This is a ZeroDivisionError test')
# Wrong type for parsing
a = 'abc'
try:
print(int(a))
except ValueError as e:
print('Your string cannot to be parsed to int')
finally:
print('This is a ValueError test')
# Validation with Input
try:
b = int(input("Enter a positive integer: "))
if b <= 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
else:
print('Your number is positive!')
finally:
print('This is an Input ValueError test')
| true |
b85fd57a82d8cd32671f1f7c6cfe05659d182cf0 | mydopico/HackerRank-Python | /Introduction/division.py | 539 | 4.1875 | 4 | # Task
# Read two integers and print two lines. The first line should contain integer division, aa//bb. The second line should contain float division, aa/bb.
# You don't need to perform any rounding or formatting operations.
# Input Format
# The first line contains the first integer, aa. The second line contains the second integer, bb.
# Output Format
# Print the two lines as described above.
# Sample Input
# 4
# 3
# sample Output
# 1
# 1.3333333333333333
a = int(raw_input())
b = int(raw_input())
print a/b
print (float(a)/b)
| true |
57ba583649fdb78dfd5afdad714e2b9bd72ea363 | nini564413689/day-3-2-exercise | /main.py | 546 | 4.34375 | 4 | # 🚨 Don't change the code below 👇
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
BMI = round (weight / height ** 2,1)
if BMI < 18.5:
result = "You are underweight."
elif BMI < 25:
result = "You have a normal weight."
elif BMI < 30:
result = "You are slightly overweight."
elif BMI < 35:
result = "You are obese."
else:
result = "You are clinically obese."
print (f" Your BMI is {BMI}, {result}")
| true |
9cd8f10f326504cf9a46d47048fcf3c25d2df827 | chaithra-yenikapati/python-code | /question_08.py | 1,356 | 4.21875 | 4 | __author__ = 'Chaithra'
notes = """
This is to make you familiar with linked list structures usage in python
see the listutils.py module for some helper functions
"""
from listutils import *
#Given sorted list with one sublist reversed,
#find the reversed sublist and correct it
#Ex: 1->2->5->4->6->7
# sort the list as: 1->2->4->5->6->7
def sort_reversed_sublist(head):
if(head==None):
return []
count=0
temp=head
temp1=temp
while temp.next!=None:
if temp.value<temp.next.value:
count=1
temp1=temp
temp=temp.next
else:
temp2=temp
temp=temp.next
temp3=temp.next
temp.next=temp2
temp1.next=temp
temp2.next=temp3
break
if(count==1):
return from_linked_list(head)
else:
return from_linked_list(temp)
#write test cases covering all cases for your solution
def test_sort_reversed_sublist():
assert [1,2,4,5,6,7]==sort_reversed_sublist(to_linked_list([1,2,5,4,6,7]))
assert [1,2,3]==sort_reversed_sublist(to_linked_list([2,1,3]))
assert [2,3]==sort_reversed_sublist(to_linked_list([3,2]))
assert [2]==sort_reversed_sublist(to_linked_list([2]))
assert []==sort_reversed_sublist(to_linked_list([])) | true |
c18b622285056b2305b06fa34624e566826b2f19 | asbabiy/programming-2021-19fpl | /shapes/reuleaux_triangle.py | 1,435 | 4.1875 | 4 | """
Programming for linguists
Implementation of the class ReuleauxTriangle
"""
import math
from shapes.shape import Shape
class ReuleauxTriangle(Shape):
"""
A class for Reuleaux triangles
"""
def __init__(self, uid: int, width: int):
super().__init__(uid)
self.width = width
def get_area(self):
"""
Returns the area of an Reuleaux triangle
:return int: the area of an Reuleaux triangle
"""
area = 0.5 * (math.pi - math.sqrt(3)) * (self.width ** 2)
return area
def get_perimeter(self):
"""
Returns the perimeter of an Reuleaux triangle
:return float: the perimeter of an Reuleaux triangle
"""
perimeter = math.pi * self.width
return perimeter
def get_inscribed_circle_radius(self):
"""
Returns the inscribed circle radius of an Reuleaux triangle
:return float: the inscribed circle radius of an Reuleaux triangle
"""
inscribed_circle_radius = (1 - 1 / math.sqrt(3)) * self.width
return inscribed_circle_radius
def get_circumscribed_circle_radius(self):
"""
Returns the circumscribed circle radius of an Reuleaux triangle
:return float: the circumscribed circle radius of an Reuleaux triangle
"""
circumscribed_circle_radius = self.width / math.sqrt(3)
return circumscribed_circle_radius
| true |
95058a6355a18b7a0ce81c9671e8e102ce194ac0 | bhanugudheniya/Python-Program-Directory | /CWH_Program_Practice_DIR/CH6_ConditionalExpression_PositiveIntegerCheck.py | 229 | 4.28125 | 4 | userInput = int(input("Enter Number: "))
if userInput > 0:
print(userInput, "is a positive integer")
elif userInput < 0:
print(userInput, "is a negative integer")
else:
print("Nor Positive and Nor Negative Integer, it's Zero") | true |
f4eb7877a49cca45074124096ace75dd5e89b72f | bhanugudheniya/Python-Program-Directory | /CWH_Program_Practice_DIR/CH5_DictionaryAndSets_DeclarationAndInitialization.py | 499 | 4.15625 | 4 | student = {
"name" : "bhanu",
"marks" : 99,
"subject" : "CS",
# "marks" : 98 # always print last updated value
}
print(student) # print whole dictionary
print(student["name"]) # print value of key "name"
print(len(student)) # print dictionary length
print(type(student)) # data types
# Access Dictionary
x = student.get("marks") # get by key
print(x)
y = student.keys() # get all keys
print(y)
val = student.values() # print all values
print(val) | true |
a528a47e1d7c6c1c861e9128c43db7a6645ff453 | bhanugudheniya/Python-Program-Directory | /PythonHome/Input/UserInput_JTP.py | 705 | 4.25 | 4 | name = input("Enter name of student : ")
print("Student name is : ", name)
# 'name' is variable which store value are stored by user
# 'input()' is function which is helps to take user input and string are written in this which is as it is show on screen
# ---------------------------------------------------------------------------------------------------------------------------- #
# --> By default the 'input()' function takes the string input but what if we want to take other data types as an input
# --> If we want to take input as an integer number, we need to typecast the input() function an integer
a = int(input("Enter First Number = "))
b = int(input("Enter Second Number = "))
print(a+b) | true |
141b1eafcfbdbd8324b7f5004774ea9c3a2986e8 | gmaldona/Turtles | /runGame.py | 2,561 | 4.21875 | 4 | import turtle
import random
from tkinter import *
import time
### Class for each player object
class Player:
## Starting y coordinate
y = -250
## Initialing variables
def __init__(self, vMin, vMax, color):
self.player = turtle.Turtle()
self.player.showturtle()
self.player.shape('turtle')
self.color = color
self.player.color(self.color)
self.velocity = random.randint(vMin, vMax)
self.player.penup()
self.player.setheading(90)
self.player.sety(self.y)
## Function that starts moving the turtle
def start(self):
self.player.pendown()
self.player.forward(self.velocity)
## Class that holds all of the player objects
class Race:
turtle.Screen().bgcolor('#498000')
## Array that holds all of the player objects
turtles = []
## Color for each turtle
colors = ['blue', 'red', 'orange', 'pink', 'black', 'purple', 'cyan', 'yellow']
## Function that adds turtles to the array
def addTurtle(self, amount):
## Initializes players for each turtle given in the parameters
for x in range(0, amount):
## Creates a player with a given velocity
t = Player(0, 10, self.colors[x])
## Appends the turtle to the array
self.turtles.append(t)
## Sets up the race
def setup(self):
currentX = -350
maxX = 350
## Spacing between each of the turtles
spacing = 700 / (len(self.turtles) - 1)
## Each turtle gets their x coordinate set to the current x position and the spacing
for t in self.turtles:
t.player.setx(currentX)
currentX = currentX + spacing
## Function that starts the race
def start(self):
## Variable that is responsible for stopping the race
won = False
## color of the turtle that won
color = ''
## Moves the turtle until a color won
while won != True:
## Loops through each turtle
for t in self.turtles:
## Moves the turtle
t.start()
## If a turtle crossed the finish line
if t.player.ycor() >= 250:
## There is a winnter
won = True
color = t.color
time.sleep(2)
def run(numberOfTurtles):
race = Race()
race.addTurtle(numberOfTurtles)
race.setup()
race.start()
run(8) | true |
0aa3a7fddbe66a9fb10a00f251c5bc0519267e19 | Code-Law/Ex | /BYFassess.py | 2,097 | 4.15625 | 4 | def Student():
Student_num = int(input("please input your student number:"))
while Student_num < 4990 or Student_num > 5200:
Student_num = int(input("your student number is out of range, please input again!"))
while Student_num in Student_Numbers:
Student_num = int(input("this student number has already been inputted, please input again!"))
Student_Numbers.append(Student_num)
Subject_Choice()
def Subject_Choice():
global Fundamentals
Fundamentals = 3
Subject_choices = []
subject_1 = input("what's your first subject choice?")
while subject_1 not in Subjects:
subject_1 = input("this is not a choice, please input again:")
Subject_choices.append(subject_1)
subject_2 = input("what's your second subject choice?")
while subject_2 not in Subjects:
subject_2 = input("this is not a choice, please input again:")
while subject_2 == subject_1:
subject_2 = input("this subject has already been inputted, please input again:")
Subject_choices.append(subject_2)
subject_3 = input("what's your third subject choice?")
while subject_3 not in Subjects:
subject_3 = input("this is not a choice, please input again:")
while subject_3 == subject_1 or subject_3 == subject_2:
subject_3 = input("this subject has already been inputted, please input again:")
Subject_choices.append(subject_3)
if "Geography" in Subject_choices:
Fundamentals = Fundamentals - 1
if "History" in Subject_choices:
Fundamentals = Fundamentals - 1
if "Economics" in Subject_choices:
Fundamentals = Fundamentals - 1
Foundamental_num = Fundamentals
Subject_choice = Subject_choices
print(Foundamental_num + 1)
print("you have chosen %0d fundamental subjects" % (Foundamental_num+1))
print(Subject_choice)
Student_Numbers = []
Subject_choice = []
Subjects = ["Math", "English", "Geography", "Physics", "Chemistry", "History", "Economics"]
for i in range(210):
Student()
# print("your subject choices are:")
# print(Subject_choices)
| true |
43624ddb794cc122bf493cbb055169b042824d1b | michaelmnicholl/reimagined-train | /module_grade_program.py | 555 | 4.21875 | 4 | marks = [0,55,47,67]
lowest = marks[0]
mean = 0
if len(marks) < 3:
print("Fail")
print("Your score is below the threshold and you have failed the course")
exit()
for item in marks:
if item < lowest:
lowest = item
for item in marks:
mean = mean + item
mean = mean - lowest
mean = mean / 3
print(mean)
if mean >=40:
print("You have passed the course")
elif mean >=30 and mean <=39:
print("Resit required")
else:
print("Your score is below the threshold and you have failed the course")
| true |
41e9ae805b19463cf2a5dbdf4cbce27f54d2fdcb | JeanAlmenar/HolaMundo | /controlDeFlujo.py | 819 | 4.28125 | 4 | if 2 < 5:
print("2 es menor que 5")
# a == b
# a < b
# a > b
# a != b
# a <= b
# a >= b
if 2 == 2:
print("2 es igual a 2")
if 2 == 3:
print("2 no es igual a 3, y no se ve")
if 2 > 5:
print("2 no es mayor y no se ve")
if 5 > 2:
print("Este si es mayor y se ve")
if 2 !=2:
print( "es distinto a 2, y no se ve")
if 3 != 2:
print("Este si es distinto y se ve")
if 3 >=2:
print("Este si es Mayor y se ve")
if 3 <=2:
print("Este si es menor y no se ve")
elif 3 >=2:
print("Es porque 3 es mayor que 2 se ve")
else : # se usa cuando todas las if o elif dan falso
print("si todo da false me ejecuto")
if 2 < 5 and 3 > 2:
print("ambas devuelven true")
if 2 < 5 and 3 < 2:
print("no se ven ambas devuelven false")
| false |
1b5f0832809513821db10e2be39737d60209ea5f | braxtonphillips/SDEV140 | /PhillipsBraxtonM02_Ch3Ex12.py | 2,041 | 4.46875 | 4 | #Braxton Phillips
#SDEV 140
#M02 Chapter 3 Exercise 12
#This purpuse of this program is to calculate the amount a discount,
# if any, based on quantity of packages being purchased.
print('Hello, this progam will read user input to determine if a discount is applicable based on order quantity.')
packageQuantity = int(input('Please enter the amount of packages you will be purchasing. \n'))
#I read ahead some in the book. This while loop is used as defensive programming to stop the user from entering
#Non-positive integers.
while packageQuantity <= 0:
print('Error. Please enter a valid number.')
packageQuantity = int(input('Please enter the amount of packages you will be purchasing. \n'))
#Selection strucure used to determine which paclage is approriate based on used input
if packageQuantity < 10:
totalAmount = float(format(packageQuantity * 99, '.2f'))
print('Your total for this order will be $',totalAmount, sep='')
elif packageQuantity < 20:
totalAmount = float(format((packageQuantity * 99)*.9, '.2f')) #chose to multiply by .9 rather than the diff of totalAm from 10% of totalAm
print('For ordering ',packageQuantity,' packages, you have recieved a 10% discount! This brings your total for this order to $', totalAmount, sep='')
elif packageQuantity < 50:
totalAmount = float(format((packageQuantity * 99)*.8, '.2f'))
print('For ordering ',packageQuantity,' packages, you have recieved a 20% discount! This brings your total for this order to $', totalAmount, sep='')
elif packageQuantity < 100:
totalAmount = float(format((packageQuantity * 99)*.7, '.2f'))
print('For ordering ',packageQuantity,' packages, you have recieved a 30% discount! This brings your total for this order to $', totalAmount, sep='')
else:
packageQuantity >= 100
totalAmount = float(format((packageQuantity * 99)*.6, '.2f'))
print('For ordering ',packageQuantity,' packages, you have recieved a 40% discount! This brings your total for this order to $', totalAmount, sep='') | true |
4e31d151c7d8d2246a42e286263ae5af2cd87cb4 | nanihari/regular-expressions | /lower with __.py | 394 | 4.40625 | 4 | #program to find sequences of lowercase letters joined with a underscore.
import re
def lower_with__(text):
patterns="^[a-z]+_[a-z]+$"
if re.search(patterns,text):
return ("found match")
else:
return ("no match")
print(lower_with__("aab_hari"))
print(lower_with__("hari_krishna"))
print(lower_with__("harI_kriShna"))
print(lower_with__("HARI_Kri###na"))
| true |
e15765c217cc41d624aa18e1fb54d7490fde49ff | nanihari/regular-expressions | /replace_space_capital.py | 270 | 4.1875 | 4 | #program to insert spaces between words starting with capital letters.
import re
def replace_spaceC(text):
return re.sub(r"(\w)([A-Z])", r"\1 \2", text)
print(replace_spaceC("HariKrishna"))
print(replace_spaceC("AnAimInTheLifeIsTheOnlyFortuneWorthFinding"))
| true |
809214d38526ab39fa2026b0c05525ae34aaebde | nanihari/regular-expressions | /remove numbers.py | 278 | 4.375 | 4 | ##program to check for a number at the end of a string.
import re
def check_number(string):
search=re.compile(r".*[0-9]$")
if search.match(string):
return True
else:
return False
print(check_number("haari00"))
print(check_number("hari"))
| true |
80bcae00e491919c7f627182755948c19115cedf | nanihari/regular-expressions | /snake to camel convertion.py | 282 | 4.25 | 4 | ##program to convert snake case string to camel case string.
import re
def snake_camel(text):
return ''.join(x.capitalize() or '_' for x in text.split('_'))
print(snake_camel("harikrishna"))
print(snake_camel("hari__KRISHNA"))
print(snake_camel("HARI_krishna!!!@###"))
| false |
50929ea4cbf1a0ca13d4a9054c577055e71bb196 | ar1ndamg/algo_practice | /3.sorting_algos.py | 1,533 | 4.5 | 4 | def insertion_sort(arr: list):
""" Takes an list and sorts it using insertion sort algorithm """
l = len(arr)
#print(f"length: {l}")
for i in range(1, l):
key = arr[i]
j = i-1
while j >= 0:
if key < arr[j]:
# slide the elements what are greater than the key to the right in the sorted array
swap(arr, j, j+1)
j -= 1
return arr
def swap(arr, i, j):
#print(f"swapping: {arr[i]},{arr[j]}")
arr[i], arr[j] = arr[j], arr[i]
def merge_sort(arr: list, start: int, end: int):
""" Takes an list and sorts it using merge sort algorithm """
if end == start:
return [arr[start]]
else:
mid = start + (end - start)//2
left = merge_sort(arr, start, mid)
right = merge_sort(arr, mid+1, end)
sorted_arr = merge(left, right)
return sorted_arr
def merge(left: list, right: list):
i = j = k = 0
l1 = len(left)
l2 = len(right)
arr = [0]*(l1+l2)
while k < l1+l2 and i < l1 and j < l2:
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while(i < l1):
arr[k] = left[i]
i += 1
k += 1
while(j < l2):
arr[k] = right[j]
j += 1
k += 1
return arr
if __name__ == '__main__':
arr = [5, 3, 4, 1, 6, 8, 11, 25, 54, 32, 21, 12]
print(merge_sort(arr, 0, len(arr)-1))
print(insertion_sort(arr))
| true |
0c6e89d23d913a1234d8bcd95de548b6a5bd6a62 | hariprasadraja/python-workspace | /MoshTutorial/basics.py | 2,268 | 4.28125 | 4 | import math
"""
Tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=7729s
"""
course = 'Python learning tutorial'
print(course[0:-3])
print("Another variable: ")
another = course[:]
print(another)
# works only on python > 3.6
# formated_string = (f'this is an another course')
# print(formated_string)
print(len(another))
print(another.upper())
# find and return the location of 'P'
print(another.find('P'))
# replaces 'P' to J
print(another.replace('P', 'J'))
# Math
x = 2.9
print(round(2.9))
print(abs(-2.9)) # always retrun positive value
print(math.ceil(2.9))
is_hot = False
is_cold = True
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It is cold day")
print("wear warm clothes")
else:
print("It is a lovely day")
print("enjoy your day")
price = 1000000
has_good_credit = True
if has_good_credit:
downpayemnt = 0.1 * price
else:
downpayemnt = 0.2 * price
print("the downpayment is $" + str(downpayemnt))
# Logical Operators
has_high_income = False
has_good_credit = True
if has_good_credit and not has_high_income:
print("eligilble for loan")
else:
print("not eligible for loan")
# while loop
secret_number = 9
guest_count = 0
guess_limit = 3
while guest_count < guess_limit:
guess = int(input("Guess:"))
guest_count += 1
if guess == secret_number:
print("You won!")
break
else:
print("You Lost!")
# Data Types
x = 10.0001
y = 2
quo, reminder = divmod(x, y)
print("Quotient", quo)
print("Reminder", reminder)
# Execptin handline
try:
age = int(input('Age:'))
income = 20000
risk = income/age
print(age)
except ValueError:
print("Invalid value")
except ZeroDivisionError:
print("Age cannot be 0")
# Class
class Point:
# constructor
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print("move")
def draw(self):
print("draw")
# Initialize with constructor
point1 = Point(10, 20)
print(point1.x)
print(point1.y)
point1.x = 10
point1.y = 20
print(point1.x)
print(point1.y)
# Inherritance
class Mammal:
def walk(self):
print("walk")
class Dog(Mammal):
pass
class Cat(Mammal):
def walk(self):
print("walk")
| true |
ba785abefc90c1d15878514b9d93be99c7383f4f | Ankush-Chander/euler-project | /9SpecialPythagoreanTriplet.py | 539 | 4.28125 | 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 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
import sys
import os
if len(sys.argv) != 2:
print("Usage: python " + sys.argv[0] + " number")
else:
number = int(sys.argv[1])
# print(number)
for i in range(1,number):
for j in range(1,number-i):
k = number-(i+j)
if i**2 + j**2 == k**2:
print(i,j,k)
print(i*j*k)
break | true |
187d5213a7f6cf3019875728f382186dbdf4d2e1 | fedor9ka/python_basic_07_04_20 | /lesson1/task5.py | 1,451 | 4.15625 | 4 | """Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает
фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.
Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите
численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника."""
debit = int(input('Введите значение выручки: '))
credit = int(input('Введите значение издержек: '))
result = debit - credit
if debit >= credit:
print(f'Прибыль составляет {result}')
profit = result / debit * 100
print(f'Рентабельность {profit}%')
workers = int(input('Введите количество сотрудников: '))
result_worker = result / workers
print(f'Прибыль фирмы в расчете на одного сотрудника составдяет: {result_worker}')
else:
print(f'Убыток {result}') | false |
1df7dca01c15594555d5b19f63c50049229a4b05 | rudrasingh21/Python---Using-Examples | /27. Dict - Given Key Exists in a Dictionary or Not.py | 247 | 4.125 | 4 | # Given Key Exist in a Dictionary or Not
d={'A':1,'B':2,'C':3}
k = input("Enter Key which you want to search:- ")
if k in d.keys():
print("Value is present and value for the Key is:- ", d[k])
else:
print("Key is not present")
| true |
6958f52980d417abfb01324cebe6f4b6cf452eb3 | rudrasingh21/Python---Using-Examples | /11.Count the Number of Digits in a Number.py | 271 | 4.125 | 4 | #Count the Number of Digits in a Number
'''
n=int(input("Enter number: "))
s = len(str(n))
print(s)
'''
n=int(input("Enter number: "))
count = 0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are: ",count)
| true |
26ecc9df30d13fbeabe16387bfcf5dd79b3ee02d | rudrasingh21/Python---Using-Examples | /25. Dict - Add a Key-Value Pair to the Dictionary.py | 278 | 4.25 | 4 | #Add a Key-Value Pair to the Dictionary
n = int(input("Enter number of Element you want in Dictionary:- "))
d = {}
for i in range(1,n+1):
Key = input("Enter Key : ")
Value = input("Enter Value : ")
d.update({Key:Value})
print("Updated Dictonary is: ",d) | true |
f0689ed643caf94fccd0fbe9cec7ddad49d7b43b | Onawa33/IDF-Class | /Python/Exercises1/BMI.py | 211 | 4.21875 | 4 | weight = float(input("Enter weight in pounds: "))
height = float(input("Enter height in inches: "))
kg = weight * .45359237
meters = height * .0254
BMI = kg / (meters**2)
print("Your BMI is: %.2f" %(BMI))
| false |
d063654808224d54d7ee8c41d6019dab24b458ac | arjun-krishna1/leetcode-grind | /mergeIntervals.py | 2,766 | 4.34375 | 4 | '''
GIVEN
INPUT
intervals: intervals[i] = [start of i'th interval, end of i'th interval]
merge all overlapping intervals
OUTPUT
return an array of the non-overlapping intervals that cover all the intervals in the input
EXAMPLE
1:
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
already sorted
the end of intervals[0] is after the start of intervals[1] and before the end of intervals[1], these two can be merged
the lowest start time is 1, the highest end time is 6
so [1, 3] and [2, 6] can be merged to [1, 6]
intervals = [[1, 6], [8, 10], [15, 18]]
all of the end times of the rest intervals are before the start times of the next interval
6 < 8, 10 < 15
it is done
return [[1, 6], [8, 10], [15, 18]]
2:
already sorted
[[1, 4], [4, 5]] -> [1, 5]
intervals[0][1] >= intervals[1][0]: they are overlapping
erge them -> [[1, 5]]
BRUTE FORCE
while we haven't considered all of the intervals left
find each other interval whose start time is before this ones end time
and its end time is after this end time
i.e. they are overlapping
find the smallest start time out of all of these overlapping interval
find the largest end time out of all of these overlapping intervals
replace all of these overlapping interval with the smallest start time and the largest end time
move to the next interval
return intervals
SORTING O(n**2) time (single iteration, popping non-end element from list) O(1) space
sort intervals
while we have intervals left to consider
if the next intervals start time is before this ones end time
merge these two
else
move to the next one
return intervals
OPTIMIZATION
push result into another list -> O(n) time, O(n) space
'''
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
# sort intervals
intervals.sort()
result = []
start_time = intervals[0][0]
end_time = intervals[0][1]
# iterate through each interval
for i in range(len(intervals)):
# this interval is overlapping with the previous interval
if end_time >= intervals[i][0]:
end_time = max(end_time, intervals[i][1])
# not merged
else:
# add the previous merged interval to result
result.append([start_time, end_time])
# update start and end time of this interval
start_time = intervals[i][0]
end_time = intervals[i][1]
# add the last interval
result.append([start_time, end_time])
return result
| true |
826a3993e35aece4c19e88969dd44439fc86b969 | ericdasse28/graph-algorithms-implementation | /depth-first-search.py | 1,334 | 4.3125 | 4 | """
Python3 program to print DFS traversal
from a given graph
"""
from collections import defaultdict
# This class represents a directed graph using
# adjacency list representation
class Graph:
def __init__(self):
# Default dictionary to store graph
self.graph = defaultdict(list)
def add_edge(self, u, v):
"""Function to add an edge"""
self.graph[u].append(v)
def dfs_util(self, v, visited):
"""A function used by DFS"""
# Mark the current node as visited
# and print it
visited.add(v)
print(v, end=" ")
# Recur for all the vertices
# adjacent to this vertex
for neighbor in self.graph[v]:
if neighbor not in visited:
self.dfs_util(neighbor, visited)
def dfs(self, v):
"""The function to do DFS traversal. It uses
recursive dfs_util()"""
# Create a set to store visited vertices
visited = set()
# Call the recursive helper function
# to print DFS traversal
self.dfs_util(v, visited)
# Driver code
# Create a graph given
# in the above diagram
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.dfs(2)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.