blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2827c8423400bfe3d5c7992fd80d1a8d321dbd9f | pmmorris3/Code-Wars-Solutions | /5-kyu/valid-parentheses/python/solution.py | 471 | 4.25 | 4 | def valid_parentheses(string):
bool = False
open = 0
if len(string) == 0:
return True
for x in string:
if x == "(":
if bool == False and open == 0:
bool = True
open += 1
if x == ")" and bool == True:
if open - 1 == 0:
bool = False
open -= 1
elif x == ")" and (bool == False or open == 0):
return False
return open == 0 | true |
bff81845806f726c9ebf0c35c407076314d711ff | borodasan/python-stady | /duel/1duel/1duel.py | 483 | 4.4375 | 4 | def p(p):
for i in range(0,5,2): #The range() function defaults to increment the sequence by 1,
#however it is possible to specify the increment
#value by adding a third parameter: range(0, 5, 2)
#Assignment operators are used to assign values to variables:
p+=i #p += i --> p = p + i
p-=2 #p -= 2 --> p = p - 2
print(p)
p(2)
print("\nExample Range")
for x in range (0,5,2):
print(x)
| true |
a67e31b47c7be597942229d2f9046e4b7dc4e283 | borodasan/python-stady | /python-collections-arrays/set.py | 1,504 | 4.65625 | 5 | #A set is a collection which is unordered and unindexed.
#In Python sets are written with curly brackets.
print("A set is a collection which is")
print("unordered and unindexed".upper())
print("In Python sets are written with curly brackets.")
#Create a Set
print("Create a Set:")
thisset = {"apple", "banana", "cherry"}
print(thisset)
print("Sets are unordered, so the items will appear in a random order.")
print("You cannot access items in a set by referring to an index,")
print("since sets are unordered the items has no index.")
print("But you can loop through the set items using a")
print("for".upper())
print("loop,")
print("or ask if a specified value is present")
print("in".upper())
print("a set, by using the in keyword.")
print("Loop through the set, and print the values:")
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
print("Check if \"banana\" is present in the set:")
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
print("To add one item to a set use the add() method.")
print("To add more than one item to a set use the update() method.")
print("Add an item to a set, using the add() method:")
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
print("Add multiple items to a set, using the update() method:")
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
thisset = {"apple", "banana", "cherry"}
print(thisset)
x = thisset.pop()
print(x)
print(thisset)
| true |
423736de6e6515f77cec66aefb7941ba34c623ae | shane806/201_Live | /13. More Lists/live.py | 297 | 4.15625 | 4 | matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 1, 2, 3],
[4, 5, 6, 7]]
def create_new_2d_list(height, width):
pass
def main():
# how do I get at the 9?
# how do I loop through the third row?
# how do I loop through the second column?
pass
main()
| true |
5158eedff805fe1a02c30ccc26fbe4027407d813 | untalinfo/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 570 | 4.125 | 4 | #!/usr/bin/python3
"""
Module
"""
def append_after(filename="", search_string="", new_string=""):
"""
Inserts a line of text to a file
Args:
filename (str, optional)
search_string (str, optional) Defaults to "".
new_string (str, optional) Defaults to "".
"""
with open(filename, encoding="UTF8") as f:
string = ""
for line in f:
string += line
if search_string in line:
string += new_string
with open(filename, "w", encoding="UTF8") as f:
f.write(string)
| true |
85eb2ffc8676179e4c6f23062f20a19e0d0a1906 | HATIMj/MyPythonProblems | /Divisor.py | 1,138 | 4.125 | 4 | #DIVISOR OR NOT
try: #trying the below inputs
n=int(input("Enter the total number of apples:--"))#Taking an input of number of apples
mn=int(input("Enter the minimum no. of students:--")) #Taking the input of minimum number of students
mx=int(input("Enter the maximum no. of students:--")) #Taking the input of maximumn number of students
except ValueError: # if there is no integer in an input it will print the below message and exit the program
print("Please Enter only integers")
exit() #Exiting the python file
if mn==mx:
if n%mn==0:print(f"This is not a range. {mn} is a divisor of {n}") #If mn>=mx then it is not a range
else:print(f"This is not a range. {mn} is not a divisor of {n}")
elif mn>mx:
print("This is not a range.")
else:
for i in range(mn,mx+1): #Looping in range
if n%i==0:print(f"{i} is a divisor of {n}") #Condition to check if it is a divisor
elif n%i!=0:print(f"{i} is not a divisor of {n}") #Condition to check if it is not a divisor
else:pass #else pass
| true |
6ea2887ac7d1679ca5663d773c288bbfc38b40cf | emmanuelnyach/python_basics | /algo.py | 818 | 4.25 | 4 | # num1 = input('enter first number: ')
# num2 = input('enter second number: ')
#
# sum = float(num1) + float(num2)
#
# print('the sum of {} and {} is {}'.format(num1, num2, sum))
# finding the largest num in three
#
# a = 8
# b = 4
# c = 6
#
# if (a>b) and (a>c):
# largest=a
# elif (b>a) and (b>c):
# largest=b
# else:
# largest=c
#
# print(largest, " is the largest ")
# sum of natural numbers upto num
# num = 6
#
# if num < 0:
# print('enter positive numbers!')
# else:
# sum = 0
#
# while(num>0):
# sum += num
# num -= 1
# print("the sum is ", sum)
num = int(input('enter number: '))
factorial = 1
if num < 0:
print('sorry, factorial does not exist!')
elif num == 0:
print('the factorial of 0 is 1')
else:
for i in range(1, )
| true |
03d5fa4ff4dece6cb4e00d200257353e66ce478d | elementbound/jamk-script-programming | /week 4/listsum.py | 738 | 4.125 | 4 | # 4-3) list calculation with type detection
#
# calculate sum and average of elements in the list
# ignore all values in the list that are not numbers
#
# initializing the list with the following values
#
# list = [1,2,3,4,5,6,7,8,9,20,30, "aa", "bee", 11, "test", 51, 63]
def is_int(val):
try:
val = int(val)
return True
except ValueError:
return False
def main():
# Initialize list
values = [1,2,3,4,5,6,7,8,9,20,30, "aa", "bee", 11, "test", 51, 63]
# Throw out non-integer values
values = [x for x in values if is_int(x)]
# Display results
print('Sum {0}/{1} and average {2}'.format(sum(values), len(values), sum(values)/len(values)))
if __name__ == '__main__':
main()
| true |
bb510d0b1d3e9b30af489969971b3702c03eaf25 | Steven-Chavez/self-study | /python/introduction/numbers.py | 848 | 4.28125 | 4 | # Author: Steven Chavez
# Email: steven@stevenscode.com
# Date: 9/4/2017
# File: numbers.py
''' Expression is used like most other languages.
you are able to use the operators +, -, *, and /
like you would normally use them. You can also group
the expressions with parentheses ()'''
# addition, subtraction, multiplication
1 + 1 # = 2
4 - 2 # = 2
1 * 2 # = 2
# division always returns a floating point number
# whole numbers are type int decimals (5.3, 3.0) are floats
6 / 5 # = 1.2
# equations using parentheses grouping
(2 + 5) * (40-35) # = 35
# floor division (//)
11 / 2 # = 5.5 normal division
11 // 2 # = 5 floor division gets rid of the fraction
# modulus operator (%) returns the remainder of the division
11 % 2 # = 1
11 % 10 # = 1
23 % 6 # = 5
# power calculations using the (**) operator
3 ** 2 # 3 squared = 9
7 ** 5 # 7 to the power of 5 = 16807 | true |
7fb4ede2dbd7ba97c78af7fa5cedcef8fcbf7baf | rakesh0180/PythonPracties | /TupleEx.py | 506 | 4.21875 | 4 | items = [
("p1", 4),
("p2", 2),
("p3", 5)
]
# def sort_item(item):
# return item[1]
# print(item.sort(key=sort_item))
# print(item)
# using lambada we avoid above two statement
items.sort(key=lambda item: item[1])
print(items)
# map
x = list(map(lambda item: item[1], items))
print("map", x)
# filter
y = list(filter(lambda item: item[1] >= 3, items))
print("filter", y)
# list comphersion
# it is used inside of lambda
filter = [item[1] for item in items]
print("filter", filter)
| true |
7d1d9a1997ec0ad4df02b524784e424cd8a31d95 | devcybiko/DataVizClass | /Week3/RockPaperScissors.py | 812 | 4.125 | 4 | import random
while True:
options = ["r", "p", "s"]
winning_combinations = ["rs", "sp", "pr"]
### for rock, paper, scissors, lizard, spock...
# options = ["r", "p", "s", "l", "x"]
# winning_combinations = ["sp", "pr", "rl", "lx", "xs", "sl", "lp", "px", "xr", "rs"]
user_choice = input(options)
computer_choice = random.choice(options);
if user_choice not in options:
print("bad choice")
continue ### go to top of the while loop
combo = user_choice + computer_choice
if user_choice == computer_choice:
print(f"it's a draw: you both picked {user_choice}\n")
elif combo in winning_combinations:
print(f"You won! {user_choice} beats {computer_choice}\n")
else:
print(f"You lost! {user_choice} loses to {computer_choice}\n")
| true |
62e75902fa73c4b3cf3c0efbbeff4e928cb80119 | BENLINB/Practice-assignment-for-Visual-Studio | /Generate username.py | 536 | 4.125 | 4 | #Problem2
#writing programm that would prompt the username in the format Domain Name-Username.
print("#######################################")
print("WELCOME TO DBS CONSOLE")
print("#######################################")
#asking the user to input his credentials
student=input("enter username")
index= student.index("\\") #preparing an index
student_id=student[:index]
student_name= student[index:][1:]
#printing the result as the seprate combination
print("Domain",student_id)
print("Username",student_name)
| true |
599ecf8e936096c23c02615562f20d5eaf8a2b0e | prince5609/Leet_Code | /Max_Deapth_Binary_Tree.py | 579 | 4.15625 | 4 | # Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes
# along the longest path from the root node down to the farthest leaf node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth_tree(root):
return get_depth(root, 0)
def get_depth(node, max_depth):
if node is None:
return max_depth
else:
return max(get_depth(node.left, max_depth + 1), get_depth(node.right, max_depth + 1))
| true |
a0d4f9f823847403700707ce540fa1b6e7aef386 | Nitin-K-1999/Python_script | /Sample Script 1.py | 504 | 4.34375 | 4 | # A list of cricket team is given below. Print the number of possible matches between each of them. Also print each possible match in the format team1 vs team2.
team_list = ['CSK','RCB','Sun Risers','Deccan Chargers','Mumbai Indians']
matches = []
for index in range(len(team_list)) :
for team in team_list[index+1:] :
matches.append('{} vs {}'.format(team_list[index],team))
print('The number of possible matches is',len(matches))
print('They are :')
for match in matches :
print(match)
| true |
8978220700fcf7ed48d7b0840bebd70696ee3fd8 | VRamazing/UCSanDiego-Specialization | /Assignment 2/fibonacci/fibonacci.py | 359 | 4.15625 | 4 | # Uses python3
# Task. Given an integer n, find the nth Fibonacci number F n .
# Input Format. The input consists of a single integer n.
# Constraints. 0 ≤ n ≤ 45.
def calc_fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
arr=[1,1]
for i in range(2,n):
arr.append(arr[i-1]+arr[i-2])
return arr[n-1]
n = int(input())
print(calc_fib(n))
| true |
077db2a0f5904ba96886cc827b25c8d384e7e1b7 | VRamazing/UCSanDiego-Specialization | /Assignment 3/greedy_algorithms_starter_files/fractional_knapsack/fractional_knapsack.py | 2,169 | 4.15625 | 4 | # Uses python3
import sys
# Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
# Input Format. The first line of the input contains the number n of items and the capacity W of a knapsack.
# The next n lines define the values and weights of the items. The i-th line contains integers v i and w i
#—the value and the weight of i-th item, respectively.
# Constraints : 1 ≤ n ≤ 10 3 , 0 ≤ W ≤ 2 · 10 6 ; 0 ≤ v i ≤ 2 · 10 6 , 0 < w i ≤ 2 · 10 6 for all 1 ≤ i ≤ n.
# All the numbers are integers.
# Output Format : Output the maximal value of fractions of items that fit into the knapsack. The absolute
# value of the difference between the answer of your program and the optimal value should be at most
# 10 −3 . To ensure this, output your answer with at least four digits after the decimal point (otherwise
# your answer, while being computed correctly, can turn out to be wrong because of rounding issues
def get_optimal_value(capacity, weights, values):
value = 0.
valDensity=[]
# Frst Step calculate value density ie list containing ratio of weight per unit weight and sort it in ascending order.
for i in range(len(weights)):
valDensity.append(values[i]/weights[i])
backup=valDensity.copy() #Store Density in backup variable before sorting.
if len(weights) > 1:
valDensity.sort(reverse=True)
#Second Step - Start from element of max value density and try to fit it whole in capacity and if it doesn't take a fraction of it.
totalValue=0
for i in valDensity:
index=backup.index(i)
weight=weights[index]
value=values[index]
if capacity//weight >= 1:
capacity -= weight
totalValue += value
else:
if capacity==0:
break
totalValue += value*capacity/weight
capacity = 0
return totalValue
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:0.5f}".format(opt_value))
| true |
cbeb6a4b06cd9f36bf351c269ca71de0793e2081 | ktandon91/DataStructures | /3. DyPro/rod_price.py | 1,021 | 4.28125 | 4 | """
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n.
Determine the maximum value obtainable by cutting up the rod and selling the pieces.
For example, if length of the rod is 8 and the values of different pieces are given as following,
then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
"""
list2 = [
[1,1],
[2,5],
[3,8],
[4,9],
[5,10],
[6,17],
[7,17],
[8,20]
]
# list2 = [
#
# [1,5],
# [2,5],
# [3,7]
# ]
def recursive_cost(length_of_list):
#Base Case
if length_of_list == 0 :
return 0
cost = list2[length_of_list-1][1] + list2[len(list2)-length_of_list-1][1]
return max(cost,recursive_cost(length_of_list-1))
length_of_list = len(list2)
print(recursive_cost(length_of_list)) | true |
82234bc9ffaa3acb0a0bb64d040ec8e249789414 | iamshubhamsalunkhe/Python | /basics/Continueandbreak.py | 336 | 4.4375 | 4 | #continue is used to skip a iteration and jump back to other iteration
"""
for i in range(1,11,1):
if(i==5):
continue
print(i)
"""
'''
##break is used to break a iteration or stop a iteration at specific point
for i in range(1,11,1):
if(i==5):
continue
if(i==8):
break
print(i)
'''
| true |
d54773b3f32729d8076b34ada3d07c1be629e2b3 | standrewscollege2018/2020-year-13-python-classwork-OmriKepes | /classes and objects python.py | 1,650 | 4.625 | 5 | ''' This program demonstrates how to use classes and objects.'''
class Enemy:
''' The enemy class has life, name, and funcations that do something.'''
def __init__(self, name, life):
'''This funcation runs on instantiation and sets up all attributes.'''
self._life = life
self._name = name
#add the new enemy object to the enemy_list list
enemy_list.append(self)
def get_name(self):
'''This funcation returns the name of the enemy.'''
return(self._name)
def get_life(self):
'''This funcation returns the amount of life remaining.'''
return self._life
def attack(self):
'''This funcation substracts 1 from the object's health.'''
print("Ouch!")
self._life -= 1
def add(self):
print("Increased health!")
self._life+=1
def show_all():
'''This funcation displays details of all enemies in enemy_list.'''
for enemy in enemy_list:
print(enemy.get_name())
def life_check():
'''This funcation asks the user for an integar, and then returns the names of all enemies who have at least that much life left.'''
check = int(input("Enter a number: "))
for enemy in enemy_list:
if enemy.get_life()>= check:
print(enemy.get_name())
def create_enemy():
'''This funcation creates a new enemy with a name and life.'''
new_name = input("Enter new name: ")
new_life = int(input("Enter new life: "))
Enemy(new_name, new_life)
enemy_list.append(new_name, new_life)
# The enemy_list stores all the enemy objects
enemy_list = []
create_enemy()
life_check()
| true |
4873d8070a2d54482d0ea387eb1c901cfba8ef9e | Will-is-Coding/exercism-python | /pangram/pangram.py | 503 | 4.21875 | 4 | import re
def is_pangram(posPangram):
"""Checks if a string is a pangram"""
lenOfAlphabet = 26
"""Use regular expression to remove all non-alphabetic characters"""
pattern = re.compile('[^a-zA-Z]')
"""Put into a set to remove all duplicate letters"""
posPangram = set(pattern.sub('', posPangram).lower())
if len(posPangram) == lenOfAlphabet:
alpha = set('abcdefghijklmnopqrstuvwxyz')
return set(posPangram).issubset(alpha)
else:
return False
| true |
23eb4288c74348e898b5e987f8755ebf2cc2db62 | Liam-Pigott/python_crash_course | /11-Advanced_Python_Modules/defaultdict.py | 769 | 4.15625 | 4 | from collections import defaultdict
# defaultdict is a dictionary-like object which provides all methods provided by a dictionary but takes a first argument (default_factory)
# as a default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method.
# A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
d = {'k1': 1}
print(d['k1']) # 1
#print(d['k2']) # KeyError
d = defaultdict(object)
print(d['one']) # <object object at 0x006F6600>
for item in d:
print(item)
d = defaultdict(lambda : 0)
print(d['one']) # automatically assign 0 using above lambda
d['two'] = 2
print(d) # defaultdict(<function <lambda> at 0x006A7FA0>, {'one': 0, 'two': 2}) | true |
aad7fec002bf6717bb2a7e6389c964ec6344cd4a | Liam-Pigott/python_crash_course | /02-Statements/control_flow.py | 1,768 | 4.15625 | 4 | # if, elif and else
if True:
print("It's True")
else:
print("False")
loc = 'Bank'
if loc == 'Work':
print('Time to work')
elif loc == 'Bank':
print('Money maker')
else:
print("I don't know")
name = 'Liam'
if name == 'Liam':
print("Hello Liam")
elif name == 'Dan':
print('Hi Dan')
else:
print("What's your name?")
# For Loops
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in mylist:
print(num)
for num in mylist:
if (num % 2 == 0):
print(f'Even number: {num}')
else:
print('Odd number: {}'.format(num))
list_sum = 0
for num in mylist:
list_sum = list_sum + num
print(f'The total sum of mylist is {list_sum}')
my_string = 'Hello world'
for letter in my_string:
print(letter)
for _ in my_string:
print('_ is used when there isn\'t any intention to use a variable in the for loop')
mylist = [(1, 2), (3, 4), (5, 6), (7, 8)]
print(len(mylist))
for item in mylist:
print(item)
# tuple unpacking
for a, b in mylist:
print(a)
print(b)
d = {'k1': 1, 'k2': 2, 'k3': 3}
for item in d:
print(item) # only prints keys
for key, value in d.items():
print(value) # prints values
# While loops
x = 0
while x < 5:
print(x)
x += 1
else:
print('x is not less than 5')
# break: breaks out of current enclosing loop
# continue: goes to the top of the closest loop
# pass: does nothing
x = [1, 2, 3]
for item in x:
pass # good as a placeholder to code later and avoid syntax errors
my_string = 'Liam'
for letter in my_string:
if letter == 'a':
continue
print(letter)
my_string = 'Liam'
for letter in my_string:
if letter == 'a':
break
print(letter)
x = 5
while x < 5:
if x == 2:
break
print(x)
x += 1 | true |
6f2d440071bdacdb59adc4409561dfb6b63683d3 | ksannedhi/practice-python-exercises | /Ex11.py | 618 | 4.34375 | 4 | '''Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.).
You can (and should!) use your answer from Exercise 4 to help you. Take this opportunity to practice using functions.'''
def find_prime_or_not(num):
divisors = list(range(1,num+1))
div_list = [div for div in divisors if num%div == 0]
if len(div_list) == 2:
result = "Prime"
else:
result = "Not prime"
return result
user_input = int(input("Please enter a number: "))
print(find_prime_or_not(user_input))
| true |
bbe653b8a4f428b0c7abc5ede7939455abdf2a06 | ksannedhi/practice-python-exercises | /Ex15.py | 532 | 4.4375 | 4 | '''Write a program (using functions!) that asks the user for a long string containing multiple words.
Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My'''
def reverse_words(input_text):
words = input_text.split()
rev_words = words[::-1]
return " ".join(rev_words)
user_input_text = input("Type something: ")
print(f'Reversed output: {reverse_words(user_input_text)}')
| true |
993033a674b3d7a44cc8aacb6f9910d84c8b4531 | pzinz/sep_practice | /22_HarvardX_w01_03.py | 2,199 | 4.25 | 4 | # Static typing mean that the type checking is performed during compile time
# dynamic typing means that the type checking is performed at run time
# Varible, objects and references
# x = 3 ; Python will first create the object 3 and then create the variable X and then finally reference x -> 3
# list defined as followed
l1 = [2,3,4]
print(type(l1))
l2 = l1
print(type(l2))
l1[0] = 24
print(l1)
print(l2)
# Each object in python has a type, value and identity
L = [1,2,3]
M = [1,2,3]
print(L == M)
print(L is M) # Check whether L is the same object as M
# Above will return False
print('ID of L is:', id(L))
print("ID of M", id(M))
print(id(L) == id(M))
# Mutuable objects can be identical in contents yet be different objects
M = list(L)
print(M is L)
M = L[:]
print(M)
aa = 3
bb = aa
bb = bb - 1
print(aa)
LL = [2,3,4]
M1 = LL
M2 = LL[:]
print(M1 is M2)
# COPIES
# shallow copy
# deep copy
import copy
a = [1,[2]]
b = copy.copy(a)
c = copy.deepcopy(a)
print(b is c)
print(b is a)
print("----------")
print(True or False)
if False:
print("False")
elif True:
print("True")
else:
print("Finally")
print("============")
for x in range(10):
print(x)
age = {}
print(type(age))
age = dict()
print(type(age))
age = {"Tim": 29, "Jim": 31, "Pam": 27, "Sam": 39}
age["Tom"] = 50
age["Nick"] = 33
names = age.keys()
print(names)
print(age)
for name in names:
print(name)
print(age.keys())
for name in age.keys():
print(name,age[name])
for name in sorted(age,reverse=True):
print(name,age[name])
bears = {"Grizzly":"angry", "Brown":"friendly", "Polar":"friendly"}
for bear in bears:
if(bears[bear] == "friendly"):
print("Hello, "+bear+" bear!")
else:
print("odd")
print("====")
n = 100
number_of_times = 0
while n >= 1:
n //= 2
number_of_times += 1
print(number_of_times)
is_prime = True
for i in range(2,n):
if n%i == 0:
print(i)
print(is_prime)
numbers = range(10)
squares = []
for num in numbers:
square = num **2
squares.append(square)
print(squares)
squares2 = [number ** 2 for number in numbers]
print(squares2)
for i in range(10):
print(i)
sum(x for x in range(1,10) if x % 2)
print(sum2) | true |
ec68888812b15838438f33bcb97c68e3dac62ba2 | malekhnovich/PycharmProjects | /Chapter5_executing_control/Chapter6_dictionaries/tuple_example.py | 1,336 | 4.59375 | 5 | '''
IF DICTIONARY KEYS MUST BE TYPE IMMUTABLE WHILE LIST TYPE IS MUTABLE
YOU CAN USE A TUPLE
TUPLE CONTAINS A SEQUENCE OF VALUES SEPERATED BY COMMAS AND ENCLOSED IN PARENTHESIS(()) INSTEAD OF BRACKETS([])
'''
#THIS IS A TUPLE BECAUSE THE PARENTHESIS ARE ROUND RATHER THAN SQUARE
#SQUARE PARENTHESIS WOULD BE A LIST
#THE DIFFERENCE BETWEEN THE TWO IS A TUPLE IS IMMUTABLE WHILE A LIST IS MUTABLE
#THIS MEANS THAT A TUPLE'S CONTENTS CAN NOT BE MODIFIED WHILE A LISTS CONTENTS CAN BE MODIFIED
days=('Mo','Tu','We')
print(days)
print(days[0])
#SINCE TUPLES ARE IMMUTABLE THEY CAN BE USED AS KEYS FOR DICTIONARIES
#EXAMPLE OF USING TUPLES FOR THE KEYS IN DICTIONARY CALLED PHONEBOOK
phonebook={('Jason','Bay'):'25',
('David','Wright'):'22',
('Josh','Thole'):'23'}
print(phonebook[(('Jason','Bay'))])
print(phonebook.items())
#IF WE WANTED A ONE ITEM TUPLE WE WOULDNT BE ABLE TO JUST PUT ONE ELEMENT IN THE ROUND PARENTHESIS(())
#THIS IS BECAUSE THE COMPUTER WILL THINK IT IS A STRING OR ANOTHER INSTANCE THAT IS NOT A TUPLE
#IN ORDER TO GET A ONE ITEM TUPLE WE CAN PUT IN OUR SINGLE ITEM FOLLOWED BY A COMMA(,)
day2=('Mo',)#THIS IS THE PROPER EXECUTION OF A ONE ITEM TUPLE
day3=('Mo')#THIS IS THE INCORRECT EXECUTION OF A ONE ITEM TUPLE BECAUSE THE COMPUTER THINKS IT IS A STRING
print(type(day2))
print(type(day3)) | true |
b42ace7c28ad5224af073ba6703128d6f80bfae5 | ses1142000/python-30-days-internship | /day 10 py internship.py | 1,313 | 4.3125 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import re
>>> string = "a-zA-Z0-9"
>>> if re.findall(r'/w',string):
print("the string contains a set of char")
else:
print("the string does not contains a set of char")
the string does not contains a set of char
>>>
>>>
>>> import re
>>> pattern=re.compile('a.?b')
>>> match='aaabcd'
>>> if re.search(pattern,match):
print("found a match")
else:
print("match not found")
found a match
>>>
>>>
>>> import re
>>> test_number = "internship python program"
>>> res = len(re.findall(r'/w+',test_number))
>>> print("check the number at the end of the word is:"+str(res))
check the number at the end of the word is:0
>>>
>>>
>>> import re
>>> results= re.finditer(r"([0-9]{1,3})","exercises number 1,12,13 and 260 are important")
>>> print("number of length 1 to 3")
number of length 1 to 3
>>>
>>> for n in results:
print(n.group(0))
1
12
13
260
>>>
>>>
>>> import re
>>> def match(text):
pattern = '[A-Z]+$'
if re.search(pattern,text):
return('match')
else:
return('match not found')
>>> print(match("ABCDEF"))
match
>>> print(match("GEEKS"))
match
>>> | true |
9e90c8c11d9352283cd731aec48de88038b64f88 | JanusClockwork/LearnPy | /Py3Lessons/python_ex05.py | 1,597 | 4.125 | 4 | name = 'Janus Clockwork' #according to my computer lol
age = 26
height = 65 #inches. Also, why is height spelled like that. I before E except after C? My ass.
weight = 114 #lbs. also I AM GROWIIINNNG
eyes = 'gray' #'Murrican spelling
teeth = 'messed up'
hair = 'brown'
favePet = 'cats'
faveAnime = 'Yowamushi Pedal'
faveBand = 'Radioactive Chicken Heads'
print ("Let's talk about %s." % name)
print ("She's %d inches tall." % height)
print ("That's %d centimeters." % (height * 2.54))
print ("She's %d pounds and still gets knocked over by the wind." % weight)
print ("It's true. That really happened before.")
print ("She's got %s eyes and %s hair." % (eyes, hair))
print ("Her teeth are %s and she drinks too much coffee." % teeth)
print ("%s's favorite pets are %s." % (name, favePet))
print ("Her favorite anime is %r and favorite band is %r." % (faveAnime, faveBand))
#according to the book, this line is tricky... CHALLENGE ACCEPTED
print ("If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight))
#for some reason when I place "%r like that, it adds a space and some single quotes... I wonder why.
#oh, it's cuz %r adds those single quotes. Like, it's meant to place quotes.
#oohh okay:
#s – strings
#d – decimal integers (base-10)
#f – floating point display
#c – character
#b – binary
#o – octal
#x – hexadecimal with lowercase letters after 9
#X – hexadecimal with uppercase letters after 9
#e – exponent notation
#and I'm gonna guess r - literal translation with single quotes
#also Python doesn't belive in comment blocks. Why. Y U liek dis. | true |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.