blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d389a579ea1360932b5af127018b9b35e66ecc3b | paluchasz/Python_challenges | /interview_practice_hackerank/Arrays/Minimum_Swaps.py | 2,389 | 4.21875 | 4 | '''Find minimum number of swaps in an array of n elements. The idea is that the min
number of swaps is the sum from 1 to number of cycles of (cycle_size - 1). E.g
for [2,4,5,1,3] we have 2 cycles one between 5 and 3 which is size 2 and requires 1 swap
and one between 2 4 and 1 which is of size 3 and requires 2 swaps. So total swaps of 3.
Reference: https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/ '''
def MinSwaps(arr):
n = len(arr) #e.g for [2,4,5,1,3]
arr_position = list(enumerate(arr)) #[(0, 2), (1, 4), (2, 5), (3, 1), (4, 3)]
arr_position.sort(key = lambda element: element[1]) #[(3, 1), (0, 2), (4, 3), (1, 4), (2, 5)]
#Lambda is a function with no name, e.g double = lambda x: x*2 then double(5) = 10, lambda takes
# x as the argument and returns x*2
#Create an empty list of False.
visited = []
for k in range(len(arr)):
visited.append(False)
ans = 0
for i in range(len(arr)):
if visited[i] or arr_position[i][0] == i:
continue
#continue makes the program ignore the rest of the loop in this iteration
#which is exactly what we want if it element has already been visited or is
#in the correct place. If the arr is already sorted then 2nd assertion is always true!
cycle_size = 0
j = i
while not visited[j]: #ie when visited element is False so not visited yet
visited[j] = True
j = arr_position[j][0] #in our example j is 0 then 3 then 1 and visited[1] is already
#True by then so we stop while loop
cycle_size += 1
if cycle_size > 0:
ans += (cycle_size - 1)
return ans
#Python enumertate() e.g:
#arr = [2,4,5,1,3]
#enumerate_arr = enumerate(arr)
#print(enumerate_arr) # prints <enumerate object at 0x7ff5eb6ac558>
#print(list(enumerate_arr)) # prints [(0, 2), (1, 4), (2, 5), (3, 1), (4, 3)]
#enumerate_arr[i][j] gives the jth element of ith tuple, so enumerate_arr[1][1] = 4
#and enumerate_arr[2][0] = 2 for example
#e.g of Python Sort() function:
#arr2 = [(0, 2), (1, 4), (2, 5), (3, 1), (4, 3)]
#def takeSecond(elem):
# return elem[1]
#arr2.sort(key = takeSecond)
#print(arr2) would give [(3, 1), (0, 2), (4, 3), (1, 4), (2, 5)]
def Main():
arr = [2,4,5,1,3]
result = MinSwaps(arr)
print(result)
Main()
| true |
cba55fed10f53f69c2860cf020507a736827532e | paluchasz/Python_challenges | /interview_practice_hackerank/Warm_up_problems/Counting_Valleys.py | 961 | 4.28125 | 4 | '''This program has a series of Ds and Us, we start at sea level and end at sea level, we
want to find the number of valleys, ie number of times we go below sea level (and back to 0)'''
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
level = 0 #keep account of the level above/below sea level
valleys_count = 0
for i in range(n):
if s[i] == "D":
level -= 1
if s[i] == "U":
level += 1
if level == -1:
if s[i+1] == "U": #if the level is on -1 and the next thing is to go up then we know
valleys_count += 1 #we are leaving the valley and we can add count.
return valleys_count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = countingValleys(n, s)
fptr.write(str(result) + '\n')
fptr.close()
| true |
3608c44ab2d527502b864be1e13af76a126a55f7 | ekaterinaYashkina/simulated_annealing_PMLDL | /Task2/utils.py | 1,659 | 4.15625 | 4 | import math
from geopy.distance import lonlat, distance
"""
Calculates the distance between the two nodes using euclidean formula
neighbours - list of tuples, nodes coordinates
first, second - indices of elements in neighbours list, between which the distance should be computed
"""
def euclidean_dist(first, second, neighbours):
first_c = neighbours[first]
second_c = neighbours[second]
return math.sqrt((first_c[0] - second_c[0]) ** 2 + (first_c[1] - second_c[1]) ** 2)
"""
Calculates the distance between the two nodes with lat lon coordinates. This is done with
geopy lib.
neighbours - list of tuples, nodes coordinates
first, second - indices of elements in neighbours list, between which the distance should be computed
"""
def long_lat_dist(first, second, neighbours):
first_c = neighbours[first]
second_c = neighbours[second]
return distance(lonlat(*first_c), lonlat(*second_c)).kilometers
"""
Calculates the distance among the provided path.
Dots - list of elements that construct the path. Indices of coors
coors - list of tuples, nodes coordinates
dist - which formula to use for distance calculation (now available - 'lonlat' and 'euclidean')
"""
def calculate_path(dots, coors, dist = 'lonlat'):
if dist == 'lonlat':
dist_f = long_lat_dist
elif dist == 'euclidean':
dist_f = euclidean_dist
else:
raise ValueError("Provided distance function is not exist. Please, use lonlat or euclidean")
dist_v = 0
for i in range(len(dots)-1):
dist_v+=dist_f(dots[i], dots[i+1], coors)
dist_v+=dist_f(dots[len(dots)-1], dots[0], coors)
return dist_v | true |
8aa19aece7c856c53348b9f18a895d8a6999f2bc | Lynch08/MyWorkpands | /Code/Labs/LabWk4/isEven.py | 249 | 4.1875 | 4 | # Author: Enda Lynch
# tell the user if they input an odd or even number
number = int(input("Enter an integer:"))
if (number % 2) == 0 :
print ("{} is an even number" . format(number))
else:
print ("{} is not an even number" . format(number))
| true |
38400be20795cf6cbdb634a9e6ad55ee7c719f8d | Lynch08/MyWorkpands | /Code/Labs/LabWk4/guess3.py | 568 | 4.25 | 4 | # generates random number for user to guess
# Author: Enda Lynch
# import random module and set limit between 1 and 100
import random
numberToGuess = random.randint(0,100)
#string for user
guess = int(input("Please guess the number between 1 and 100:"))
##'while' sets loop and 'if' and 'else' give prompts
while guess != numberToGuess:
if guess < numberToGuess:
print ("Too Low")
else:
print ("Too High")
guess = int(input("Please guess again:"))
#display when number is correct
print ("Well done! Yes the number was ", numberToGuess) | true |
2618d88acba70b47d7b374bcd1864ab3eeed50cf | Lynch08/MyWorkpands | /Code/Labs/LabWk3/div.py | 347 | 4.125 | 4 | #Author: Enda Lynch
# Division programme with remainder
#enter values using inputs to devide on integer by another
X = int(input('Enter number: '))
Y = int(input('Divided by: '))
# '//' gives divides the integers and '%' gives the remainder
B = X//Y
C = X%Y
#display work
print("{} divided by {} is equal to {} remainder {} ".format(X, Y, B, C))
| true |
7a2ed190c3d27d635a021014ee974f3873516d16 | tparackal/Test-Code | /test.py | 202 | 4.21875 | 4 | def numType(x):
a = "none"
if x < 0:
a = "negative"
if x > 0:
a = "positive"
if x == 0:
a = "zero"
return a
num = input("Enter a number: ")
result = numType(num)
print("Number is " + result) | false |
a4b94d07c019eba3b5d741dd14ebd0b478b107a5 | CptObviouse-School-Work/SDEV220 | /module3/6.5.py | 354 | 4.21875 | 4 | '''
Jesse Duncan
SDEV 220
Programming Assignment: 6.5
Due June 17, 2018
'''
def displaySortedNumbers(num1, num2, num3):
numbers = [num1, num2, num3]
numbers.sort()
print("The sorted numbers are " + str(numbers[0]), str(numbers[1]), str(numbers[2]))
num1, num2, num3 = eval(input("Enter three numbers: "))
displaySortedNumbers(num1, num2, num3)
| true |
bb90ab5f1e40dee795f826f8831d1c7b9b23555b | CptObviouse-School-Work/SDEV220 | /module2/3.4.py | 216 | 4.1875 | 4 | '''
Jesse Duncan
SDEV 220
Exercise 3.4
Due June 10, 2018
'''
import math
side = eval(input("Enter the side: "))
area = (5 * (side * side)) / (4 * math.tan(math.pi / 5))
print("The area of the pentagon is " + str(area))
| false |
2e225d616432eabeddd4a1913cbc82b7013f7fd2 | CptObviouse-School-Work/SDEV220 | /module2/4.15.py | 1,400 | 4.125 | 4 | '''
Jesse Duncan
SDEV 220
Exercise 4.15 Game: Lottery
Due June 10, 2018
'''
import random
# Generate a lottery number
lottery = random.randint(0, 999)
# Prompt the user to enter a guess
guess = eval(input("Enter your lottery pick (three digits): "))
#Get digits from lottery
removeLastDigit = lottery // 10
firstDigit = removeLastDigit // 10
secondDigit = removeLastDigit % 10
thirdDigit = lottery % 10
# Get digits from guess
removeLastGuessDigit = guess // 10
guessDigit1 = removeLastGuessDigit // 10
guessDigit2 = removeLastGuessDigit % 10
guessDigit3 = guess % 10
print("The lottery number is", lottery)
if guess == lottery:
print("Exact match: you win $10,000")
else:
matches = 0
# place digits into a list
guess = [guessDigit1, guessDigit2, guessDigit3]
lottery = [firstDigit, secondDigit, thirdDigit]
# sort the list to be iterated
lottery.sort()
guess.sort()
# if the lists match then all the digits where the same
if lottery == guess:
print("Match all digits: you win $3,000")
else:
# iterate over the list comparing each value to determine matches
for x in lottery:
for y in guess:
if x == y:
matches += 1
print("match one digit: you win $1,000")
break
# if no matches display sorry message
print("Sorry, no match")
| true |
6b406d1ea76d8a30b1a3dd315eb2656335d1b2fe | Leoads99/Programing-Language---II | /ex1.1.py | 2,605 | 4.1875 | 4 | """
Ex 01 -
Preencha uma lista com 10 números digitados pelo usuário e exiba:
a - O maior número da lista
b - O menor número da lista
c - a média dos números contidos na lista
d - todos os números menores do que a média calculada no item anterior
cont = 0
lista = []
while cont <10:
numeros = int(input('Digite dez números:'))
lista.append(numeros)
cont = cont+1
else:
media = sum(lista)/ len(lista)
print ('o maior número é',(max(lista)))
print ('o menor número é',(min(lista)))
print ('A média dos números é', media)
print (min(lista))
print ('Números menores que a média')
for a in lista:
if a < media:
print(i)
Ex 02 -
Preencha uma lista com 20 números
sorteados aleatóriamente
(utilize a função randint do módulo random para sortear os números).
from random import randint
cont = 0
lista = []
while cont<20:
num = randint(1,500)
lista.append(num)
cont = cont+1
else:
print ('A lista de números gerados é:', lista)
Exercício 03
Preencha uma lista com 10 números sorteados aleatóriamente. A partir desta lista, gere uma lista com os números pares e outra lista com os números ímpares.
Exemplo:
Suponha que a lista com os números sorteados seja: [1, 4, 7, 9, 5, 3, 7, 9, 8, 8].
Para esta lista, o programa deve gerar as seguintes listas:
[4, 8, 8]
[1, 7, 9, 5, 3, 7, 9]
from random import randint
lista = []
for a in range(20):
num = randint(0,100)
lista.append(num)
pares = []
impares = []
for a in lista:
if a % 2 == 0:
pares.append(a)
if a % 2 == 1:
impares.append(a)
print (f'A lista de números pares é {pares}')
print (f'A lista de números ímpares é {impares}')
Exercício 04
Faça um programa que simule um lançamento de dados. O programa deve sortear 10 números aleátorios (de 1 a 6) e armazenar esses números em uma lista.
Na sequência, informe quantas vezes cada número foi sorteado.
Exemplo:
Suponha que a lista com os números sorteados seja: [3, 1, 5, 3, 5, 4, 5, 5, 3, 1].
Para esta lista, o programa deve exibir:
Número 1 foi sorteado 2 vezes
Número 2 foi sorteado 0 vezes
Número 3 foi sorteado 3 vezes
Número 4 foi sorteado 1 vezes
Número 5 foi sorteado 4 vezes
Número 6 foi sorteado 0 vezes
"""
from random import randint
lista_dado = []
cont = 0
while cont<10:
sorteio = randint(1,10)
lista_dado.append(sorteio)
cont = cont+1
for a in lista_dado:
print(f'Número {a} foi sorteado {lista_dado.count(cont)} vezes')
print (lista_dado) | false |
b92050a43e7859e3fa58a04e7e72b5b98982e740 | hibfnv/Python-learning | /func_parm.py | 311 | 4.125 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# Author: Eason
def str(var1,*vartuple):
print var1
for var in vartuple:
print var
print "=" * 20
print "输出定义的变量:"
print "=" * 20
str(10)
print "=" * 20
print "输出所有未定义的变量:"
print "=" * 20
str(20,30,40)
print "=" * 20 | false |
e02be49d885d049f820771a4cd6ee1b3c045453d | lsrichert/LearnPython | /ex3.py | 2,909 | 4.65625 | 5 | # + plus does addition
# - minus does subtraction
# / slash does division
# * asterisk does multiplication
# % percent is the modulus; this is the remainder after dividing one number
# into another i.e. 3 % 2 is 1 because 2 goes into 3 once with 1 left over
# < less-than
# > greater-than
# <= less-than-equal
# >= greater-than-equal
#PEMDAS (Python follows the standard order of operations)
#P Parentheses, then
#E Exponents, then
#MD Multiplication and division, left to right, then
#AS Addition and subtraction, left to right
#Modulus Tip: One way to look at this is "X divided by Y with J remaining"
# For example: "100 divided by 16 with 4 remaining." The result of '%' is the J part,
# or the remaining part.
#Python 2 doesn't calculate exact math unless you use a floating point number.
# For instance, 7/4 results in 1, while 7.0/4.0 results in 1.75
#So, floating points are basically numbers with a decimal. This is required
# in order for Python to calculate fractions and not just whole numbers.
#line below prints a string
print "I will now count my chickens:"
#line below prints the string and then prints answer to the math problem
print "Hens", 25 + 30 / 6
#below line prints the string and then prints the answer to the math problem
print "Roosters", 100 - 25 * 3 % 4
#75 % 4 = 3 (because 4 goes into 75 18 times; and
#4 times 18 = 72, which leaves 3 left over)
#line below prints the string
print "Now I will count the eggs:"
#lines below print the answer to the math problems
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print 3+2+1-5+4%2-1/4+6
print 'NEW with floating numbers'
print 3.0+2.0+1.0-5.0+4.0%2.0-1.0/4.0+6
#the above two lines are the same; spacing doesn't matter
#3+2+1-5+0-0+6
#7
#python 2 calculates 1/4 as 0; in order to obtain the accurate answer of
# .25, you must use floating points (decimals)
#line below prints the question AND then the answer
print "Is it true that 3+2<5-7?"
print "Is it true that 3.0+2.0<5.0-7.0?"
#line below prints the answer to the math problem
print 3+2<5-7
print 3.0+2.0<5.0+7.0
#lines below print the question AND then the answer
print "What is 3+2?", 3+2
print "NEW now with floating points!"
print "What is 3.0+2.0?", 3.0+2.0
print "What is 5-7?", 5-7
print "NEW now with floating points!"
print "What is 5.0-7.0?", 5.0-7.0
#line below prints the string
print "Oh, that's why it's False."
#line below prints the string
print "How about some more."
#line below prints the question AND answer
print "Is it greater?", 5 > -2
print "NEW now with floating points!"
print "Is it greater?", 5.0>-2.0
#line below prints the question AND answer
print "Is it greater or equal?", 5 >= -2
print "NEW now with floating points!"
print "Is it greater or equal?", 5.0>= -2.0
#line below prints the question AND answer
print "Is it less or equal?", 5 <= -2
print "NEW now with floating points!"
print "Is it greater or equal?", 5.0<= -2.0
| true |
a0aff6ea7d696b27594019f2bc9207ef5f875291 | jaindinkar/PoC-1-RiceUniversity-Sols | /Homework1/Q10-sol.py | 2,161 | 4.25 | 4 | class BankAccount:
""" Class definition modeling the behavior of a simple bank account """
def __init__(self, initial_balance):
"""Creates an account with the given balance."""
self.balance = initial_balance
self.fees = 0
def deposit(self, amount):
"""Deposits the amount into the account."""
self.balance += amount
def withdraw(self, amount):
"""
Withdraws the amount from the account. Each withdrawal resulting
in a negative balance also deducts a penalty fee of 5 dollars
from the balance.
"""
if self.balance - amount < 0:
self.fees += 5
amount += 5
self.balance -= amount
def get_balance(self):
"""Returns the current balance in the account."""
return self.balance
def get_fees(self):
"""Returns the total fees ever deducted from the account."""
return self.fees
# my_account = BankAccount(10)
# my_account.withdraw(15)
# my_account.deposit(20)
# print (my_account.get_balance(), my_account.get_fees())
my_account = BankAccount(10)
my_account.withdraw(5)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(20)
my_account.withdraw(5)
my_account.deposit(10)
my_account.deposit(20)
my_account.withdraw(15)
my_account.deposit(30)
my_account.withdraw(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(50)
my_account.deposit(30)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
my_account.deposit(20)
my_account.withdraw(15)
my_account.deposit(10)
my_account.deposit(30)
my_account.withdraw(25)
my_account.withdraw(5)
my_account.deposit(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.deposit(30)
my_account.withdraw(25)
my_account.withdraw(10)
my_account.deposit(20)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
print (my_account.get_balance(), my_account.get_fees()) | true |
36c7857bf6cb4087456e70307643515040ae8352 | phoenix14113/TheaterProject2 | /main.py | 2,029 | 4.3125 | 4 |
import functions
theater = functions.createTheater(False)
NumberOfColumns = len(theater)
NumberOfRows = len(theater[0])
while True:
# print the menu
print("\n\n\n\n")
print("This is the menus.\nEnter the number for the option you would like.\n")
print("1. Print theater layout.")
print("2. Purchase 1 or more seats.")
print("3. Display theater statistics.")
print("4. Reset theater.")
print("5. Quit program.")
# try:
# collect user's decision on what function to use
userChoice = str(input("\n\nWhich option would you like to select? "))
if userChoice == '1':
# displays the layout of the theater
functions.printBoard(NumberOfRows, NumberOfColumns, theater)
continue
elif userChoice == '2':
# allows users to purchase seats
theater = functions.pickMultipleSeats(
NumberOfRows, NumberOfColumns, theater)
continue
elif userChoice == '3':
# displays how many seats have been purchased, how many seats left, and theater revenue
functions.statistics(NumberOfRows, NumberOfColumns, theater)
continue
elif userChoice == '4':
# resets the layout and seats taken in the theater
# makes sure that the user really wants to completely reset the program
print("Do you really want to do this. It will reset the entire theater")
try:
safeGuard = input("Enter '1' if you would like to proceed: ")
if safeGuard == 1:
theater = functions.createTheater(True)
NumberOfColumns = len(theater)
NumberOfRows = len(theater[0])
except:
continue
continue
elif userChoice == '5':
# quits program
print(
"\nThank you for using my program. You will return to where you\nleft off when you come back.")
print
break
else:
print("invalid input 1")
# except(NameError, SyntaxError):
# print("invalid input 2")
| true |
516d0656dc657d042ea1deddc24439531bca95ef | AlexDimitro0v/Gaussian-Distributions-Package | /distributions/example_code.py | 2,751 | 4.15625 | 4 | from distributions.gaussian_distribution import Gaussian
from distributions.binomial_distribution import Binomial
def main_gaussian():
# initialize two gaussian distributions
gaussian_one = Gaussian(25, 3)
gaussian_two = Gaussian(30, 4)
# initialize a third gaussian distribution reading in a data file
gaussian_three = Gaussian()
gaussian_three.read_data_file('../numbers') # calculates the mean and the stdev automatically
# print out the mean and standard deviations
print(f"Mean 1: {gaussian_one.mean}")
print(f"Mean 2: {gaussian_two.mean}")
print(f"Standard Deviation 1: {gaussian_one.stdev}")
print(f"Standard Deviation 2: {gaussian_two.stdev}")
print('-'*25)
print("Gaussian 3:")
print(f"Mean: {gaussian_three.mean}")
print(f"Standard Deviation:{gaussian_three.stdev}")
# plot histogram of gaussian three
gaussian_three.plot_histogram()
gaussian_three.plot_histogram_pdf()
print(f"Gaussian Three probability density function for x=5: {gaussian_three.pdf(5)}")
# add gaussian_one and gaussian_two together
print('-'*25)
print("Adding 2 gaussians:")
print((gaussian_one + gaussian_two).__repr__())
def main_binomial():
# initialize two binomial distributions
binomial_one = Binomial(0.4, 20)
binomial_two = Binomial(0.4, 60)
# initialize a third binomial distribution reading in a data file
binomial_three = Binomial()
binomial_three.read_data_file('../numbers_binomial')
# print out the 3 Binomials
print("Binomial 1:")
print(f"Total number of trials: {binomial_one.n}")
print(f"Probability of an event occurring: {binomial_one.p}")
print(f"Mean: {binomial_one.mean}")
print(f"Standard Deviation: {binomial_one.stdev}")
print('-'*25)
print("Binomial 2:")
print(f"Total number of trials: {binomial_two.n}")
print(f"Probability of an event occurring: {binomial_two.p}")
print(f"Mean: {binomial_two.mean}")
print(f"Standard Deviation: {binomial_two.stdev}")
print('-'*25)
print("Binomial 3:")
binomial_three.replace_stats_with_data()
print(f"Total number of trials: {binomial_three.n}")
print(f"Probability of an event occurring: {binomial_three.p}")
print(f"Mean: {binomial_three.mean}")
print(f"Standard Deviation:{binomial_three.stdev}")
# plot histogram of binomial three
print(f"Binomial three probability density function for x=5: {binomial_three.pdf(5)}")
binomial_three.plot_bar()
binomial_three.plot_bar_pdf()
# add binomial_one and binomial_two together
print('-'*25)
print("Adding 2 binomials:")
print((binomial_one + binomial_two).__repr__())
if __name__ == '__main__':
main_binomial()
| false |
429b4627202ef18b85b7d088f8972f984d4f872a | NelsonJyostna/Array | /Array_12.py | 1,250 | 4.15625 | 4 | #python array Documentation
#https://docs.python.org/3.1/library/array.html
#See these videos
#https://www.youtube.com/watch?v=6a39OjkCN5I
#https://www.youtube.com/watch?v=phRshQSU-xAar
#import array as ar
#from array import *
#h=ar.array('i',[1,6,5,8,9])
#print(h)
from array import *
h=array('i',[1,6,5,8,9])
#print(h.buffer_info())
#print(h.typecode)
#h.reverse()
#print(h)
#append #Add one value at the end
#h.append(12)
#extend #Add more than one value at the end by using SQUARE brackets
#h.extend([16,17,18])
#insert #Add one value at specific vale at particular position.
#h.insert(2,55)
#Remove the variables from an array
h.pop() #Remove the last variable from the array
#print(h)
h.pop(2) #Remove the 2nd element from the array Using Indexing
#print(h)
h.remove(1) #Remove the element which we want to remove
print(h)
#For loop for array
#for i in range(len(h)): #Using len function
# print(h[i])
#for e in h: #We can directly acess array variables from h array
# print(e)
#newarr= array(h.typecode, (a for a in h)) # copy array h into newarr
#for a in newarr:
# print(a) | true |
2b5afb0c23f01c5cd78462e373b86c2985bc0b81 | tarunna01/Prime-number-check | /Prime number check.py | 271 | 4.15625 | 4 | num = int(input("Enter the number to check for prime"))
mod_counter = 0
for i in range(2, num):
if num % i == 0:
mod_counter += 1
if mod_counter != 0:
print("The given number is not a prime number")
else:
print("The given number is a prime number")
| true |
bfd09644dc48fca95bbcb7cc513c6345be15d1b4 | judegarcia30/cvx_python101 | /02_integer_float.py | 910 | 4.40625 | 4 | # Integers are whole numbers
# Floats are decimal numbers
num = 3
num_float = 3.14
print(type(num))
print(type(num_float))
# Arithmetic Operators
# Addition: 3 + 2
# Subtraction: 3 - 2
# Multiplication: 3 * 2
# Division: 3 / 2
# Floor Division: 3 // 2
# Exponent: 3 ** 2
# Modulus: 3 % 2
num_1 = '100'
num_2 = '200'
print(num_1 + num_2)
print(int(num_1) + int(num_2))
# Order of operation by adding parenthesis
print(3 * 2 + 1) # result is 7
print(3 * ( 2 + 1 )) # result is 9
# incrementing a variable
num = 1
num = num + 1
num += 1
# Comparison Operators, result always return a Boolean (True/False) value
# Equal: 3 == 2 False
# Not Equal: 3 != 2 True
# Greater than: 3 > 2 True
# Less than: 3 < 2 False
# Greater or Equal: 3 >= 2 True
# Less or Equal: 3 <= 2 False | true |
0e3f7d61c853088014a4c90cca82f09e08b7fc6a | Aphinith/Python101 | /dataTypes/loops.py | 469 | 4.59375 | 5 | # example of for loop
item_list = [1, 2, 3, 4, 5]
# for item in item_list:
# print(item)
# example of while loop
i = 1
# while i < 5:
# print('This is the value of i: {}'.format(i))
# i = i +
# examples of using range
first_range = list(range(0,10))
# print(first_range)
# for x in range(0,20):
# print('testing x in loop using range: ', x)
# example of list comprehension
x = [1, 2, 3, 4]
y = [num**2 for num in x]
print('Using list comprehension: ', y) | true |
f0ec0a36fef58a10d02dae1cb042a156cc0248b2 | zakaleiliffe/IFB104 | /Week Work/Week 3/IFB104-Lecture03-Demos/01-stars_and_stripes.py | 2,566 | 4.3125 | 4 | #---------------------------------------------------------------------
#
# Star and stripes - Demo of functions and modules
#
# To demonstrate how functions can be used to structure code
# and avoid duplication, this program draws the United States
# flag. The U.S. flag has many duplicated elements -
# the repeated stripes and stars - and would be very
# tedious to draw if we had to do each part separately.
#
# Instead we import a function to draw a single stripe and
# another function to draw a single star, and repeatedly
# "call" these functions to create multiple stars and stripes.
# Import the graphics functions required
from turtle import *
# Import the functions that draw the stars and stripes
from flag_elements import star, stripe
#---------------------------------------------------------------------
# Define some global constants that determine the flag's
# proportions
flag_width = 850
flag_height = 500
stripe_height = 38.45
union_height = 270
union_width = 380
star_size = 32
y_offset = 10 # distance of the star field from the top-left corner
x_offset = 40
x_sep = 60 # separation of the individual stars
y_sep = 52
#---------------------------------------------------------------------
# The "main program" that draws the flag by calling the
# imported functions
# Set up the drawing window
#
setup(flag_width, flag_height)
setworldcoordinates(0, 0, flag_width, flag_height) # make (0, 0) bottom-left
title("This is not a political statement")
bgcolor("white")
penup()
# Draw the seven red stripes
#
goto(0, stripe_height) # top-left of bottom stripe
setheading(90) # point north
stripe_numbers = range(7) # draw seven stripes
for stripe_no in stripe_numbers:
stripe(flag_width, stripe_height, "red")
forward(stripe_height * 2) # go up to next red stripe's position
# Draw the blue "union" in the top left
#
goto(0, flag_height) # top left-hand corner of the flag
stripe(union_width, union_height, "blue")
# Draw the stars (to save time, only 30 of them, in a 6 X 5
# matrix, as the US flag appeared in 1848)
#
goto(0 + x_offset, flag_height - y_offset) # near top left-hand corner of the flag
row_numbers = range(5) # draw five rows of stars
column_numbers = range(6) # draw six stars in each row
for row_no in row_numbers:
for column_no in column_numbers:
star(star_size, "white")
setheading(0) # point east
forward(x_sep)
goto(0 + x_offset, ycor()) # go back to left-hand edge
setheading(270) # point south
forward(y_sep) # move down to next row of stars
# Exit gracefully
hideturtle()
done()
| true |
f2ed50358ac9a0e776a08353f5fcb47e43c33416 | zakaleiliffe/IFB104 | /Week Work/week 10/BUilding IT/Questions/2-alert_print_date.py | 2,393 | 4.59375 | 5 | #---------------------------------------------------------
#
# Alert date printer
#
# The following function accepts three positive
# numbers, expected to denote a day, month and year, and
# prints them as a date in the usual format.
#
# However, this function can be misused by providing
# numbers that don't form a valid date.
#
# Your task is to add assertions to the function which raise
# an AssertionError exception if the given numbers cannot
# be a valid A.D. date, e.g., if the month value is greater
# than 12 or if the year is negative. (To keep the exercise
# simple you don't need to worry about leap years or the
# different number of days in different months, although a
# "real" function along these lines would need to do so.)
# The test cases below show the messages that should be
# returned with an exception violation.
#
#---------------------------------------------------------
# These are the tests your function must pass.
#
"""
---------- "Normal" cases, with expected inputs ----------
Normal case
>>> print_date(9, 12, 2012) # Test 1
9/12/2012
Normal case
>>> print_date(1, 1, 1960) # Test 2
1/1/1960
Normal case
>>> print_date(28, 2, 1950) # Test 3
28/2/1950
-------- "Invalid" cases, with unexpected inputs ---------
Invalid case - impossible month
>>> print_date(13, 0, 2012) # Test 4
Traceback (most recent call last):
AssertionError: Invalid month: 0
Invalid case - impossible A.D. year (but could be B.C.?)
>>> print_date(6, 5, -10) # Test 5
Traceback (most recent call last):
AssertionError: Invalid year: -10
Invalid case - impossible day
>>> print_date(-2, 3, 2001) # Test 6
Traceback (most recent call last):
AssertionError: Invalid day: -2
"""
#---------------------------------------------------------
#
# Make the following function alert its caller to
# invalid parameters by raising an AssertionError
# exception.
#
# A function to print a given date.
#
def print_date(day, month, year):
# Print the date
print str(day) + '/' + str(month) + '/' + str(year)
#---------------------------------------------------------
# This function executes the unit tests above when called.
# To see if your solution passes all the tests, just call
# the function below.
#
def test():
from doctest import testmod, REPORT_ONLY_FIRST_FAILURE
print testmod(verbose = False,
optionflags = REPORT_ONLY_FIRST_FAILURE)
| true |
281669198fd194e77dc2380c416d6ffb32d76c68 | zakaleiliffe/IFB104 | /Week Work/Week 4/Building IT Systems/IFB104-Lecture04-Demos/5-keyboard_input.py | 781 | 4.3125 | 4 | # Keyboard input
#
# This short demo highlights the difference between Python's raw_input
# and input functions. Just run this file and respond to the prompts.
text = raw_input('Enter some alphabetic text: ')
print 'You entered "' + text + '" which is of type', type(text)
print
number = raw_input('Enter a number: ')
print 'You entered "' + number + '" which is of type', type(number)
print
text = input('Enter some alphabetic text IN QUOTES: ')
print 'You entered "' + text + '" which is of type', type(text)
print
number = input('Enter a number (no quotes): ')
print 'You entered', number, 'which is of type', type(number)
# Notice that when we were confident that we had a string value
# (assuming the user is well-behaved) we used the string
# concatentation operator "+".
| true |
4c51cbab748aa26bdab3322a4427a9b097672e6b | zakaleiliffe/IFB104 | /Week Work/WEEK 6/Building IT systems/Week06-Questions/1-line_numbering.py | 1,893 | 4.46875 | 4 | #----------------------------------------------------------------
#
# Line numbering
#
# Define a function which accepts one argument, the name of a
# text file and prints the contents of that file line by line.
# Each line must be preceded by the line number. For instance,
# the file 'joke.txt' will be printed as follows:
#
# 1 A Joke
# 2
# 3 One spring morning - so the story goes - two village tradesmen
# 4 met on the road to work. Said one, noticing that his mate's
# 5 ...
#
# (It appears that our sense of humour has changed a bit in the
# last century!)
#
# Optional: Since the number of digits in the line number changes,
# you can make the output look neater by using Python's "rjust"
# function, or similar, to produce the line numbers in a fixed
# number of spaces.
#
# Note: You should open the file in "Universal mode" so that
# it doesn't matter whether the text lines are terminated with
# Microsoft DOS, Apple or UNIX/Linux newline characters.
#
# Note: When you read a line of text from a file it will have a
# "newline" character at the end. Since Python's "print"
# command usually produces a newline at the end of its output
# this will result in extra blank lines being written. There are
# two ways to solve this:
#
# 1) Remove the newline character '\n' from the end of each line
# before printing; or
# 2) Put a comma at the end of the "print" statement, which tells
# it to print without writing a newline.
#
#----------------------------------------------------------------
#
#### DEVELOP YOUR print_line_numbers FUNCTION HERE
text_in = open('joke.txt', 'U')
number = 0
for line in text_in:
print (number + 1) , line,
text_in.close()
#----------------------------------------------------------------
#
# Some tests - uncomment as needed.
#
#print_line_numbers('joke.txt')
# print_line_numbers('AnimalFarm-Chapter1.txt')
| true |
0ebc0fa0ed1b48382ef36c87f6aab350e3f02636 | zakaleiliffe/IFB104 | /Week Work/week 2/Building IT systems/demo week 2/IFB104-Lecture02-Demos/3-draw_Pacman.py | 1,257 | 4.4375 | 4 | #---------------------------------------------------------------------
#
# Demonstration - Draw Pacman
#
# As an introduction to drawing using Turtle graphics, here we'll
# draw a picture of the pioneering computer games character, Pacman.
# (Why Pacman? Because he's easy to draw!)
#
# Observation: To keep the code short we have "hardwired" all the
# measurements and angles in this program. In general, however,
# this is not good coding practice, because it makes the program
# hard to change, e.g., if we wanted to change the size of the
# drawing.
# Import the Turtle graphics functions
from turtle import *
# Draw a black canvas
setup() # create window
title('Pacman') # put a title on the window
bgcolor('black') # make the background black
# Draw a huge yellow dot for Pacman's head
color('yellow')
dot(250)
# Draw a small black dot for Pacman's eye
penup()
color('black')
setheading(90) # point north
forward(65)
dot(40)
# Draw a black triangle to form Pacman's mouth
home()
setheading(30)
begin_fill() # start the filled-in region
forward(150)
right(120)
forward(150)
right(120)
forward(150)
end_fill() # end the filled-in region
# Finish the drawing
hideturtle() # hide the cursor
done() # release the drawing canvas so it can be closed
| true |
05bd4cd46abc7ac340def95d084dde7f997d65e0 | zakaleiliffe/IFB104 | /Week Work/week 2/Building IT systems/week 2 quetions/Week02-questions/Done/3_random_min_and_max.py | 2,344 | 4.4375 | 4 | #------------------------------------------------------------------------#
#
# Minimum and Maximum Random Numbers
#
# In this week's exercises we are using several pre-defined
# functions, as well as character strings and lists. As a simple
# exercise with lists, here you will implement a small program which
# generates a large collection of random numbers and then finds the
# smallest and largest numbers produced. After a large number of
# trials it should print the smallest and largest random numbers
# generated, e.g.:
#
# Results for 100 trials for random numbers between 1 and 1000
# The smallest number generated was 25
# The largest number generated was 987
#
# The goal is to produce a large collection of random numbers in a
# fixed range and then print the smallest and largest numbers produced.
# To do this you will need to use:
# a) The randint function to generate random numbers
# b) A for-each loop to do an action several times
# c) A list-valued variable which is initially the empty list []
# d) The "+" operator (or the "append" method) to add a value to
# the list. Note that the "+" operator joins two lists, not a
# value and a list. A value can be turned into a singleton list
# just by putting square brackets around it.
#
# Import the random function needed
#moved down
# Define some convenient constant values
#moved down
# Solution strategy:
#
# 1) Create an empty list to hold the random numbers
# 2) Use the built-in "range" function to produce a
# list of numbers, one for each trial
# 3) For each of the trial numbers:
# a) Produce a random number in the fixed range
# b) Add the random number to the end of the list
# of random numbers
# 4) Print the minimum number in the list of random numbers
# 5) Print the maximum number in the list of random numbers
#### PUT YOUR EQUIVALENT PYTHON CODE HERE
from random import randint
number_of_trials = 100
range_of_random_numbers = 1000
random_numbers = []
trial_numbers = range(number_of_trials)
for trial_num in trial_numbers:
random_number = randint (1, range_of_random_numbers)
random_numbers.append(random_number)
print "The maxmum number in the list of random numbers is:", max(random_numbers)
print "The minimum number in the list of randon numbers is:", min(random_numbers)
| true |
1fd51daff7b2075a7371b380abddb323ea3cba72 | zakaleiliffe/IFB104 | /Week Work/Week 3/Week03-questions/DONE/3_stars_and_stripes_reused.py | 1,891 | 4.3125 | 4 | #--------------------------------------------------------------------
#
# Stars and stripes reused
#
# In the lecture demonstration program "stars and stripes" we saw
# how function definitions allowed us to reuse code that drew a
# star and a rectangle (stripe) multiple times to create a copy of
# the United States flag.
#
# As a further example of the way functions allow us to reuse code,
# in this exercise we will import the flag_elements module into
# this program and create a different flag. In the PDF document
# stars_and_stripes_flags you will find several flags which can be
# constructed easily using the "star" and "stripe" functions already
# defined. Choose one of these and try to draw it.
#
# First we import the two functions we need (make sure a copy of file
# flag_elements.py is in the same folder as this one)
from flag_elements import star, stripe
# Import the turtle graphics functions
from turtle import *
#some global constants
flag_width = 400
flag_height = 600
stripe_height = 200 #1/3 of total height
star_size = 100
x_offset = 40
y_offset = 10
star_height = 190
star_colour = "black"
# Set up the drawing environment
setup(600, 400)
setworldcoordinates(0, 0,flag_width, flag_height)#sets home
title ('The Ghana Flag')
bgcolor ("white")
penup()
##### PUT YOUR CODE FOR DRAWING THE FLAG HERE
## Draw the bottom green strip
goto(0, stripe_height)
setheading(90)
stripe_numbers = range(1) #Draw first green bottom stripe
for stripe_no in stripe_numbers:
stripe(flag_width, stripe_height, "dark green")
forward(stripe_height)
for stripe_no in stripe_numbers:
stripe(flag_width, stripe_height, "yellow")
forward(stripe_height)
for stripe_no in stripe_numbers:
stripe(flag_width, stripe_height, "red")
forward(stripe_height)
penup()
goto(200, 400)
pendown()
star(star_height, star_colour)
# Exit gracefully
hideturtle()
done()
| true |
689cb7e9c11aedc04d083eadf29b2a1a5521bf10 | anantkaushik/algoexpert | /Binary-Search.py | 581 | 4.1875 | 4 | """
Problem Link: https://www.algoexpert.io/questions/Binary%20Search
Write a function that takes in a sorted array of integers as well as a target integer. The function should use the Binary Search algorithm
to find if the target number is contained in the array and should return its index if it is, otherwise -1.
"""
def binarySearch(array, target):
# Write your code here.
start, end = 0, len(array)-1
while start <= end:
mid = (start+end)//2
if array[mid] == target:
return mid
elif array[mid] < target:
start = mid + 1
else:
end = mid - 1
return -1 | true |
95b94e2744fae0f5fc3554f57aa514f980bdbd17 | anantkaushik/algoexpert | /Two-Number-Sum.py | 718 | 4.25 | 4 | """
Problem Link: https://www.algoexpert.io/questions/Two%20Number%20Sum
Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum.
If any two numbers in the input array sum up to the target sum, the function should return them in an array, in sorted order.
If no two numbers sum up to the target sum, the function should return an empty array. Assume that there will be at most one
pair of numbers summing up to the target sum.
"""
def twoNumberSum(array, targetSum):
# Write your code here.
temp = set()
for no in array:
diff = targetSum - no
if diff in temp:
return [diff if diff < no else no,no if diff < no else diff]
temp.add(no)
return [] | true |
975c387e56c0e68da27fd859c9908f1169307442 | Freddy875/Python | /Numeros/Numeros.py | 1,531 | 4.59375 | 5 | '''
Existen 3 tipos numeircos en Python
int
float
complex
'''
x =1
y = 2.8
z = 1j
print(type(x))
print(type(y))
print(type(z))
#Enteros
print("Enteros")
'''
Los entrsos son todo numero positivo
o negativo sin decimales
de longitud indefinida
'''
x = 1
y = 123456789
z = -987654321
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
#Flotantes o reales
'''
Numeros con punto flotante
es un numero positivo o negativo
contien uno o mas decimales
'''
print("Flotantes o reales")
x = 1.10
y = 1.0
z = -35.59
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
'''
Los flotantes tambien puede ser expresado
en notación cientifica con la letra "e"
para indicar la potencia de 10
'''
x = 35e3
y = 12e4
z = -87.7e100
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
#Complejos
print("Complejos")
'''
Los complejos son escritos con
la letra "j" para indicar
la parte imaginaria
'''
x = 3+5j
y = 5j
z = -5j
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
#Conversiones
print("Conversiones")
'''
Convertir un tipo de dato a otro
'''
#Convertir de entero a flotante:
x = float(1)
#Convertir de flotante a entero:
y = int(2.8)
#Convertir de entero a complejo
z = complex(x)
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
#Numero random o aleatorio
print("Numero aleatorio del 1 al 10")
import random
print(random.randrange(1,10))
print("Numero aleatorio del 1 al 100")
print(random.randrange(1,100)) | false |
4b3cd2a324ba26d888e2fdf7506cb9250a2508da | Freddy875/Python | /Listas/Acceso_A_Las_Listas.py | 585 | 4.21875 | 4 | #Acceso a la listas
estalista =["manzana","bananas","cereza"]
print(estalista[1])
#Indice negativo
print(estalista[-1])
#Rango de index
estalista =["manzana","bananas","cereza","naranja","kiwi","limon","melon","mango"]
print(estalista[2:5])
print(estalista[:4])
#Esto devuelve los valores del indice 0 al indice 4
print(estalista[2:])
#Esto devuelve los valores del indice 2 al final
print(estalista[-4:-1])
#Indice negativo empieza desde el final de la lista
#Revisar si un elementos existe
if "manzana" in estalista:
print("Si, 'manzana' esta en la lista de frutas")
| false |
f5ba637446b4eab8b78d6529a44764d05a7af847 | Freddy875/Python | /Operadores/OperadoresAritmeticos.py | 541 | 4.125 | 4 | '''
Operadores son usados para desempenio de operaciones con valores y variables
'''
#Operadores artimeticos
x = 5
y = 3
#Suma
print("Suma")
print(x + y)
#Resta
print("Resta")
print(x - y)
#Multiplicacion
print("Multipliacion")
print(x*y)
#Division
x = 12
y = 3
print("Division")
print(x/y)
#Modulos
x = 5
y = 2
print("Modulos")
print(x%y)
#Exponencial
x = 2
y = 5
print("Exponenciales")
print(x ** y)
#Division Floor
#Redondea el resultado al numero entero más cercano
x = 15
y = 2
print("Exponenciales")
print(x // y)
| false |
26777d3a822041c22fb7f861b63766dd18a223dd | Freddy875/Python | /Introduccion/Pilas(conListas).py | 509 | 4.1875 | 4 | #Pilas
#Las pilas pueden emularse con Listas
#Las pilas son una estructura de datos
#de tipo LIFO (Last In-First Out)
pila = [1,2,3]
print(f"La pila inicila {pila}")
#Agregar elementos por el final de la pila
pila.append(4)
pila.append(5)
print(f"La pila despues de agregar dos valores {pila}")
#Sacar elementos de la pila por el final
variableN = pila.pop()
print(f"Sacando el ultimo elemento {variableN} de la pila {pila}")
#El metodo pop ademas de sacar el ultimo elemento tambien lo retorna
| false |
3b94901914ba40d20a29f0b89b2c6e8b42bf2e8a | garimasilewar03/Python_Task | /9.py | 976 | 4.4375 | 4 | '''Write a program such that it asks users to “guess the lucky number”. If the correct number is guessed the program stops, otherwise it
continues forever.
number = input("Guess the lucky number ")
while 1:
print ("That is not the lucky number")
number = input("Guess the lucky number ")
Modify the program so that it asks users whether they want to guess again each time. Use two variables, ‘number’ for the number and ‘answer’
for the answer to the question of whether they want to continue guessing. The program stops if the user guesses the correct number or answers
“no”. ( The program continues as long as a user has not answered “no” and has not guessed the correct number)
'''
number = -1
again = "yes"
while number != 1 and again != "no":
number = input("Guess the lucky number: ")
if number != 1:
print ("That is not the lucky number")
again = input("Would you like to guess again? ")
| true |
5ed47bc2085e9808de61264f362a1d16e8eb78bc | softicer-67/ALGORITMS | /Lesson_7/2.py | 695 | 4.15625 | 4 | '''
2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами
на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
'''
from random import randint
def sort(array):
res = []
new_arr = arr[:]
for _ in range(len(new_arr)):
mini = min(new_arr)
mini_index = new_arr.index(mini)
res.append(mini)
del new_arr[mini_index]
return res
N = 20
arr = []
for i in range(N):
arr.append(randint(0, 50))
print(arr)
print(sort(arr))
| false |
b16fa5b82118b0d71e48b7aaa274e22d65dd0585 | softicer-67/ALGORITMS | /Lesson_1/3.py | 609 | 4.21875 | 4 | """
3. По введенным пользователем координатам двух точек вывести уравнение прямой вида y=kx+b, проходящей через эти точки.
"""
print('Координаты точки A(x1,y1): ')
x1 = int(input('\tx1 = '))
y1 = int(input('\ty1 = '))
print('Координаты точки B(x2,y2): ')
x2 = int(input('\tx2 = '))
y2 = int(input('\ty2 = '))
print('Уравнение прямой, проходящей через эти точки: ')
k = (y1 - y2) / (x1 - x2)
b = y2 - k * x2
print('\ty = %.2f*x + %.2f' % (k, b))
| false |
20c30cbcea1a137a4416ac0fd5eb41056b50b6d9 | margarineHound/sorting-algorithms | /reverse_string.py | 576 | 4.125 | 4 | def reverse_string(word, word_new):
if len(word) > 0:
word_new.append(word[-1])
reverse_string(word[:-1], word_new)
return ''.join(word_new)
def reverse_string_loop(word, word_new):
for i in range(len(word)):
word_new.append(word[-(i+1)])
return ''.join(word_new)
def main():
word = input('enter string: ')
word_new = []
word_new = reverse_string(word, word_new)
print(repr(word_new))
word_new = []
word_new = reverse_string_loop(word, word_new)
print(repr(word_new))
if __name__ == "__main__":
main() | false |
46981ad4de6e8a408302f80921a8290999cc512b | markstali/atividade-terminal-git | /code13.05.py | 2,854 | 4.25 | 4 | #01 - Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações:
# a) tamanho da lista.
# b) maior valor da lista.
# c) menor valor da lista.
# d) soma de todos os elementos da lista.
# e) lista em ordem crescente.
# f) lista em ordem decrescente.
""" L = [5, 7, 2, 9, 4, 1, 3]
print('tamanho da lista',len(L))
print('maior valor da lista.',max(L))
print('menor valor da lista.', min(L))
print('soma de todos os elementos da lista', sum(L))
L.sort()
print('lista em ordem crescente.', L)
L.reverse()
print('lista em ordem decrescente.',L)
"""
#02 - Utilizando listas, faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
# "Telefonou para a vítima?"
# "Esteve no local do crime?"
# "Mora perto da vítima?"
# "Devia para a vítima?"
# "Já trabalhou com a vítima?"
# O programa deve no final emitir uma classificação sobre a participação da pessoa no crime.
# Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita",
# entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente".
""" quest = []
print("Responda 1 para Sim e 0 para Não\n")
quest.append(int(input("Telefonou para a vítima?[1/0]: ")))
quest.append(int(input("Esteve no local do crime?[1/0]: ")))
quest.append(int(input("Mora perto da vítima?[1/0]: ")))
quest.append(int(input("Devia para a vítima?[1/0]: ")))
quest.append(int(input("Já trabalhou com a vítima?[1/0]: ")))
if sum(quest) == 2:
print("Suspeito")
elif sum(quest) == 3 or sum(quest) == 4:
print("Cumplice")
elif sum(quest) == 5:
print("Assassino")
else:
print("Inocente") """
# 1. Crie um código em Python que pede qual tabuada o usuário quer ver, em
# seguida imprima essa tabuada.
""" num = int(input("Qual tabuada deseja imprimir?: "))
for i in range(1,11):
print(f'{num} x {i} = ',num*i) """
# 2. Elaborar um programa para imprimir os números de 1 (inclusive) até 10
# (inclusive) em ordem decrescente.
""" for i in range(1,11):
print(i, end = ' ')
for C in range(10, 0, -1):
print(C, end = ' ') """
# 3. Faça um programa que leia o estado civil de 15 pessoas (Solteiro / Casado) e
# mostre ao final a quantidade de pessoas de cada estado civil.
""" estado_civil = []
for i in range(1, 16):
estado_civil.append(input('Qual seu estado civil?(Solteiro[s] / Casado[c]): \n'))
print('Solteiros = ',estado_civil.count('s'))
print('Casados = ',estado_civil.count('c')) """
# 4. Faça um algoritmo que imprima 10 vezes a frase: “Go Blue”.
""" for i in range(1,11):
print('Go Blue', end = ' ') """
# 5. Faça um programa que mostre os valores numéricos inteiros ímpares situados
# na faixa de 0 a 20.
""" for i in range(1, 21, 2):
print(i, end = ' ') """
| false |
34f88b64105e960ae15d83589f7f808497d3e6e3 | Dansultan/python_fundamentals-master | /04_conditionals_loops/04_07_search.py | 358 | 4.28125 | 4 | '''
Receive a number between 0 and 1,000,000,000 from the user.
Use while loop to find the number - when the number is found exit the loop and print the number to the console.
'''
number = int(input("Please choose a number between 1 and 1,000,000 : "))
i = 0
while i <= 1000000:
i+=1
if i == number:
print(i)
else:
continue
| true |
05f89d81c140e24536a8370a3a9ba5faa6a0d2f1 | Dansultan/python_fundamentals-master | /04_conditionals_loops/04_01_divisible.py | 362 | 4.5 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
number = int(input("Please enter a number between 1 and 1,000,000,000 :"))
if number%3 == 0:
print("Your number is divisible by 3")
else:
print("Your number is not divisible by 3") | true |
2430c5d0ad1b3c340be21963928f26b576552196 | acecoder93/python_exercises | /Week1/Day5/PhoneBook_App.py | 2,024 | 4.40625 | 4 | # Phone Book App
print ('Welcome to the latest version of hthe Electronic Phone Book')
print ('Please see the list below of all of the options that are available.')
print ('''Electronic Phone Book
---------------------
1. Look up an Entry
2. Set an entry
3. Delete an entry
4. List all entries
5. Quit ''')
options = int(input('Please select an option: (1-5)? '))
myDictionary = [{
"John Doe" : "111-111-1111",
"Mamma Mia" : "222-222-2222",
"Mickey Mouse" : "333-333-3333",
"Ric Flair" : "444-444-4444"}
,{
"first_name" : "John",
"last_name" : "Doe",
"phone_number" : "888-888-8888"
}]
def look_up():
look_up = str.lower(input('Please provide the person\'s name: '))
if look_up == myDictionary[name]:
print ('{}\'s phone number is: {}'.format(name,myDictionary[name]))
def set_entry():
set_name = str.lower(input('Please provide the person\'s name: '))
set_number = int((input('Please provide the person\'s phonenumber: ')))
def delete_entry():
delete_entry = str.lower(input('Please provide the person\'s name: '))
def list_all_entries():
list_all_entries = str.lower(input('Would you like to list all entries? (Y or N) '))
while options != range(1,5,1):
if options == 1:
look_up()
elif options == 2:
set_entry()
elif options == 3:
delete_entry()
elif options == 4:
list_all_entries()
elif options == 5:
finish = str.lower(input('Quit the application? (Y or N) '))
else:
options = int(input('What do you want to do (1-5)? '))
# break
# if myDictionary[look_up] in myDictionary:
# print (myDictionary.value())
# look_up = str.lower(input('Please provide the person\'s name: '))
# set_entry = str.lower(input('Please provide the person\'s name and phone number: '))
# delete_entry = str.lower(input('Please provide the person\'ns name: '))
# list_all_entries = str.lower(input('Would you like to list all entries? (Y or N) '))
| true |
926a60d1843e0e1161b64521cbd91c5808fec66d | ivaneyvieira/pythonJango | /testeIF.py | 219 | 4.21875 | 4 | #!/usr/bin/env python3
num = int(input("Digite um número: "))
if num % 2 == 0:
print("Eh par")
else:
print("Eh impar")
if num % 2 == 0:
print("Eh um número par")
else:
print("Eh um número impar")
| false |
76384fcd407b5d010b9bb56bac5f23c71aa45a0d | chloe-wong/leetcodechallenges | /088_Merge_Sorted_Array.py | 1,281 | 4.28125 | 4 | """
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
"""
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
if n == 0:
return(nums1)
else:
del nums1[-n:]
for x in range(len(nums2)):
target = nums2[x]
currentindex = 0
while True:
try:
if nums2[x] <= nums1[currentindex]:
nums1.insert(currentindex,target)
break
else:
currentindex = currentindex + 1
except IndexError:
nums1.append(target)
break
| true |
a5bfc3163002084e274f971292f7fd5fe51916b6 | sardar1023/myPyGround | /OOP_impl.py | 2,227 | 4.53125 | 5 | #Python is amazing language. You can also implement OOPs concepts through python
#Resource: https://www.programiz.com/python-programming/object-oriented-programming
####Creat a class object and method####
class Parrot:
species = "bird"
def __init__(self,name,age):
self.name = name
self.age = age
def sing(self,song):
return "{} is now sings {}".format(self.name,song)
def dance(self):
return "{} is now dancing".format(self.name)
blu = Parrot("Blu",10)
woo = Parrot("Woo",15)
print("Blue is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
print(blu.sing("'Happy'"))
print(blu.dance())
###Inheritance####
#Parent Class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
class Penguin(Bird):
def __init__(self):
#call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
####Encapsulation####
"""In python we can denote private attribute
using underscore as prefix i.e single "_" or
"__"."""
class computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self,price):
self.__maxprice = price
c = computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
###Polymorphism--(Use common interface)###
class Airplane:
def fly(self):
print("Airplane can fly")
def swim(self):
print("AirPlane cannot swim")
class Boat:
def fly(self):
print("Boat cannot fly")
def swim(self):
print("Boat can swim")
###Let's define a common interface
def flying_test(bird):
bird.fly()
plane = Airplane()
boat = Boat()
# passing the object
flying_test(plane)
flying_test(boat)
| true |
99962d1c4eba31c6cc61e686fa475dc46c87699f | praveenkumarjc/tarzanskills | /loops.py | 250 | 4.125 | 4 | x=0
while x<=10:
print('x is currently',x)
print('x is still less than 10')
x=x+1
if x==8:
print('breaking because x==8')
break
else:
print('continuing....................................')
continue | true |
6996d908c879d262226ff1601ba70f714c861714 | Olb/python_call_analysis | /Task2.py | 2,634 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
"""
Returns a dictionary of calls in a given period O(n)
"""
def calls_in_period(calls, period):
# Below was a suggestion from reviewer feedback
call_dict = {}
for call in calls:
if call[0] not in call_dict.keys():
call_dict[call[0]] = int(call[3])
else:
call_dict[call[0]] += int(call[3])
if call[1] not in call_dict.keys():
call_dict[call[1]] = int(call[3])
else:
call_dict[call[1]] += int(call[3])
return call_dict
"""
Retuns the number and time in seconds of the longest time
by a given number on calls in a given period O(n)
Parameters: str, format '09-2016' for September 2016
"""
def longest_call_in_period(calls, period):
dict = calls_in_period(calls, period)
maxValue = 0
maxKey = ''
# Worse case dict could hold n
for key in dict:
if dict[key] > maxValue:
maxValue = dict[key]
maxKey = key
return maxKey, maxValue
def test():
result = longest_call_in_period(calls, '09-2016')
message = '{} spent the longest time, {} seconds, on the phone during September 2016.'.format(result[0], result[1])
print(message)
def tests():
test_cases = [['97424 22395', '90365 06212', '01-09-2026 06:03:22', '1'],
['94489 72078', '92415 91418', '01-09-2016 06:05:35', '2'],
['78993 92058','92411 96415','30-09-2016 23:14:19', '3'],
['78993 92058','92411 96415','30-08-2016 23:14:19', '3'],
['94489 72078','92411 96415','30-09-2016 23:14:19', '4']]
# Test total durations
assert(calls_in_period(test_cases, '09-2016')['97424 22395'] == 0)
assert(calls_in_period(test_cases, '09-2016')['78993 92058'] == 3)
assert(calls_in_period(test_cases, '09-2016')['94489 72078'] == 6)
result = longest_call_in_period(test_cases, '09-2016')
message = '{} spent the longest time, {} seconds, on the phone during September 2016.'.format(result[0], result[1])
assert(message == '92411 96415 spent the longest time, 7 seconds, on the phone during September 2016.')
test()
| true |
59858e66eb9e86f1503fe9afb90d1186226a569a | richardmanasseh/hort503 | /lpthw/ex4.py | 1,427 | 4.40625 | 4 | # Ex 4: Variables and Names
# Variables are "words" that hold a value
FRUIT = peach #
# The operand to the left of the = operator (FRUIT) is the name of the variable
# The operand to the right (peach) is the value stored in the variable.
# A variable is similar to the memory functionality found in most calculators, in that it holds one value which can be retrieved many times
# you to assign a single value to several variables simultaneously. e.g:
a = b = c = 1 # Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location
#You can also assign multiple objects to multiple variables e.g:
a,b,c = 1,2,"john" # Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c.
cars = 100
space_in_a_car = 4
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are" , cars , "cars available.")
print("There are only" , drivers , "drivers available.")
print("There will be" , cars_not_driven , "empty cars today.")
print("We can transport" , carpool_capacity , "people today.")
print("We have" , passengers , "to carpool today.")
print("We need to put about" , average_passengers_per_car , "in each car.")
| true |
6c3532589b88192fd0ff2b029cb0f9fd631aaf22 | richardmanasseh/hort503 | /lpthw/ex7.py | 940 | 4.1875 | 4 | # More Printing & Formatting
print("Mary had a little lamp.")
print("Its fleece was white as {}. ".format('snow'))
print("And everywhere that Mary went.")
print("." * 10) # Prints string (".") ten times
# By default python’s print() function ends with a newline, because it comes with a parameter called ‘end’.
# By default, the value of this parameter is ‘\n’, i.e. the new line character.
# Line ending uses Windows convention of "\r\n" .
print("Welcome to" , end = ' ')
print("GeeksforGeeks", end = ' ') # Output: Welcome to GeeksforGeeks
print("Python" , end = '@')
print("GeeksforGeeks") # Python@GeeksforGeeks
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch end = ' ' at the end. try removing it and see what happens
print(end1 + end2 + end3 + end4 + end5 + end6, end= ' ')
print(end7 + end8 + end9 +end10 + end11 + end12)
| true |
9fed24a2a440c14883e062c59ea8d402a52e772c | richardmanasseh/hort503 | /lpthw/ex29.py | 2,422 | 4.25 | 4 | # What If
# At the end of each working day,the balance of a bank account is considered...
# IF the account is overdrawn, charges are applied to the account.
# So we ask the question: is the account overdrawn? Yes (=True) or No (=False)
# Algorithm:
# Step 1 Define your problem: we apply charges to a bank account if the account is overdrawn
# Step 2 Algorithms input(s):account_balance, bank_charge
# Step 3 Define the algorithm's local (input and output) variables: account_balance
# Step 4 Outline the algorithm's operation(s): # set bank charge
# set bank bonus
# set account balance
# determine whether or not account is overdrwan
# if True, apply the charge
# display the account balance
# Step 5 Output the results (output) of your algorithm's operation(s): display the account balance.
set bank_charge = 10
set account_balance = 100
if account_balance < 0:
account_balance = account_balance - bank_charge # indentation typically four spaces
print("The account balance is" + str(account_balance))
set bank_charge = 10
set account_balance = -10
if account_balance < 0:
account_balance = account_balance - bank_charge # indentation typically four spaces
print("The account balance is" + str(account_balance))
people = 20
cats = 30
dogs = 15
if people < cats: # if this Boolean expression is True, execute the "branch" code under it; otherwise skip it.
print("Too many cats! The world is doomed!") # this branch code has to be indented with four spaces to tell the block defined by the Boolean expression.
# Python expects you to indent something after you end a line with ":"
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs += 5 # <=> 15 dogs + 5 = 20 dogs. += can be considered an "increment operator"
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")
if people == dogs:
print("People are dogs.")
| true |
75bb09a361e33624f85c545e37210a78639f9d1b | richardmanasseh/hort503 | /Assignments/lpthw/Assignment02/ex13.py | 987 | 4.125 | 4 | from sys import argv
script, first, second, third = argv
# module sys is not imported, rather just argv has been imported as a variable.
# Python modules can get access to code from another module by importing the file/function using import
# sys = system library, contains some of the commands one needs in order to work with command-line arguments
# argv is aka argument vector,
# Arguments are command modifiers that change the behavior of a command.
# read the WYSS section for how to run this
# whenever you run a script e.g. ex13.py on the command-line, s soon as you hit Enter, that program gets stored automatically in argv element 0 (agrv[0]) all the time
# if you put any thing else after that e.g. ext13.py test.txt, it will automatically get stored in argv[1]
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
# **** Run the program with all three arguments
| true |
2a303f20dfe2844ea99580423d4e18af81d6c5ee | richardmanasseh/hort503 | /Assignments/lpthw/Assignment02/ex7.py | 968 | 4.3125 | 4 | print("Mary had a little lamp.")
print("Its fleece was white as {}. ".format('snow'))
print("And everywhere that Mary went.")
print("." * 10) # what'd that do? Prints string ten times
# By default python’s print() function ends with a newline.
# # Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\n’, i.e. the new line character. You can end a print statement with any character/string using this parameter.
print("Welcome to" , end = ' ')
print("GeeksforGeeks", end = ' ') # Output: Welcome to GeeksforGeeks
print("Python" , end = '@')
print("GeeksforGeeks") # Python@GeeksforGeeks
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch end = ' ' at the end. try removing it and see what happens
print(end1 + end2 + end3 + end4 + end5 + end6, end= ' ')
print(end7 + end8 + end9 +end10 + end11 + end12)
| true |
a18a42ff4815c6954e5c4cdf8ea1a172f7d16cd4 | richardmanasseh/hort503 | /Assignments/Assignment04/ex21.py | 1,115 | 4.34375 | 4 | # Functions Can Return Something
# The print() function writes, i.e., "prints", a string in the console.
# The return statement causes your function to exit and hand back a value to its caller.
def add(a, b): # this (add) function is called with two parameters: a and b
print(f"ADDING {a} + {b}") # we print what our function is doing
return a + b # we return the addition of a + b
def subtract(a, b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a, b):
print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a, b):
print(f"DIVIDING {a} / {b}")
return a / b
print("Let's do some math with just functions!")
age = add(30, 5) # call the add function, and set it to variable "age"
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}")
# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) # making function calls inside functions
print("That becomes: ", what, "Can you do it by hand?")
| true |
eaba342178fd0cd9efd60ed6816a213412396edf | richardmanasseh/hort503 | /lpthw/ex33.py | 1,525 | 4.3125 | 4 | # While-Loops
# The while loop tells the computer to do something as long as the condition is met
# it's construct consists of a block of code and a condition.
# It works like this: " while this is true, do this "
i = 1 # intially i =1
while i <= 10: # loop condition, interpreter first checks if this condtion is true
print(i) # 1 < 10, prints 1
i = i + 1 # then adds 1 to i, so i now goes from 1 to 2 (i+=1), overwiting the intital value of 1
# program then goes back to check the loop condition once more, and executes the code inside the loop again
# loop is evaluated for values of i in the range 1-10
print("Done with loop")
# Output: list, 1-10
x = 5
while x > 0:
print(f"timeleft = ", x)
x -= 1 # decreases the value of munutes by 1, then assigns this new value back to minutes, overwiting the intital value of 5
# we need to decrease the value of minutes by 1 so that the loop condition while minutes > 0 will eventually evaluate to false
#If we forget that, the loop will keep running endlessly resulting in an infinite loop
# ...in this case the program would keep printing timeleft = 5 until you somehow kill the program
z = 1 # intially z =1
while z <= 15: # loop condition, interpreter first checks if this condtion is true
if z == 12:
break # break statement to prematurely terminate the excecution of the loop
else:
print(z) # 1 < 15, prints 1
z = z + 1
# Output: list, 1-11
| true |
57a0315522093751af054ca900fbd16c4ab30f8b | shruti310gautam/python-programming | /function.py | 291 | 4.25 | 4 | #You are given the year, and you have to write a function to check if the year is leap or not.
def is_leap(year):
leap = False
if (year%4 == 0 and year%100 != 0) or (year%400 == 0) :
leap = True
return leap
#Sample Input=1990
#Sample Output=False
| true |
f485c5a58c0774d0ef5ec230ebf62361849d7a3f | wgatharia/csci131 | /5-loops/exercise_3.2.py | 411 | 4.40625 | 4 | """
File: exercise_3.2.py
Author: William Gatharia
This code demonstrates using a while loop.
"""
#loop and print numbers from 1 to 10 using a while loop
number = 1
while True:
print(number)
#increment number
#short hand for increasing number by 1
#number += 1
number = number + 1
#check if number is greater than 10 and exit loop using break
if number > 10:
break
| true |
7a9673f15d019e3d98f5f4584ceec3f3d496a2f3 | rosmoke/DCU-Projects | /bucketlist/bl-binary-to-decimal.py | 359 | 4.125 | 4 | import sys
binary = sys.argv[1]
i = len(binary) # here we set the counter to how many numbers we have
power = 0
result = 0
while i > 0: # here we set the counter to do something i times
result += int(binary[i-1]) * 2 ** power # we convert each number to decimal
i = i - 1
power = power + 1 # now we increase the power for every number we have
print result | false |
08ef8f971812f815cf41a5b56050eb3bfeaf3917 | abdullaheemss/abdullaheemss | /My ML Projects/Data Visualization Exercises/01 - Understanding plotting.py | 626 | 4.125 | 4 | # ---------------------------------------------------------
# Understand basics of Plotting
# ---------------------------------------------------------
# Import pyplot from matplotlib
import matplotlib.pyplot as plt
# Create data to plot
x_days = [1,2,3,4,5]
y_price1 = [9,9.5,10.1,10,12]
y_price2 = [11,12,10.5,11.5,12.5]
# Change the chart labels
plt.title("Stock Movement")
plt.xlabel("Week Days")
plt.ylabel("Price in USD")
# Create the plot
plt.plot(x_days, y_price1, label="Stock 1")
plt.plot(x_days, y_price2, label="Stock 2")
plt.legend(loc=2, fontsize=12)
# Show the Plot
plt.show()
| true |
ab8f166f68cb1bb13fa24aa3fe0d140809f6f5bf | webclinic017/data-pipeline | /linearRegression/lrSalesPredictionOnAddData.py | 1,026 | 4.375 | 4 | # https://towardsdatascience.com/introduction-to-linear-regression-in-python-c12a072bedf0
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import statsmodels.formula.api as smf
# Import and display first five rows of advertising dataset
advert = pd.read_csv('advertising.csv')
print(advert.head())
# Initialise and fit linear regression model using `statsmodels`
model = smf.ols('sales ~ TV', data=advert)
model = model.fit()
print("model.params ==> ")
print(model.params)
# # Sales = 7.032 + 0.047*TV --
# # Predict values
# sales_pred = model.predict()
#
#
# # Plot regression against actual data
# plt.figure(figsize=(12, 6))
# plt.plot(advert['TV'], advert['sales'], 'o') # scatter plot showing actual data
# plt.plot(advert['TV'], sales_pred, 'r', linewidth=2) # regression line
# plt.xlabel('TV Advertising Costs')
# plt.ylabel('Sales')
# plt.title('TV vs Sales')
# plt.show()
# new_X = 400
# pred_new_X = model.predict({"TV": new_X})
# print("pred_new_X"+str(pred_new_X)) | true |
310d5545758fc462c4269353a15beb122762f660 | sven-walser/Python-test | /selbstprojekte/namensbewerter.py | 479 | 4.125 | 4 | #!/usr/bin/env python3
print("Sag mir wie du heisst dann bewerte ich deinen Namen")
name = input("Dein Name: ")
name = name.lower()
if name == "sven":
print("so ein schöner Name")
elif name == "claudio":
print("Das ist der schlechteste Name den ich je gehört habe")
elif name == "simon":
print("wow du warst also stärker als die Tür")
elif name == "roman":
print("häufiger Name aber immer noch besser als CLaudio")
else:
print("Dieser Name ist nicht so schön")
| false |
a12f8edb0fda9985d3739772c338b45f6ae9ad7c | AngeloESFM/All_programs | /raiz_cuadrada.py | 231 | 4.125 | 4 | import math
num1 = input("inserte número para sacarle raiz cuadrada:")
num1 = float(num1)
print(math.sqrt(num1))
def raiz_c(n):
num1 = 0
while num1 * num1 <= n:
num1 += 0.00001
return num1
print(raiz_c(num1))
| false |
3f7e8cbe8ec1617d5125b361167de964b513998d | AngeloESFM/All_programs | /listas_o_vectores2.py | 588 | 4.375 | 4 | # 26 Listas
# Sirven para tener elementos guardadados entre corchetes como vectores
# Colección de elementos, las listas están ordenadas y son mutables
frutas = ["Naranja", "Manzana", "Banana", "Kiwi", "Mandarina", "Uva"]
# 0 1 2 3 4 5
# Imprime toda la lista
print (frutas)
print (frutas[5])
# Imprime de atras hacía adelante
print (frutas[-6])
# usando los dos puntos ":" es para indicar un intervalo de las lista, cuantos elementos se muestran
print (frutas[1:4])
print (frutas[:3])
print (frutas[1:])
| false |
e84d6844fa2d7c63fa300054a797152dffe3b322 | adarsh161994/python | /part 2.py | 811 | 4.40625 | 4 | # Addition of strings
# stri = "My name is"
# name = " Adarsh"
# print(stri + name)
# How to make temp
# name1 = "ADARSH"
# name2 = "YASH"
# temp = "This is {} and {} is my best friend".format(name1, name2)
# print(temp)
# Now introducing 'f' string It is also doing same thing which we have done above.
# ITS also very important to understand.
# =>
# name1 = "Adarsh"
# name2 = "Yash"
# temp = f"My name is {name1} and {name2} is my best friend" # This is the syntax of "f" function
# print(temp)
# Exercise to do
# 1. ** Exponentiation operator
# 2. // Floor division operator
# 3. % Modulo operator
# a = 6
# b = 3
# expo = a**b (Exponential operator)
# mod = a % b (Modulo operator)
# fd = a // b (Floor Division operator)
# print(expo, mod, fd)
# Python collection
# 1. LIST
| true |
af26e1489a9ae2956c4c8163c57d88282ef4e239 | Urielglb/Curso-Python-Raccoons | /clase2/listas.py | 1,956 | 4.21875 | 4 | #Declarando listas
vacio = []#Lista vacia, se le puede meter elementos despues
supermercado =["Lechuga","Crema","Pan"]#Lista de strings
edades = [10,45,60]#lista de numeros
mixto = ["Lechuga",10,4.5,"Pan"]#Lista de varios tipos de dato, no se recomienda mezclar datos
#Accediendo a la lista
print(edades[0])#Primer elemento de edades
print(supermercado[1])#Segundo elemento de supermercado
print(mixto[3].upper())#Cuarto elemento de la lista en mayusculas
#Modificando los elementos de la lista
peliculas = ["Django","Perros de reserva"]
print(peliculas[1])
peliculas[1] = "Había una vez en Hollywood"
print(peliculas[1])
#Añadiendo elementos
actores = []
actores.append("Brad Pitt")#Agrega al final el elemento
print(actores[0])
actores.insert(0,"Jaime Fox")#Agrega el elemento en el numero que le das
print(actores[0]+", "+actores[1])
#Eliminando elemnetos de la lista
musicos = ["José José","Juan Gabriel","Roger Waters","Paul McCartney","David Bowie"]
del musicos[1]#Elimina a Juan Gabriel de la lista
star_man=musicos.pop()#Elimina el último elemento de la lista y te lo da
print(star_man)
el_principe = musicos.pop(0)#Elimina el elemento del numero que brindas de la lista y te lo da
print(el_principe)
musicos.remove("Roger Waters")#Elimina el elemento que recibe como parametro
#Ordenar
numeros = [5,4,3]
numeros.sort()
print(numeros[0])
#Reversa
directores = ["Tarantino","Cameron"]
directores.reverse()
print(directores[0])
#Slices
jokers = ["Nicholson","Ledger","Leto","Phoenix"]
print(jokers[1:3])#Mostrara elementos de la lista del 1 al 2
print(jokers[1:4:2])#Mostrara los elementos del 1 al 3 moviendose de dos en dos
#Omitir elementos con slices
batmans = ["Affleck","Keaton","Bale"]
print(batmans[:2])#Solo va a imprimir del 0 al 1
print(batmans[1:])#Solo va a imprimir del 1 en adelante
#Matrices
matriz = [
[1,2],
[3,4]
]#La matriz es una lista de listas
d1 = matriz[0][0]*matriz[1][1]
d2 = matriz[0][1]*matriz[1][0]
determinante = d1 - d2
print(determinante) | false |
c0ece596323cfcd837849a7fa5513a2daad6ddd2 | Renato-moura/PrgBancoFatec | /prgBancoEx1_3.py | 278 | 4.28125 | 4 | #3 Escreva um programa que calcula e mostra a rea de um crculo, uma vez que o usurioinforme o raio. Use math.pi para obter um valor aproximado de pi. (Use import math antes).
import math
raio = float(input("digite o raio: "))
area = math.pi * (raio ** 2)
print(area) | false |
95451780778a80ba364d857addb9e23ac67b856f | spradeepv/dive-into-python | /hackerrank/domain/artificial_intelligence/bot_building/bot_saves_princess.py | 2,769 | 4.3125 | 4 | """
Princess Peach is trapped in one of the four corners of a square grid. You
are in the center of the grid and can move one step at a time in any of the
four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the size of
the grid. This is followed by an NxN grid. Each cell is denoted by '-' (
ascii value: 45). The bot position is denoted by 'm' and the princess
position is denoted by 'p'.
Grid is indexed using Matrix Convention
Output format
Print out the moves you will take to rescue the princess in one go. The
moves must be separated by '\n', a newline. The valid moves are LEFT or
RIGHT or UP or DOWN.
Sample input
3
---
-m-
p--
Sample output
DOWN
LEFT
Task
Complete the function displayPathtoPrincess which takes in two parameters -
the integer N and the character array grid. The grid will be formatted
exactly as you see it in the input, so for the sample input the princess is
at grid[2][0]. The function shall output moves (LEFT, RIGHT, UP or DOWN) on
consecutive lines to rescue/reach the princess. The goal is to reach the
princess in as few moves as possible.
The above sample input is just to help you understand the format. The
princess ('p') can be in any one of the four corners.
Scoring
Your score is calculated as follows : (NxN - number of moves made to rescue
the princess)/10, where N is the size of the grid (3x3 in the sample testcase).
"""
def displayPathtoPrincess(n,grid):
#print grid
my_pos_x = 0
my_pos_y = 0
princess_pos_x = 0
princess_pos_y = 0
for x in range(n):
for y in range(n):
if grid[x][y] == 'm':
my_pos_x = x
my_pos_y = y
elif grid[x][y] == 'p':
princess_pos_x = x
princess_pos_y = y
#print "My Position: ", my_pos_x, my_pos_y
#print "Princess Position: ", princess_pos_x, princess_pos_y
if my_pos_x > princess_pos_x:
# Princess is above me
diff_x = my_pos_x - princess_pos_x
for _ in range(diff_x):
print "UP"
elif my_pos_x < princess_pos_x:
# Princess is below me
diff_x = princess_pos_x - my_pos_x
for _ in range(diff_x):
print "DOWN"
if my_pos_y > princess_pos_y:
# Princess is to my left side
diff_y = my_pos_y - princess_pos_y
for _ in range(diff_y):
print "LEFT"
elif my_pos_y < princess_pos_y:
# Princess is to my right side
diff_y = princess_pos_y - my_pos_y
for _ in range(diff_y):
print "RIGHT"
n = int(raw_input())
grid = []
for i in xrange(0, n):
grid.append(list(raw_input().strip()))
displayPathtoPrincess(n, grid)
| true |
ccfe895e27c01f03f8a277528d35f306d89e56ea | spradeepv/dive-into-python | /hackerrank/domain/artificial_intelligence/bot_building/bot_clean_large.py | 2,103 | 4.40625 | 4 | """
In this challenge, you must program the behaviour of a robot.
The robot is positionned in a cell in a grid G of size H*W. Your task is
to move the robot through it in order to clean every "dirty" cells.
Input Format
The first line contians the position x and y of the robot.
The next line contains the height H and the width W of the grid.ille.
The H next lines represent the grid G. Each cell is represented by one of
those three characters:
'b' for the position of the robot
'd' for a dirty cell
'-' for a clean cell
If the robot is on a dirty cell, the character 'd' will be used.
Constraints
1<=W<=50
1<=H<=50
Output Format
You must print the next action the robot will perform. Here are the five
possibilities:
LEFT
RIGHT
UP
DOWN
CLEAN
It's important you understand that the input you get is a specific
situation, and you must only print the next action to perform. You program
will be called iteratively several times so that the robot cleans all the grid.
Sample Input
0 0
5 5
b---d
-d--d
--dd-
--d--
----d
Sample Output
RIGHT
Resultant state
-b--d
-d--d
--dd-
--d--
----d
"""
from functools import partial
def next_move(bot_x, bot_y, height, width, board):
dirty_cells = []
for x in range(height):
for y in range(width):
if board[x][y] == 'd':
dirty_cells.append((x, y))
# Get closest cell
dist = lambda s, d: (s[0]-d[0]) ** 2 + (s[1]-d[1]) ** 2
closest_dirty_cell = min(dirty_cells, key=partial(dist, (bot_x, bot_y)))
x = closest_dirty_cell[0]
y = closest_dirty_cell[1]
move = ""
if bot_x != x:
if bot_x > x:
move = "UP"
else:
move = "DOWN"
elif bot_y != y:
if bot_y > y:
move = "LEFT"
else:
move = "RIGHT"
else:
move = "CLEAN"
print move
if __name__ == "__main__":
pos = [int(i) for i in raw_input().strip().split()]
dim = [int(i) for i in raw_input().strip().split()]
board = [[j for j in raw_input().strip()] for i in range(dim[0])]
next_move(pos[0], pos[1], dim[0], dim[1], board) | true |
7c54a3e4de30e706ff577367a5ed608d93b6233f | spradeepv/dive-into-python | /hackerrank/domain/python/sets/intro_mickey.py | 975 | 4.40625 | 4 | """
Task
Now, lets use our knowledge of Sets and help 'Mickey'.
Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student 'Mickey' to compute an average of all the plants with distinct heights in her greenhouse.
Formula used:
Average=SumofDistinctHeightsTotalNumberofDistinctHeights
Input Format
First line contains, total number of plants in greenhouse.
Second line contains, space separated height of plants in the greenhouse.
Total number of plants is upto 100 plants.
Output Format
Output the average value of height.
Sample Input
10
161 182 161 154 176 170 167 171 170 174
Sample Output
169.375
Explanation
set([154, 161, 167, 170, 171, 174, 176, 182]), is the set containing distinct heights. Using sum() and len() functions we can compute the average.
Average=13558=169.375
"""
from __future__ import division
n = int(raw_input())
l = map(int, raw_input().split())
s = set(l)
avg_ht = sum(s)/len(s)
print "{:.3f}".format(avg_ht)
| true |
3e09c61d5a62a3e00412522aa5e0895402696f87 | spradeepv/dive-into-python | /hackerrank/domain/python/built_in/any_or_all.py | 1,386 | 4.3125 | 4 | """
any()
This expression returns True if any element of the iterable is true.
If the iterable is empty, it will return False.
Code
----
any([1>0,1==0,1<0])
True
any([1<0,2<1,3<2])
False
all()
This expression returns True if all of the elements of the iterable are
true. If the iterable is empty, it will return True.
Code
----
all(['a'<'b','b'<'c'])
True
all(['a'<'b','c'<'b'])
False
Task
----
You are given a space separated list of integers. If all the integers are
positive, then you need to check if any integer is a palindromic integer.
Input Format
------------
The first line contains an integer N. N is the total number of integers in
the list.
The second line contains the space separated list of N integers.
Constraints
-----------
0<N<100
Output Format
-------------
Print True if all the conditions of the problem statement are satisfied.
Otherwise, print False.
Sample Input
------------
5
12 9 61 5 14
Sample Output
------------
True
Explanation
-----------
Condition 1: All the integers in the list are positive.
Condition 2: 5 is a palindromic integer.
Hence, the output is True.
Can you solve this challenge in 3 lines of code or less?
There is no penalty for solutions that are correct but have more than 3 lines.
"""
n = int(raw_input())
l = map(int, raw_input().split())
print all(el > 0 for el in l) and any(str(el) == str(el)[::-1] for el in l)
| true |
abc4b59db59660232c5ee767870f41b686fe526b | spradeepv/dive-into-python | /hackerrank/domain/python/numpy/min_max.py | 1,838 | 4.5625 | 5 | """
Problem Statement
min
The tool min returns the minimum value along a given axis.
import numpy
my_array = numpy.array([[2, 5],
[3, 7],
[1, 3],
[4, 0]])
print numpy.min(my_array, axis = 0) #Output : [1 0]
print numpy.min(my_array, axis = 1) #Output : [2 3 1 0]
print numpy.min(my_array, axis = None) #Output : 0
print numpy.min(my_array) #Output : 0
By default, the axis value is None. Therefore, it finds the minimum over all
the dimensions of the input array.
max
The tool max returns the maximum value along a given axis.
import numpy
my_array = numpy.array([[2, 5],
[3, 7],
[1, 3],
[4, 0]])
print numpy.max(my_array, axis = 0) #Output : [4 7]
print numpy.max(my_array, axis = 1) #Output : [5 7 3 4]
print numpy.max(my_array, axis = None) #Output : 7
print numpy.max(my_array) #Output : 7
By default, the axis value is None. Therefore, it finds the maximum over all
the dimensions of the input array.
Task
You are given a 2-D array with dimensions NXM.
Your task is to perform the min function over axis 1 and then find the max
of that.
Input Format
The first line of input contains the space separated values of N and M.
The next N lines contains M space separated integers.
Output Format
Compute the min along axis 1 and then print the max of that result.
Sample Input
4 2
2 5
3 7
1 3
4 0
Sample Output
3
Explanation
The min along axis 1 = [2,3,1,0]
The max of [2,3,1,0] = 3
"""
import numpy
n, m = map(int, raw_input().split())
a = numpy.array([map(int, raw_input().split()) for i in range(n)],
dtype=numpy.int)
min_array = numpy.min(a, axis=1)
print numpy.max(min_array) | true |
7c5c86da342258cbe51310f7ef859ec7e25dc73c | spradeepv/dive-into-python | /hackerrank/domain/python/regex/validating-named-email.py | 1,589 | 4.4375 | 4 | """
Problem Statement
You are given N names and email addresses. Your task is to print the names
and email addresses if they are valid.
A valid email address follows the rules below:
- Email must have three basic components: username @ website name . extension.
- The username can contain: alphanumeric characters, -,. and _.
- The username must start with an English alphabet character.
- The website name contains only English alphabet characters.
- The extension contains only English alphabet characters, and its length
can be 1, 2, or 3.
Input Format
name <example@email.com>
The first line contains an integer N.
The next N lines contains a name and an email address separated by a space.
Constraints
0<N<100
Output Format
Print the valid email addresses only. Print the space separated name and
email address on separate lines.
Output the valid results in order of their occurrence.
Sample Input
2
DEXTER <dexter@hotmail.com>
VIRUS <virus!@variable.:p>
Sample Output
DEXTER <dexter@hotmail.com>
Explanation
dexter@hotmail.com
This is a valid email address.
virus!@variable.:p
This is invalid because it contains a ! in the username and a : in the
extension.
Bonus
Email.utils()
import email.utils
print email.utils.parseaddr('DOSHI <DOSHI@hackerrank.com>')
('DOSHI', 'DOSHI@hackerrank.com')
print email.utils.formataddr(('DOSHI', 'DOSHI@hackerrank.com'))
DOSHI <DOSHI@hackerrank.com>
"""
import email.utils
import re
for _ in range(int(raw_input())):
pair = email.utils.parseaddr(raw_input())
pattern = r'^[a-z]+[a-z0-9_\-.]*@[a-z]+.[a-z]{1,3}$'
#print pair[1]
if re.match(pattern, pair[1]):
print email.utils.formataddr(pair) | true |
33e672ec8d42bf4f655a9eb08d406108b041f025 | zuzanadostalova/The-Python-Bible-Udemy | /6_Section_Conditional_logic.py | 667 | 4.28125 | 4 | # 30. lesson - Future lesson overview
# 31. lesson - Booleans
# Boolean is not created through typing its value - we get it from doing logical comparison
print(2<3)
# Output: True
print(2>3)
# Output: False
print(type(2<3))
# Output: <class 'bool'>
# print(2 = 3)
# Output: Error - cannot assign to literal
print(2 == 3)
# Output: False
print(3 == 3)
# Output: True
print(2 != 3)
# Output: True; 2 does not equal to 3
print(4 >= 3)
# Output: True, 4 is bigger or equals 3
print(3 >= 3)
# Output: True
print(2 >= 3)
# Output: False
print(4 <= 3)
# Output: False
print(2 <= 3)
# Output: True
print(3 <= 3)
# Output: True
# 6 booleans >, <, ==, !=, >=, <=
| true |
0caac48689854309f5e867a07cd148287a9a376e | zuzanadostalova/The-Python-Bible-Udemy | /8_Section_For_loops.py | 1,918 | 4.46875 | 4 | # 50. lesson - For loops
# most useful loops
# "for" loops - variable (key) - changing on each cycle of the loop
# and iterable (students.keys()) - made up from elements
# In each cycle, the variable becomes the next value in the iterable
# operation on each value
# range function - set up number, create number iterables
# how to put "for" loops inside each other
# advanced process, powerful - lot of information in a one line of code
# Do not forget column (:) after end parentheses
# "for", variable = number, iterable = range (could be a list, string)
for number in range(1,1001):
print(number)
for number in range(1,11,2):
print (number)
# list
for list in [1,2,3,4]:
print(list)
# string
for letter in "abcd":
print(letter)
# If you wait, it tells you how to do it
# This is used:
vowels = 0
consonants = 0
for letter in "Hello":
if letter.lower() in "aeiou":
vowels = vowels + 1
elif letter == "":
pass
else:
consonants = consonants + 1
print("There are {} vowels.".format(vowels))
print("There are {} consonants.".format(consonants))
# Output:There are 2 vowels.
# There are 3 consonants.
# 51. lesson - "For" loops 2
students = {
"male":["Tom", "Charlie", "Harry", "Frank"],
"female":["Sarah", "Huda", "Samantha", "Emily", "Elizabeth"]
}
for key in students.keys():
print(key)
# Output: male, female = keys
for key in students.keys():
print(students[key])
# Output:['Tom', 'Charlie', 'Harry', 'Frank']
# ['Sarah', 'Huda', 'Samantha', 'Emily', 'Elizabeth']
# To pull out each name
# "For" loop for following names
# students of the key male
# for every name in the male list - if there is a, print the name
# and subsequently female names
for key in students.keys():
for name in students[key]:
if "a" in name:
print(name)
# Output:
# Charlie
# Harry
# Frank
# Sarah
# Huda
# Samantha
# Elizabeth
| true |
1ef901e075f7b922099badb7e1a62ea826317a21 | gidpfeffer/CS270_python_bootcamp | /2-Conditionals/2_adv.py | 866 | 4.21875 | 4 | """
cd into this directory
run using: python 2_adv.py
"""
a = 10
if a < 10:
print("a is less than 10")
elif a > 10:
print("a is greater than 10")
else:
print("a is 10")
# also could do
if a == 10:
print("a is 10")
# or
if a is 10:
print("a is 10")
# is checks for object equality where == does value equality
# don't use the keyword is for integers or floats
# ex
if 10000 is 10000:
print("10000 is 10000")
if 10000 is pow(10, 4):
pass
else:
print("10000 is NOT pow(10, 4)")
# If you want to see some crazy magic that results from this ask Colter
# not negates the statements
#ex
if not False:
print("Not False is True")
# So we can write
if not a < 10 and not a > 10:
print("a is 10")
# There is no Null but we do have None and None is false
if not None:
print("None is false")
# there is a ternary operator it is contentious use at own risk
| true |
8a96f25f94b5f008c11075e2667f8b34ae850f04 | gidpfeffer/CS270_python_bootcamp | /4-Functions/2_optional_args.py | 979 | 4.3125 | 4 | """
cd into this directory
run using: python 2_optional_args.py
"""
def printName(firstName, lastName=""):
print("Hi, " + firstName + lastName)
# uses default lastname
printName("Gideon")
# uses passed in lastname
printName("Gideon", " Pfeffer")
def printNameWithAge(firstName, lastName="", age=25):
print("Hi, " + firstName + lastName + ", you are " + str(age) + " years old")
# Does not work!!, specify which argument is which if out of order
# printNameWithAge("Bob", 12)
printNameWithAge("Bob", age=12)
# Be careful with defualt parameters especially mutable objects
# ex
def add_to_list(x, list=[]):
list.append(x)
return list
l = [x**3 for x in range(-2, 5, 2)]
print(l)
l = add_to_list(5, l)
print(l)
new_list = add_to_list(2)
print(new_list)
another_new_list = add_to_list(17)
print(another_new_list)
# you will see that the default list used for the parameter is the same
# across all function calls, it DOES NOT give you a fresh empty list every call
| true |
17404714d2acef85fed4768120996bb9e9ff86c5 | bhvya1505/Cryptography | /Stream Ciphers/Caesar/caesar.py | 371 | 4.125 | 4 | plaintext = raw_input("Enter your plaintext: ")
key = input("Enter the key: ")
ciphertext = ""
small = "abcdefghijklmnopqrstuvwxyz"
capital = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in plaintext:
if i in small:
ciphertext += small[(small.index(i)+key)%26]
elif i in capital:
ciphertext += capital[(capital.index(i)+key)%26]
else:
ciphertext += i
print ciphertext
| false |
07f33784f2e4962b190adc616d93048cac1f33ff | todorovventsi/Software-Engineering | /Programming-Fundamentals-with-Python/functions-exercises/03. Characters in Range.py | 424 | 4.1875 | 4 | def print_chars_in_between(char1, char2):
result = ""
if ord(char1) > ord(char2):
for char in range(ord(char2) + 1, ord(char1)):
result += chr(char) + " "
else:
for char in range(ord(char1) + 1, ord(char2)):
result += chr(char) + " "
return result
first_char = input()
second_char = input()
sequence = print_chars_in_between(first_char, second_char)
print(sequence)
| true |
ad772b77b29d2c780c2361ed6041b3b8c63c0259 | todorovventsi/Software-Engineering | /Python-Advanced-2021/05.Functions-advanced-E/04.Negative_vs_positive.py | 444 | 4.15625 | 4 | def compare_negatives_with_positives(nums):
positives = sum(filter(lambda x: x > 0, nums))
negatives = sum(filter(lambda x: x < 0, nums))
print(negatives)
print(positives)
if positives > abs(negatives):
return "The positives are stronger than the negatives"
return "The negatives are stronger than the positives"
numbers = [int(num) for num in input().split()]
print(compare_negatives_with_positives(numbers))
| true |
da1aec1428db680418a45e7b717b8c06639d5f70 | todorovventsi/Software-Engineering | /Programming-Fundamentals-with-Python/functions-lab/01. Grades.py | 437 | 4.21875 | 4 | def convert_grade_to_text_grade(grade_as_num):
if 2 <= grade_as_num <= 2.99:
return "Fail"
elif 3 <= grade_as_num <= 3.49:
return "Poor"
elif 3.50 <= grade_as_num <= 4.49:
return "Good"
elif 4.50 <= grade_as_num <= 5.49:
return "Very Good"
elif 5.50 <= grade_as_num <= 6.00:
return "Excellent"
grade = float(input())
result = convert_grade_to_text_grade(grade)
print(result)
| false |
c1436658b05474f63d7b99cf949878a9e63b5c35 | keurfonluu/My-Daily-Dose-of-Python | /Solutions/42-look-and-say-sequence.py | 844 | 4.125 | 4 | #%% [markdown]
# A look-and-say sequence is defined as the integer sequence beginning with a single digit in which the next term is obtained by describing the previous term. An example is easier to understand:
#
# Each consecutive value describes the prior value.
# ```
# 1 #
# 11 # one 1's
# 21 # two 1's
# 1211 # one 2, and one 1.
# 111221 # #one 1, one 2, and two 1's.
# ```
# Your task is, return the nth term of this sequence.
#%%
def sequence(n):
if n == 1:
return "1"
else:
seq = sequence(n-1)
out = ""
count = 1
for a, b in zip(seq[1:], seq[:-1]):
if a == b:
count += 1
else:
out += "{}{}".format(count, b)
count = 1
out += "{}{}".format(count, seq[-1])
return out
print(sequence(5)) | true |
104cf3da661d2a8b84736b8312876bdcc912126c | jugshaurya/Learn-Python | /2-Programs-including-Datastructure-Python/5 - Stack/balanceParenthesis.py | 1,003 | 4.21875 | 4 | '''
Balanced Paranthesis
Given a string expression, check if brackets present in the expression are balanced or not. Brackets are balanced if the bracket which opens last, closes first.
You need to return true if it is balanced, false otherwise.
Sample Input 1 :
{ a + [ b+ (c + d)] + (e + f) }
Sample Output 1 :
true
Sample Input 2 :
{ a + [ b - c } ]
Sample Output 2 :
false
'''
def isBalance(string):
my_stack = [] # using list as stack
for chr in string:
if chr in '({[':
my_stack.append(chr)
elif chr in ')}]' :
if my_stack == [] :
return False
if chr == ')':
if my_stack[-1] != '(':
return False
else:
my_stack.pop()
elif chr == '}':
if my_stack[-1] != '{':
return False
else:
my_stack.pop()
else :
if my_stack[-1] != '[':
return False
else:
my_stack.pop()
return my_stack == []
def main():
string = input()
if isBalance(string):
print('true')
else:
print('false')
if __name__ =='__main__':
main()
| true |
67601147a8b88309baf61fdc1f5f81a769b8dc0c | solomonbolleddu/LetsUpgrade--Python | /LU Python Es Day-4 assignment.py | 1,471 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Assignment - 4 Day - 4
# 1) write a program to find all the occurences of the substring in the given string along with the index value
# I have used list comprehension + startswith() to find the occurences ***
# In[2]:
a=input("Enter The String\n")
b=input("Enter The Substring\n")
c= [i for i in range(len(a)) if a.startswith(b, i)]
print("The Indices of the Substrings are : " + str(c))
# 2)write a program to apply islower() and isupper() with different strings.
# im going to use lowercase, uppercase, lower and uppercases, numerical and special keys for two functions
# ----islower()
# case-1 (lowercases)
# In[5]:
str1="bienvenue"
str1.islower()
# case-2 (uppercases)
# In[8]:
str2="BIENVENUE"
str2.islower()
# case-3 (lower and uppercases)
# In[9]:
str3="biENveNue"
str3.islower()
# case-4 (numerical)
# In[12]:
str4="212345"
str4.islower()
# case-5 (lowercase with special keys and number )
# In[14]:
str5="@#$1234bienvenue$$555@@#"
str5.islower()
# ----isupper()
# case-1 (lowercases)
# In[15]:
str1="bienvenue"
str1.isupper()
# case-2 (uppercases)
# In[18]:
str2="BIENVENUE"
str2.isupper()
# case-3(lower and upper cases)
# In[19]:
str3="BiEnVeNUE"
str3.isupper()
# case-4(numerical)
# In[22]:
str4="12345667"
str4.isupper()
# case-5(uppercases with special keys and numbers)
# In[23]:
str5="@@#$$$13245BIENVENUE62787##@@"
str5.isupper()
# In[ ]:
| true |
eb64252481f0ed81477e05e82455d7109655f57f | decareano/python_repo_2019 | /else_if_testing.py | 408 | 4.25 | 4 | people = 30
cars = 40
buses = 15
if cars > people:
print("we should take the cars.")
elif cars < people:
print("we should not take the cars")
else:
print("dont know what to do")
if buses > cars:
print("too many buses")
elif buses < cars:
print("maybe we can take the buses")
else:
print("still cannot decide")
if people > buses:
print("alright, lets take the buses")
else:
print("lets stay home")
| true |
87c9cd1d601d04d104fe23ef0b4e7c1fe18c0c69 | Devil-ReaperL/Trash | /1010/study3/字典.py | 1,238 | 4.34375 | 4 | # 字典: key唯一值 : 若出现重复 前者key对应的值发生改变
# key 唯一 value 随意
#{key1:value1,key2:value,...}
students = {
"name":"张奇",
"age":27,
"sex":"male",
"height":"1.8",
"name":"王齐",
"腰围":27,
}
print(len(students))
for i,j in students.items():
print(i,j)
print(students.items(),type(students.items()))
"""
i= input("key:")
if i in students:
print(students.pop(i)) # pop返回这个key对应的value
else:
print("key 不存在")
"""
students.popitem()
for i in students:
print(i,students[i])
#查看元素的value
print(students["age"])
print(students.get("age1"))
print(students.get("age"))
# 查看所有的key
print("pwd" in students.keys())
# 查看所有的value
print(students.values())
students.update({"a":"b"})
# 替换
#students.update({"age":"18"})
students.setdefault("age1",19)
'''
update&setdefault 添加或者替换
当添加的key在原字典中不存在时,update合并 setdefault添加元素
当添加的key在原字典中存在时:
update 就是替换 参数是字典
setdefault 不发生替换,执行后不改变原字典
'''
print("++++++++++++++")
print(students)
| false |
428d6588af61c4b558a5f6f73187dd27043d3805 | Kulsoom-Mateen/Python-programs | /Calculator.py | 907 | 4.21875 | 4 | num1 = int(input("Enter 1st number : "))
num2 = int(input("Enter 2nd number : "))
operand = input("Enter Operator : ")
if operand == "+":
result = num1 + num2
print(result)
elif operand == "-":
result = num1 - num2
print(result)
elif operand == "*":
result = num1 * num2
print(result)
elif operand == "/":
result = num1 / num2
print(result)
else:
print("Invalid operator")
# num1=int(input("Enter 1st number: "))
# num2=int(input("Enter 2nd number : "))
# opr=input("Enter operand : ")
# if opr=="+":
# print(str(num1) + " + " + str(num2) + " = " + str(num1+num2))
# elif opr=="-":
# print(str(num1) + " - " + str(num2) + " = " + str(num1-num2))
# elif opr=="*":
# print(str(num1) + " * " + str(num2) + " = " + str(num1*num2))
# elif opr=="/":
# print(str(num1) + " / " + str(num2) + " = " + str(num1/num2))
# else:
# print("Invalid operator")
| false |
a0087d82fea425ad005c58521416c1b0b82910ad | Kulsoom-Mateen/Python-programs | /dictionary.py | 1,771 | 4.3125 | 4 | #student=['James',123456789,'ABC','Jones']
# dictionary is represented by curly brackets , every value should be comma separated
student={ #Name,Cell no etc are keys
'Name': 'James',
'Cell Number': 123456789,
#'Cell no.':[123,456] here cell no is list inside a dictionary bcz some students can have more than 1 cell no.
'Area':'ABC',
'Children':[{'CName':'abc','Age':3,'Address':'xyz'},{'CName':'abc','Age':3,'Address':'xyz'}], #dictionary inside a dictionary
'Fathers Name':'Jones'
}
print("Printing keysa and values both")
print(student['Children'][1]['CName'])
for k in student:
print(k,student[k]) #when we traverse on dictionary ,we get keys
print("Printing only values")
for v in student.values(): # this is second method t get values of dictionary
print(v)
print('Name' in student) #returns true if this key(name) is present in dictionary
print('Name1' in student)
print(student['Name']) #print Name key value of student dictionary
student['Name']='James Jack'
print(student['Name'])
student['Module']='Module1' # add one more key/value in dictionary
print(student)
del student['Area'] #delete area key
print(student)
print(student.pop('Cell Number')) #pop key Cell Number
print(student)
students=[]
for i in range(2): #take input for 2 students
student1={}
student1['Name']=input('Enter student name: ')
student1['Father name']=input('Enter father name : ')
student1['Cell no.']=input('Enter cell no. : ')
students.append(student1)
print("Currently enrolled students : ",len(students))
for student1 in students:
print("student")
print(student1)
if student1['Name'].lower()=='jimmy':
print('Yes Jimmy is our student')
| false |
6945f73ee0dd66db503ab0bab31999861cd1c192 | Kulsoom-Mateen/Python-programs | /even_odd.py | 268 | 4.1875 | 4 | '''number=int(input("Enter any number : "))
if number % 2 == 0:
print(str(number) +" is even number")
else:
print(str(number) +" is odd number")'''
num=int(input("Enter any number : "))
if num%2==0:
print("Number is even")
else:
print("Number is odd") | false |
79f4733b669473de0a81c2b90fce55c4d965fcb1 | Kulsoom-Mateen/Python-programs | /abstract_method.py | 608 | 4.15625 | 4 | class Book():
def __init__(self,title,author):
self.title=title
self.author=author
# @abstractmethod
def display(): pass
class MyBook(Book):
def __init__(self,title,author,price):
self.title=title
self.author=author
self.price=price
def display(self):
print("Title:",self.title)
print("Author:",self.author)
print("Price:",self.price)
title=input("Enter title of book : ")
author=input("Enter name of book's author : ")
price=int(input("Enter price of book : "))
new_novel=MyBook(title,author,price)
new_novel.display() | true |
e9649cb521f4196efde0276015cf6dd313084475 | JordanSiem/File_Manipulation_Python | /ExtractAllZipFolders.py | 1,640 | 4.34375 | 4 | import os
import zipfile
print("This executable is used to extract documents from zip folders. A new folder will be created with the zip folder "
"name + 1. This program will process through the folder structure and unzip all zip folders in subdirectories.")
print("")
print("Instructions:")
print("-First, tell the program where you'd like to start the process.")
print('-And as always, please hit "enter" when prompted in order to close and end the program.')
print("")
print("")
start = input("Where to start?")
#Will start traversing through directories/sub directories depending upon where told to start
for (root, dirs, files) in os.walk(start):
#root is file path in all directories/sub
#dirs folders in file path or in directories/sub
#files....listing of files in directories/sub
#os.walk is the command for the traversing
for x in files:
#x = file name
#rebuilding path to file
here = root + '\\' + x
#files that end in zip
if here.endswith('.ZIP') or here.endswith('.zip'):
#I kept getting an error for zip folders already extracted so added try statement to ignore if
#it waa already done.
try:
zip = zipfile.ZipFile(here, 'r')
#make folder
os.mkdir(here + '1')
zipfolder = here + '1'
zip.extractall(path=zipfolder)
except:
print("Ignoring Error: " + x + " was already extracted")
else:
pass
input("Zip files extracted....Have a great day!")
| true |
2dc01f62020a8487c74a689ba41d48c55914f913 | davidkellis/py2rb | /tests/basic/for_in2.py | 539 | 4.375 | 4 | # iterating over a list
print('-- list --')
a = [1,2,3,4,5]
for x in a:
print(x)
# iterating over a tuple
print('-- tuple --')
a = ('cats','dogs','squirrels')
for x in a:
print(x)
# iterating over a dictionary
# sort order in python is undefined, so need to sort the results
# explictly before comparing output
print('-- dict --')
a = {'a':1,'b':2,'c':3 }
keys = []
for x in a:
keys.append(x)
keys.sort()
for k in keys:
print(k)
# iterating over a string
print('-- string --')
a = 'defabc'
for x in a:
print(x)
| true |
daecf43082ccdca104974cb6299a019c74572610 | LukeO1/HackerRankCode | /CrackingTheCodingInterview/MergeSortCountingInversions.py | 1,699 | 4.125 | 4 | #!/bin/python3
"""Count the number of inversions (swaps when A[i] > B[j]) while doing merge sort."""
import sys
#Use global variable to count number of inversions
count = 0
def countInversions(arr):
global count
split(arr)
return count
def split(arr):
#If arr has more than one element, then split
if len(arr) > 1:
mid = len(arr)//2
#print("mid:", mid)
#print("arr", arr)
A = split(arr[0:mid])
B = split(arr[mid:])
#Else return the arr
else:
return arr
#Pass A and B to be merged
return merge(A, B)
def merge(A, B):
global count
#print("A", A)
#print("B", B)
#Initiate pointers to iterate over A and B, and create a new array C where the merged element will go
i = 0
j = 0
C = []
#While pointers not at the end of either A and B compare and merge into new array C
while i < len(A) and j < len(B):
if A[i] <= B[j]:
C.append(A[i])
i += 1
else:
C.append(B[j])
j += 1
# Add up inversions by summing up the remainder elements left in A
count += (len(A) - i)
#If there are still elements in A, add them to C
while i < len(A):
C.append(A[i])
i += 1
#If there are still elements in B, add them to C
while j < len(B):
C.append(B[j])
j += 1
return C
#Function from hackerrank, can substitute for anything else
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = countInversions(arr)
print(result)
| true |
b25c2afc65fc0e03da050bf3362a5cf04474214a | t-christian/Python-practice-projects | /characterInput.py | 2,249 | 4.34375 | 4 | # From http://www.practicepython.org/
# Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
# Stupid library to actually get the date
# TODO: figure out how to properly use datetime
import datetime
# Ask and figure out how old we are
# Only need year, but get exact date for practice
def getcurrentage():
birthyear = input('What year were you born?')
birthmonth = input('What month were you born? (1 to 12)')
birthday = input('What day of the month were you born? (1 to 31)')
# return the three numbers we'll need
return birthyear, birthmonth, birthday
def when100():
#How old are we?
birthyear,birthmonth,birthday = getcurrentage()
# Which day is it? Only call when calculation is run
# In case of weird stuff like running the program
# a few seconds before midnight for best practices
now = datetime.datetime.now()
# Convert everything to a *&^@# string because it wouldn't work otherwise
thisyear = str(now.year)
thismonth = str(now.month)
thisday = str(now.day)
youryear = str(birthyear)
yourmonth = str(birthmonth)
yourday = str(birthday)
year100 = str(int(birthyear) + 100)
# TODO: Figure out exact point in the year in case their birthday has passed.
# TODO: Get amount of days passed in year already?
# TODO: Leap years?
# TODO: Make list of month lengths?
# List of months to convert gibberish to readable english
months = ['January','February','March','April','May','June','July',
'August','September','October','November','December']
#Get month name from list at index minus one (No zero month)
print ('Today is ' + months[int(thismonth)-1] + ' ' + thisday+ ', ' + thisyear)
print ('You were born on ' + months[int(yourmonth)-1] + ' ' + yourday + ', ' + youryear)
#Someone is going to put in a %$#$%@ year, plan ahead
if (int(birthyear) + 100) < int(now.year):
print("You turned 100 in " + year100)
else:
print ("You'll turn 100 in " + year100)
#Start from custom function in case more are added later
def main():
when100()
main()
| true |
7c9ec57ae7dc314826604b9eb864413053023db8 | githubflub/data-structures-and-algorithms | /heap_sort.py | 2,167 | 4.34375 | 4 | ''' 1. Create an unsorted list
2. print the unsorted list
2. sort the list
3. print the sorted list
'''
def main():
myList = [4, 3, 1, 0, 5, 2, 6, 3, 3, 1, 6]
print("HeapSort")
print(" in: " + str(myList))
# sort list
myList = heapSort(myList)
print("out: " + str(myList))
def heapSort(list):
''' First, use the list to create a heap object.
Then, turn the heap into a max heap.
'''
heap = buildHeap(list)
heap = buildMaxHeap(heap)
print("heap.data: " + str(heap.data))
''' First argument of range is inclusive
2nd argument of range is not inclusive
'''
for i in range(len(heap.data)-1, 0, -1):
#print("i is " + str(i))
#print("new heap.data: " + str(heap.data))
heap.data[0], heap.data[i] = heap.data[i], heap.data[0]
heap.heap_size = heap.heap_size -1
heap = maxHeapify(heap, 0)
return heap.data
def buildHeap(list):
return Heap(list)
def buildMaxHeap(heap):
heap.heap_size = len(heap.data)
for i in range(len(heap.data)//2, -1, -1):
''' Why start at //2? Draw any heap you want on a piece of
paper. You will see that all sub trees with a root node
index greater than //2 is already a max heap, because they
are leaves on the tree, so there is no need to
maxHeapify them.
'''
#print("i is " + str(i))
heap = maxHeapify(heap, i)
return heap
def maxHeapify(heap, i):
'''maxHeapify just sorts 3-node-max subtrees.
'''
l = left(i)
r = right(i)
list = heap.data
if ((l < heap.heap_size) and (list[l] > list[i])):
largest = l
else:
largest = i
if (r < heap.heap_size and list[r] > list[largest]):
largest = r
if (largest != i):
list[i], list[largest] = list[largest], list[i]
maxHeapify(heap, largest)
return heap
def left(i):
return 2*i+1
def right(i):
return 2*i+2
def parent(i):
return i//2
class Heap:
def __init__(self, list):
self.heap_size = len(list)
self.data = list
main() | true |
e9e50f5f8f47e36df2d4e5eb562d4adf3f9f061b | Pavan7411/Revising_python | /mf.py | 1,880 | 4.25 | 4 |
def line_without_moving():
import turtle
turtle.forward(20)
turtle.backward(20)
def star_arm():
import turtle
line_without_moving()
turtle.right(360 / 5)
def hexagon():
import turtle #import turtle module for the below code to make sense
x=50 #length of polygon
n=6 #n sided regular polygon
th = 360/n #th is the external angle made by sides
#calculation based on property that external angle sum of convex polygon is 360
for i in range(n): #for loop for drawing a regular polygon
turtle.forward(x)
turtle.left(th)
def tilted_line_without_moving(length,angle):
import turtle
turtle.left(angle)
turtle.forward(length)
turtle.backward(length)
def reg_pol(x,n):
import turtle #import turtle module for the below code to make sense
#x is length of polygon
#n is number of sides of polygon
th = 360/n #th is the external angle made by sides
#calculation based on property that external angle sum of convex polygon is 360
for i in range(n): #for loop for drawing a regular polygon
turtle.forward(x)
turtle.left(th)
def tilted_shapes(tilt,theta): #exercise showing that one can pass functions as arguements as well
import turtle
def move(): #asking for directions and then moving
direction=input("Go left or right?")
import turtle
direction=direction.strip()
direction=direction.lower()
if direction == "left":
turtle.left(60)
turtle.forward(50)
if direction =="right":
turtle.right(60)
turtle.forward(50)
def prison():
import turtle
if turtle.distance(0,0) > 100:
turtle.setheading(turtle.towards(0,0))
turtle.forward(turtle.distance(0,0))
| true |
83b109bf6219348908a8f0e43b2fab2f69348b4e | Pavan7411/Revising_python | /Loop_7.py | 519 | 4.625 | 5 | import turtle #import turtle module for the below code to make sense
turtle.shape("turtle") #changing the shape of the turtle from arrow to turtle
x=10 #size of circle
n=40 #n sided regular polygon
th = 360/n #th is the external angle made by sides
#calculation based on property that external angle sum of convex polygon is 360
for i in range(n): #for loop for drawing a regular polygon
turtle.forward(x)
turtle.left(th)
| true |
73a12e7f11ed70feddd44a4cc22a0129dbf2980d | Pavan7411/Revising_python | /Loop_6.py | 395 | 4.40625 | 4 | import turtle #import turtle module for the below code to make sense
turtle.shape("turtle") #changing the shape of the turtle from arrow to turtle
x=40 #size of square
for j in range(36): #for loop for drawing multiple squares
for i in range(4): #for loop for drawing a square
turtle.forward(x)
turtle.left(90)
turtle.left(10)
| true |
5c88f3c0963bc2ecfa8e0c550567a9d43c018dd1 | spencer-mcguire/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 1,118 | 4.34375 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
# return how many times 'th' exists in a given word
# search through the word, if it has no 'th' return 0
# if it exists, set the index of the first found th and remove it from the word while + 1
# loop until the word is exhausted
# th is case sensitive, disreguard capital
# write conditional to see if the th exists, else return 0
if word.find('th') == -1:
return 0
# else create a new word while leaving out everthing up to and including the first th
# add 2 to the found index and only display the rest of the string from there
exists = word.find('th')
#print(f"exists index:{exists}")
new = word[exists + 2:]
#print(f"new word:{new}")
# call count_th to recursively continue through the given word
# increment by 1 every time the function runs
return count_th(new) + 1
| true |
92b4f6d127a5ab6bd50f08c4c3d7b9c4ed1cc868 | ldorourke/CS-UY-1114 | /O'Rourke_Lucas_Polynomials.py | 1,647 | 4.15625 | 4 | '''
Lucas O'Rourke
Takes a second degree polynomial and prints out its roots
'''
import math
a = int(input("Please enter value of a: "))
b = int(input("Please enter value of b: "))
c = int(input("Please enter value of c: "))
if a is 0 and b is 0 and c is 0:
print("The equation has infinite infinite number of solutions")
elif a is 0 and b is 0:
print("The equation has no real solution")
elif a is 0 and c is 0:
print("The equation has infinite number of solutions")
elif b is 0 and c is 0:
print("The equation has infinite number of solutions")
elif a is 0:
x = (-c/b)
print("The equation has single real solution, x =", x)
elif b is 0:
if c < 0 and a > 0:
x = (abs(c)/abs(a))**0.5
print("The equation has two real solutions, x =", x, "and", -x)
elif c < 0 and a < 0:
print("The equation has no real solution")
elif c > 0 and a > 0:
print("The equation has no real solution")
elif c > 0 and a < 0:
x = (abs(c)/abs(a))**0.5
print("The equation has two real solutions, x =", x, "and", -x)
elif c is 0:
x = -b/a
print("The equation has two real solutions x = 0 and x =", x)
elif a is not 0 and b is not 0 and c is not 0:
if ((b**2) - (4*a*c)) is 0:
x = -b/(2*a)
print("The equation has single real solution, x =", x)
elif ((b**2)-(4*a*c)) < 0:
print("The equation has no real solution")
elif ((b**2)-(4*a*c)) > 0:
x1 = ((-1*b)+((b**2)-(4*a*c))**0.5)/(2*a)
x2 = ((-1*b)-((b**2)-(4*a*c))**0.5)/(2*a)
print("The equation has two real solutions, x =", round(x1, 2)\
, "and", round(x2,2))
| true |
3bd5debd4340abed6b750f405ac83326a3f0a76c | evgenytihonov/Basic_Python | /Lesson_5/Tihonov_Evgeny_dz_5.2.py | 219 | 4.125 | 4 | def odd_num():
upper = 1 + int(input('До какого числа считать нечетные числа? '))
lower = 1
for i in range(lower, upper):
if i % 2:
print(i)
odd_num()
| false |
a2180fb2c112c0f1914f9be93e6cd07c9834a261 | titoeb/python-desing-patterns | /python_design_patterns/factories/abstract_factory.py | 2,253 | 4.53125 | 5 | """The abstract Factory
The abstract factory is a pattern that is can be applied when the object creation becomes too convoluted.
It pushes the object creation in a seperate class."""
from __future__ import annotations
from enum import Enum
from abc import ABC
# The abstract base class.
class HotDrink(ABC):
def consume(self):
pass
class Tea(HotDrink):
def consume(self):
print("This tea is delicious!")
class Coffee(HotDrink):
def consume(self):
print("This coffee is delicious!")
class HotDrinkFactory(ABC):
@staticmethod
def prepare(amount: int):
pass
class TeaFactory:
@staticmethod
def prepare(amount: int):
print("Make tea.")
return Tea()
class CoffeeFactory:
@staticmethod
def prepare(amount: int):
print("Make coffee.")
return Coffee()
def make_drink(drink_type: str):
if drink_type == "tea":
return TeaFactory.prepare(10)
elif drink_type == "coffee":
return CoffeeFactory.prepare(10)
else:
raise AttributeError(f"drink {drink_type} is not known!")
# Great so far, but is the reason for having the abstract base class? Let's see:
class HotDrinkMachine:
class AvailableDrink(Enum):
COFFEE = 1
TEA = 2
factories = []
initiallized = False
def __init__(self) -> None:
if not self.initiallized:
self.initiallized = True
for drink in self.AvailableDrink:
name = drink.name[0] + drink.name[1:].lower()
factory_name = name + "Factory"
factory_instance = eval(factory_name)()
self.factories.append((name, factory_instance))
def make_drink(self):
all_factories = "\n".join(name for name, _ in self.factories)
print(f"Available drinks: {all_factories}")
idx = int(input(f"Please pick a drink (0-{len(self.factories)-1}): "))
amount = int(input("Specify amount: "))
return self.factories[idx][1].prepare(amount)
if __name__ == "__main__":
# entry = input("What kind of drink what you like?")
# drink = make_drink(entry)
# drink.consume()
hot_drink_machine = HotDrinkMachine()
hot_drink_machine.make_drink() | true |
ff7730e47b6d173de3f0c0cf175c543311b149fd | ppesh/SoftUni-Python-Developer | /Python-OOP/02-Classes-and-Instances/02-Circle.py | 467 | 4.3125 | 4 | # 02. Circle
class Circle:
pi = 3.14
def __init__(self, radius):
self.radius = radius
def set_radius(self, new_radius):
self.radius = new_radius
def get_area(self):
area = self.pi * self.radius * self.radius
return area
def get_circumference(self):
circumference = 2 * self.pi * self.radius
return circumference
# Test Code:
"""
circle = Circle(10)
circle.set_radius(12)
print(circle.get_area())
print(circle.get_circumference())
""" | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.