blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
89a4b8735d13a7a2536d3fa18c80cda5c8b46b68 | cartoonshow57/SmallPythonPrograms | /array_replacement.py | 661 | 4.21875 | 4 | """Given an array of n terms and an integer m, this program modifies
the given array as arr[i] = (arr[i-1]+1) % m and return that array"""
def array_modification(arr1, m1):
test_arr = []
index = 0
for _ in arr1:
s = (arr1[index - 1] + 1) % m1
test_arr.append(s)
index += 1
return test_arr
arr = []
n = eval(input("Enter the number of elements in the array: "))
for j in range(n):
arr.append(eval(input("Enter array element: ")))
m = eval(input("The modulo will be taken with which number? "))
print("The given array is:", arr)
print("The modified array comes out to be:", array_modification(arr, m))
input()
| true |
40247c58ddd68593214c719ac84db9252174b69c | cartoonshow57/SmallPythonPrograms | /first_and_last.py | 431 | 4.1875 | 4 | """This program takes an array
and deletes the first and last element of the array"""
def remove_element(arr1):
del arr1[0]
del arr1[-1]
return arr1
arr = []
n = int(input("Enter number of elements in the list: "))
for i in range(n):
arr.append(int(input("Enter array element: ")))
print("The given list is: ")
print(arr)
print("After removing first and last element: ")
print(remove_element(arr))
input()
| true |
8c841eabc2a03af875f2b7286a86c2e5ac14eae4 | motirase/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/0-add_integer.py~ | 472 | 4.21875 | 4 | #!/usr/bin/python3
"""
function 0-add_integer
adds two integers
"""
def add_integer(a, b=98):
"""adds two numbers
>>> add_integer(4, 3)
7
>>> add_integer(5, 5)
10
"""
fnum = 0
if type(a) is int or type(a) is float:
fnum += int(a)
else:
raise TypeError("a must be an integer")
if type(b) is int or type(b) is float:
fnum += int(b)
else:
raise TypeError("b must be an integer")
return fnum
| true |
fb7d4013fd9394072a043c958e1e35b1ff8f3b63 | Dyke-F/Udacity_DSA_Project1 | /Task4.py | 1,441 | 4.125 | 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 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
def find_telemarketers(data1: list, data2: list):
caller = set()
responder = set()
texter = set()
reciever = set()
for call in data1:
caller.add(call[0])
responder.add(call[1])
for call in data2:
texter.add(call[0])
reciever.add(call[1])
prob_telemarketers = []
RespTextRecieves = set().union(responder, texter, reciever)
for contact in caller:
if contact not in RespTextRecieves:
prob_telemarketers.append(contact)
return sorted(prob_telemarketers)
prob_telemarketers = find_telemarketers(calls, texts)
print("These numbers could be telemarketers:")
for prob_telemarketer in prob_telemarketers:
print(prob_telemarketer)
| true |
d6396e1980649d9fcfbe3e5a50f3fb6f37016731 | aditya-sengupta/misc | /ProjectEuler/Q19.py | 1,067 | 4.21875 | 4 | """You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?"""
def weekday_shift(month, year):
if(month == 2):
if(year%400 == 0 or (year%4 == 0 and year%100 != 0)):
return 1
return 0
if(month in [4, 6, 9, 11]):
return 2
return 3
def first_of_month(month, year):
if(month == 2 and year == 1983):
return 2
elif(month == 1 and year == 1900):
return 1
elif(month > 1):
return (weekday_shift(month - 1, year) + first_of_month(month - 1, year))%7
else:
return (weekday_shift(12, year - 1) + first_of_month(12, year - 1))%7
| true |
5d393e90f23624f1a27ca7af73fa9606e08beaf4 | B3rtje/dataV2-labs | /module-1/Code-Simplicity-Efficiency/your-code/challenge-2_test.py | 1,678 | 4.25 | 4 |
import string
import random
def new_string(length):
letters = string.ascii_lowercase+string.digits
str = ''.join(random.choice(letters) for num in range(length))
return str
#print(get_random_string(10))
def string_gen ():
strings = []
number_of_strings = input("How many strings do you want to generate? ")
minimum_length = input("What is the minimum length that you want? ")
maximum_length = input("What is the max length that you want? ")
while not number_of_strings.isnumeric():
print("We only accept numeric values.")
number_of_strings = input("How many strings do you want to generate?")
while not minimum_length.isnumeric():
print("We only accept numeric values. ")
minimum_length = input("What the minimum length that you want? ")
while not maximum_length.isnumeric():
print("We only accept numeric values. ")
maximum_length = input("What is the max length that you want? ")
number_of_strings = int(number_of_strings)
minimum_length = int(minimum_length)
maximum_length = int(maximum_length)
while True:
if maximum_length < minimum_length:
print("Program reboots because your max is smaller than your minimum")
string_gen()
break
else:
break
final_length = [minimum_length, maximum_length]
final_length = random.choice(final_length)
while number_of_strings > 0:
string = new_string(final_length)
strings.append(string)
number_of_strings = number_of_strings - 1
return strings
print(string_gen())
| true |
486440929bfc62b5fc48823002c695afeacd67bb | sailesh190/pyclass | /mycode/add_book.py | 252 | 4.375 | 4 | address_book = []
for item in range(3):
name = input("Enter your name:")
email = input("Enter your email:")
phone = input("Enter your phone number:")
address_book.append(dict(name=name, email=email, phone=phone))
print(address_book) | true |
405fbc0f2d07a41d15ff248af2e429e45de498e7 | AhmUgEk/tictactoe | /tictactoe_functions.py | 1,974 | 4.125 | 4 | """
TicTacToe game supporting functions.
"""
# Imports:
import random
def display_board(board):
print(f' {board[1]} | {board[2]} | {board[3]} \n-----------\n {board[4]} | {board[5]} | {board[6]}\
\n-----------\n {board[7]} | {board[8]} | {board[9]} \n')
def player_input():
marker = 0
while marker == 0:
choice = str(input('Choose whether to be "X" or "O": ')).upper()
if choice == 'X' or choice == 'O':
marker += 1
else:
print('That choice is not valid.')
return choice
def place_marker(board, marker, position):
board[position] = marker
def win_check(board, mark):
winning_combs = ([1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7])
for comb in winning_combs:
if board[comb[0]] == mark and board[comb[1]] == mark and board[comb[2]] == mark:
return True
else:
continue
def choose_first():
first = random.randint(1, 2)
print(('\n') + (f'Player {first} goes first.\n'))
return first
def space_check(board, position):
return board[position] == ' '
def full_board_check(board):
return ' ' in board
def player_choice(board):
choice = 0
while choice == 0:
try:
pos = int(input('Please choose your next position: '))
if pos >= 1 and pos <= 9:
if space_check(board, pos):
choice += pos
return choice
else:
print('Oops, that space is already taken.\n')
continue
print('That choice is not valid.\n')
continue
except ValueError:
print('That choice is not valid.\n')
continue
def replay():
again = (input('Would you like to go again? Enter "Y" or "N"... ')).lower()
return again == 'y' | true |
8c988bf453d8f1c5bb69272e69e254df77c1b874 | shreeji0312/learning-python | /python-Bootcamp/assignment1/assignment1notes/basicEx2.py | 2,924 | 4.5625 | 5 | # WPCC
# basicEx2.py
# Let's take a look at some different types of data that Python
# knows about:
print(10)
print(3.14)
print("Python is awesome!")
print(True)
# There are 4 fundamental types of data in Python:
# integers, floating point numbers, strings, and booleans
# You can create more types of data, but we'll examine those
# later on.
# You can declare a "variable" like this in Python:
x = 54
# This variable is of the type "int"
# We can see this by running the "type" function:
print(type(x))
# this prints: <class 'int'>
# Python will interpret this variable as an integer number
# We can also make variables of type `float`
y = 5.43
print(type(y)) # <class 'float'>
# This type of data will store fractional numbers
# The next data type is called a string. This data type will hold
# a sequence of characters, and by doing so can store pretty much all
# kinds of different data like names, colors, addresses etc. A string can
# be defined with single quotes ('') or double quotes ("").
# Be careful as strings can also store numbers, and numbers stored
# in string ARE NOT # the same as their equivalent integer or float forms:
a_number = '13' # <class 'str'>
another_number = 13
# NOTE PYTHON DOESN'T SEE THESE VARIABLES AS THE SAME THING.
# One will hold the sequence of characters: '1', and '3'
# The other is the integer representation of the number 13
# Lastly, we have booleans. This type of data can only take on two different
# values: true, or false. When making booleans in Python, you must capitalize
# the first letter: True/False
a_bool = True
another_bool = False
print(type(a_bool)) # <class 'bool'>
# When declaring a variable, you must follow some rules with its name:
# the name may contain lowercase/uppercase letters and as well as numbers,
# but the first character must NOT be a number.
"""
50cent = "the best"
"""
# THIS IS NOT A VALID VARIABLE. (put a "#" on the previous line to run this file)
# but this is:
w20_e3j = True
# Be careful when referring to an existing variable, VARIABLES ARE CASE SENSITIVE
# `variable_with_good_name` IS NOT THE SAME AS `Variable_with_good_name`
print(x)
x = 2.71
# We can reassign the same variable to a different type,
# and Python won't care. In other programming languages,
# this is NOT allowed. But Python doesn't care, it's different!
# Python is smart, and will automatically convert between different
# types if needed. For example, let's try to divide a floating
# point number by an integer
some_number = 10.5
some_other_number = 2
print(some_number / some_other_number)
# The answer is 5.25 (type is `float`). In other languages, the different types
# would not play well together, but as I mentioned before, Python is smart
#########################
# EXERCISE
#########################
# Write a python program that makes a variable of every type mentioned in this file.
# Then print out their values
| true |
46004672cd99417c2bc0027e364ecb4441f1c8f9 | shreeji0312/learning-python | /python-Bootcamp/assignment1/assignment1notes/basicEx6.py | 1,907 | 4.84375 | 5 | # WPCC
# basicEx6.py
# So far we've made our own variables that store
# data that we have defined. Let's look at how we can
# ask the user to enter in data that we can manipulate
# in our program
# We will use the `input` function to ask the user to enter
# some data
user_input = input("Please enter a number: ")
# We must give the input function a string. This string will be displayed
# to the user and wait for the to enter data. Once the user has entered
# the data, the `user_input` variable will take on that value
print(user_input)
# This will print exactly what the user entered. If we print its type:
print(type(user_input))
# We see that it's type is <class 'str'> i.e. a string
# That might be a problem if we want to ask the user for a number:
user_input = input("Please enter your age: ")
"""
print(user_input + 1)
"""
# What happens if we try to add 1 to the user's input?
# We will get an error because Python doesn't know how to add the
# string data type with the integer data type. But we know that `user_input`
# is in fact an integer number. So how can we tell Python that `user_input`
# is an integer?
# We must do something called "type casting." When we cast a variable to a
# different type, we're telling Python to interpret said variable as a
# different type.
# For example, we can cast `user_input` (which is a string) to an integer,
# that way we can do arithmetic operations on it:
x = int(user_input)
# Now `x` will hold the integer interpretation of `user_input` and we may now
# add 1 to it:
print(x + 1)
# We can cast variables to more types:
a = str(user_input)
b = float(user_input)
c = int(user_input)
b = bool(user_input)
#########################
# EXERCISE
#########################
# Write a program that asks the user to enter their birth month,
# birth day, and birth year into separate variables.
# Then output the sum of all three values.
| true |
6c4c8561cb46045307cf14a1481f97b3e63c1af8 | shreeji0312/learning-python | /python-Bootcamp/assignment5/assignment5notes/2dlistEx1.py | 2,000 | 4.71875 | 5 | # WPCC
# 2dlistEx1.py
# We're going to look at what a 2D list is.
# A 2D list is a list that contains other lists.
# For example:
marks = [ [90, 85, 88], [68, 73, 79] ]
# The list `marks` contains 2 other lists, each containing
# integers. We would say that this list is of size 2x3:
# two lists, each containing 3 elements
print(len(marks)) # This will print how many lists are in `marks`
print(len(marks[0])) # This will print how many elements are in the first list inside `marks`
# So why would we want to create something like this?
# In some problems, we need to model something like a grid
# or board that requires 2 coordinates or 2 indices. For example,
# in a game of chess a piece's location is represented with 2 values:
# a row position and a column position. We can model a chess board using
# a 2D list
board = [
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
]
# The `board` list contains 8 other lists, each containing 8 numbers. (8x8)
# This above list has a 1 in the first list at the sixth index.
# The way we would access that element is by first taking the index of the
# list, then the index of the element inside of that list.
# So to get the 7th element in the 1st list:
print( board[0][6] ) # This will print `1`
# Notice that each list the same length. In Python, it's not necessary to keep
# all lists the same length, but it's definitely easier (as we've seen before, Python
# can work with different kinds of data). In other programming languages,
# making a 2D list with different list sizes would not be possible.
#########################
# EXERCISE
#########################
# Write a Python program that creates a 3x3 2D list of ints.
# Then print out the middle element i.e. The element in the 2nd list, at the 2nd spot
| true |
291d09272a542e9b24fab373d154466f9d1b0c30 | shreeji0312/learning-python | /python-Bootcamp/assignment4/assignment4notes/functionEx2.py | 1,611 | 4.84375 | 5 | # WPCC
# functionEx2.py
# When we call some Python standard functions, it gives us back
# a value that we can assign to a variable and use later in our programs.
# For example:
import random
randomNumber = random.randint(0, 10)
# This function will return the value it generates so we can assign its
# value to `randomNumber`
# So how can we do that in our own functions:
# Let's take a look at the function from the last note:
'''
def myAddFunction(a, b):
print("The sum is", a + b)
'''
# This function will add the numbers, but we can't use it later in our
# program
'''
sum = myAddFunction(10, 5)
'''
# This will not give us the expected 15. `myAddFunction` will only print the sum,
# not return it
# So we can modify this function to return the value instead.
def myAddFunction(a, b):
return a+b
theSum = myAddFunction(10, 20)
print(theSum)
# Our function now "returns" the value instead of printing it.
# This means that during runtime, the function call will take on the value
# that is returned:
# This is what it would look like behind the scenes:
'''
theSum = myAddFunction(10, 20)
theSum = .... compute
theSum = 20
'''
# Note: when a function reaches a `return` statement, it will terminate the whole
# function. For example:
def exFunc():
return True
print("PRINT ME PLS!!")
exFunc()
# The print will never happen because the function will have terminated
# at the return statement
#########################
# EXERCISE
#########################
# Write a function called `letterGrade()` that will take in
# a grade (integer) and return the appropriate letter grade
| true |
20656a0b0704de6339feab22f2a2a4d539cda92f | fantasylsc/LeetCode | /Algorithm/Python/75/0056_Merge_Intervals.py | 977 | 4.15625 | 4 | '''
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
'''
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
res = []
intervals.sort()
res.append(intervals[0])
for item in intervals[1:]:
if res[-1][1] >= item[0]:
res[-1][1] = max(res[-1][1], item[1])
else:
res.append(item)
return res
| true |
a312e0acb76d0747602ccf4c39d799a3c814c30c | fantasylsc/LeetCode | /Algorithm/Python/1025/1007_Minimum_Domino_Rotations_For_Equal_Row.py | 2,473 | 4.1875 | 4 | '''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return -1.
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
Note:
1 <= A[i], B[i] <= 6
2 <= A.length == B.length <= 20000
'''
# greedy approach
# notice that if the job can be done, all A or B should be A[0] or B[0]
class Solution:
def minDominoRotations(self, A: List[int], B: List[int]) -> int:
def check(x):
rotations_a = rotations_b = 0
for i in range(n):
if A[i] != x and B[i] != x:
return -1
elif A[i] != x:
rotations_a += 1
elif B[i] != x:
rotations_b += 1
return min(rotations_a, rotations_b)
n = len(A)
rotations = check(A[0])
if rotations != -1:
return rotations
else:
return check(B[0])
# backtracking
# TLE
# class Solution:
# def minDominoRotations(self, A: List[int], B: List[int]) -> int:
# self.res = float('inf')
# rotation = self.backtrack(A[:], B[:], 0, 0)
# if self.res != float('inf'):
# return self.res
# else:
# return -1
# def backtrack(self, A, B, start, rotation):
# if len(set(A[:])) == 1 or len(set(B[:])) == 1:
# self.res = min(self.res, rotation)
# return
# for i in range(start, len(A)):
# A[i], B[i] = B[i], A[i]
# rotation += 1
# self.backtrack(A[:], B[:], start + 1, rotation)
# A[i], B[i] = B[i], A[i]
# rotation -= 1
| true |
a18260a2c70db8afa8c17a910f0ea09a4d1802b1 | fantasylsc/LeetCode | /Algorithm/Python/100/0079_Word_Search.py | 2,907 | 4.15625 | 4 | '''
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
Constraints:
board and word consists only of lowercase and uppercase English letters.
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
'''
'''
1. loop to choose start point
2. backtrack recursion end condition
3. check current status, boundary, board[row][col] == suffix[0]
4. mark visited point
5. loop through four directions for backtracking
6. recover the change (backtrack)
a little more complex than regular backtrack problems
'''
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
self.ROWS = len(board)
self.COLS = len(board[0])
self.board = board
# start recursion from every position
for row in range(self.ROWS):
for col in range(self.COLS):
if self.backtrack(row, col, word):
return True
# no match found after all exploration
return False
def backtrack(self, row, col, suffix):
# bottom case: we find match for each letter in the word
if len(suffix) == 0:
return True
# Check the current status, before jumping into backtracking
# row or col out of range or self.board[row][col] != suffix[0]
if row < 0 or row == self.ROWS or col < 0 or col == self.COLS \
or self.board[row][col] != suffix[0]:
return False
# self.board[row][col] == suffix[0]
ret = False
# mark the choice before exploring further.
self.board[row][col] = '#'
# explore the 4 neighbor directions
for rowOffset, colOffset in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
ret = self.backtrack(row + rowOffset, col + colOffset, suffix[1:])
# break instead of return directly to do some cleanup afterwards
if ret: break
'''
# sudden-death return, no cleanup.
if self.backtrack(row + rowOffset, col + colOffset, suffix[1:]):
return True
'''
# revert the change, a clean slate and no side-effect
self.board[row][col] = suffix[0]
# Tried all directions, and did not find any match
return ret
| true |
955c1c68bdd8c6c869585f98009b603eb3938d28 | amirhosseinghdv/python-class | /Ex4_Amirhossein Ghadiri.py | 1,617 | 4.1875 | 4 | """#Ex12
num1=int(input("addad avval?"))
num2=int(input("addad dovvom?"))
if num1 >= num2:
print(num2)
print(num1)
else:
print(num1)
print(num2)
"""
"""#13:
num=int(input("please enter a number lower than 20: "))
if num >= 20:
print("Too high")
else:
print("Thank you")
"""
"""#14:
num=int(input("Enter a number between 10 and 20(inclusive: "))
if 10<= num <=20:
print("Thank you")
else:
print("Incorrect answer")
"""
"""#15:
color=input("Enter your favorite color: ")
if color == "red" or color == "Red" or color == "RED":
print("I like red too.")
else:
print("I don't like " +color+ ", i prefer red.")
"""
"""#16:
q1=input("Is it raining?")
Q1=q1.lower()
if Q1 == "yes":
q2=input("Is it windy?")
Q2=q2.lower()
if Q2 == "yes":
print("It is too windy for an umbrella.")
else:
print("Take an umbrella.")
else:
print("Enjoy your day.")
"""
"""#17:
age=float(input("Your age?"))
if age >= 18:
print("You can vote.")
elif age >= 17:
print("You can learn to drive.")
elif age >= 16:
print("You can buy a lottery ticket.")
else:
print("You can go Trick-or-Treating.")
"""
"""#18:
num=float(input("Enter a number: "))
if num < 10:
print("Too low.")
elif num > 20:
print("Too high.")
else:
print("Correct.")
"""
"""#19:
num=float(input("Enter 1, 2 or 3: "))
if num == 1:
print("Thank you.")
elif num == 2:
print("Well done.")
elif num == 3:
print("Correct.")
else:
print("Error message.")
"""
| true |
07d431c2473e33a00b597bc6412af322f116abab | AnumaThakuri/pythonassignment | /assignment4/question 1.py | 310 | 4.28125 | 4 | #average marks of five inputted marks:
marks1=int(input("enter the marks 1:"))
marks2=int(input("enter the marks 2:"))
marks3=int(input("enter the marks 3:"))
marks4=int(input("enter the marks 4:"))
marks5=int(input("enter the marks 5:"))
sum=marks1+marks2+marks3+marks4+marks5
avg=sum/5
print("average=",avg)
| true |
e343ff42820c7d794248635ec646eb8d4b184181 | lxiong515/Module13 | /GuessGame/topic1.py | 2,385 | 4.15625 | 4 | """
Program: number_guess.py
Author: Luke Xiong
Date: 07/18/2020
This program will have a set of buttons for users to select a number guess
"""
import tkinter as tk
from random import randrange
from tkinter import messagebox
window = tk.Tk()
window.title("Guessing Game")
label_intro = tk.Label(window, text = "Guess a number from 0 to 9")
label_instruct = tk.Label(window, text = "Click a button below!")
label_guess = tk.Label(window, text="Your Guesses: ")
# create the buttons
buttons = []
for index in range(0, 10):
button = tk.Button(window, text=index, command=lambda index=index : process(index), state=tk.DISABLED)
buttons.append(button)
btnStartGameList = []
for index in range(0, 1):
btnStartGame = tk.Button(window, text="Start Game", command=lambda : startgame(index))
btnStartGameList.append(btnStartGame)
# grid
label_intro.grid(row=0, column=0, columnspan=5)
label_instruct.grid(row=2, column=0, columnspan=3)
label_guess.grid(row=4, column=0, columnspan=5)
for row in range(0, 2):
for col in range(0, 5):
i = row * 5 + col # convert 2d index to 1d. 5= total number of columns
buttons[i].grid(row=row+10, column=col)
btnStartGameList[0].grid(row=13, column=0, columnspan=5)
guess = 0
secretNumber = randrange(10)
print(secretNumber)
guess_row = 4
# reset all variables
def init():
global buttons, guess, totalNumberOfGuesses, secretNumber, guess_list, guess_row
secretNumber = randrange(10)
print(secretNumber)
guess_row = 4
guess_list = []
def process(i):
global totalNumberOfGuesses, buttons, guess_row, guess_list
guess = i
guess_list=[]
if guess == secretNumber:
messagebox.showinfo(title="Congratulations!", message="That's the correct number!")
for b in buttons:
b["state"] = tk.DISABLED
else:
#save the guess to a list
guess_list.append(i)
#print the list to verify it is passing the number
#print(guess_list)
#need to display the guess_list!!! but how?
buttons[i]["state"] = tk.DISABLED
status = "none"
def startgame(i):
global status
for b in buttons:
b["state"] = tk.NORMAL
if status == "none":
status = "started"
btnStartGameList[i]["text"] = "Retart Game"
else:
status = "restarted"
init()
print("Game started")
window.mainloop()
| true |
a970f1be719d68082548cf222aeff5beaea5da64 | cyan33/leetcode | /677-map-sum-pairs/map-sum-pairs.py | 1,235 | 4.15625 | 4 | # -*- coding:utf-8 -*-
#
# Implement a MapSum class with insert, and sum methods.
#
#
#
# For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.
#
#
#
# For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix.
#
#
# Example 1:
#
# Input: insert("apple", 3), Output: Null
# Input: sum("ap"), Output: 3
# Input: insert("app", 2), Output: Null
# Input: sum("ap"), Output: 5
#
class TrieNode():
def __init__(self, count = 0):
self.count = count
self.children = {}
class MapSum(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.map = {}
def insert(self, key, val):
self.map[key] = val
def sum(self, prefix):
return sum([val for k, val in self.map.items() if k.startswith(prefix)])
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)
| true |
f7eb0bfd643b4d386350d8a220d768d734e2041b | vaibhavranjith/Heraizen_Training | /Assignment1/Q8.py | 354 | 4.25 | 4 |
#registration problem (register only people above the age 18)
name=input("Enter the name: \n")
mbno=int(input("Enter the mobile number:\n"))
age=int(input("Enter the age:\n"))
if age<=18:
print("Sorry! You need to be at least 18 years old to get membership.")
else :
print(f"Congratulations {name} for your successful registration.")
| true |
bb3b04baf74550ea0cc12ff62e717d90fc2ceca7 | hack-e-d/Rainfall_precipitation | /Script/prediction_analysis.py | 1,567 | 4.5 | 4 | # importing libraries
import pandas as pd
import numpy as np
import sklearn as sk
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# read the cleaned data
data = pd.read_csv("austin_final.csv")
# the features or the 'x' values of the data
# these columns are used to train the model
# the last column, i.e, precipitation column
# will serve as the label
X = data.drop(['PrecipitationSumInches'], axis = 1)
# the output or the label.
Y = data['PrecipitationSumInches']
# reshaping it into a 2-D vector
Y = Y.values.reshape(-1, 1)
# consider a random day in the dataset
# we shall plot a graph and observe this
# day
day_index = 798
days = [i for i in range(Y.size)]
# initialize a linear regression classifier
clf = LinearRegression()
# train the classifier with our
# input data.
clf.fit(X, Y)
# plot a graph of the precipitation levels
# versus the total number of days.
# one day, which is in red, is
# tracked here. It has a precipitation
# of approx. 2 inches.
print("the precipitation trend graph: ")
plt.scatter(days, Y, color = 'g')
plt.scatter(days[day_index], Y[day_index], color ='r')
plt.title("Precipitation level")
plt.xlabel("Days")
plt.ylabel("Precipitation in inches")
plt.show()
inpt=[]
inpt=input("enter the input").split()
for i in range(len(inpt)):
inpt[i]=float(inpt[i])
print(inpt)
inpt=np.array(inpt)
inpt = inpt.reshape(1, -1)
print('The precipitation in inches for the input is:', clf.predict(inpt))
| true |
e3187b055b6db5a497b94602820ac86b8671e637 | rajagoah/Tableua_rep | /EmployeeAttritionDataExploration.py | 2,105 | 4.125 | 4 | import pandas as pd
df = pd.read_csv("/Users/aakarsh.rajagopalan/Personal documents/Datasets for tableau/Tableau project dataset/WA_Fn-UseC_-HR-Employee-Attrition.csv")
#printing the names of the columns
print("names of the columns are:")
print(df[:0])
#checking if there are nulls in the data
#note that in pandas documentation the NULL or NaN data is called as Missing data
"""While checking for NULL values in a dataframe, we use the isnull() function on the data frame.
If we want to check if there are 'any' missing values, then we use the chained function isnull().any()
If we want to retrieve the count of missing values across the entire data frame, we need to use the chained function, isnull().sum().sum()
Note: in isnull().sum().sum() --> the first chained sum() is going to give the number of missing values in each row in dataframe.
the second sum() will add the values returned by the previous sum() function"""
print('\n***************checking for null values in the data frame***************\n')
if df.isnull().sum().sum() == 0:
print('NO NULLS')
else:
print(df.isnull().sum().sum())
#Exploring the data
#Age of employee who are considered Attrition=Yes
df_attrition_yes = df[df['Attrition'] =='Yes']
print(df_attrition_yes[['Age']].mean())
#analyzing relationship between age and years at company
print(df_attrition_yes[['Age','YearsAtCompany']].head(10))
#checking the number of records in the data frame for Attrition = yes
print('The number of rows are: ',len(df_attrition_yes.index))
"""the same can be done using the following code"""
print('The number of rows are: ',df_attrition_yes.shape)
print('The number of rows are: ',df_attrition_yes['Age'].count())
#exploring the environmentSatisfaction and JobSatisfaction
print(df_attrition_yes[['EnvironmentSatisfaction','JobSatisfaction']])
#exploring performance rate
print(df_attrition_yes[['PerformanceRating']].min(), df_attrition_yes[['PerformanceRating']].max())
#exploring years since last promotion
print(df_attrition_yes[['YearsSinceLastPromotion']].min(),df_attrition_yes[['YearsSinceLastPromotion']].max()) | true |
2c25567847813a6b87ab0952612e89fad3123b66 | EGleason217/python_stack | /_python/python_fundamentals/course_work.py | 1,988 | 4.25 | 4 | print("Hello World!")
x = "Hello Python"
print(x)
y = 42
print(y)
print("this is a sample string")
name = "Zen"
print("My name is", name)
name = "Zen"
print("My name is " + name)
first_name = "Zen"
last_name = "Coder"
age = 27
print(f"My name is {first_name} {last_name} and I am {age} years old.")
first_name = "Zen"
last_name = "Coder"
age = 27
print("My name is {} {} and I am {} years old.".format(first_name, last_name, age))
# output: My name is Zen Coder and I am 27 years old.
print("My name is {} {} and I am {} years old.".format(age, first_name, last_name))
# output: My name is 27 Zen and I am Coder years old.
x = "hello world"
print(x.title())
#tuples
dog = ('Bruce', 'cocker spaniel', 19, False)
print(dog[0]) # output: Bruce
dog[1] = 'dachshund' # ERROR: cannot be modified ('tuple' object does not support item assignment)
#lists
empty_list = []
ninjas = ['Rozen', 'KB', 'Oliver']
print(ninjas[2]) # output: Oliver
ninjas[0] = 'Francis'
ninjas.append('Michael')
print(ninjas) # output: ['Francis', 'KB', 'Oliver', 'Michael']
ninjas.pop()
print(ninjas) # output: ['Francis', 'KB', 'Oliver']
ninjas.popcopy(1)
print(ninjas) # output: ['Francis', 'Olive
#dictionaries
empty_dict = {}
new_person = {'name': 'John', 'age': 38, 'weight': 160.2, 'has_glasses': False}
new_person['name'] = 'Jack' # updates if the key exists
new_person['hobbies'] = ['climbing', 'coding'] # adds a key-value pair if the key doesn't exist
print(new_person)
# output: {'name': 'Jack', 'age': 38, 'weight': 160.2, 'has_glasses': False, 'hobbies': ['climbing', 'coding']}
w = new_person.pop('weight') # removes the specified key and returns the value
print(w) # output: 160.2
print(new_person)
# output: {'name': 'Jack', 'age': 38, 'has_glasses': False, 'hobbies': ['climbing', 'coding']}
print("Hello" + 42) # output: TypeError
print("Hello" + str(42)) # output: Hello 42
total = 35
user_val = "26"
total = total + user_val # output: TypeError
total = total + int(user_val) # total will be 61 | true |
cdf54f108bf8e4d7b26613b3d6ac3dcac3083157 | ColorfulCodes/ATM | /ATM .py | 1,073 | 4.15625 | 4 | # We will be creating a bank account
class BankAccount(object):
balance = 0
def __init__(self, name):
self.name = name
def __repr__(self):
return "This account belongs to %s and has a balance of %.2f dollars." % (self.name, self.balance)
def show_balance(self):
print "Your balance is: $%.2f." % (self.balance)
def deposit(self, amount):
if amount <= 0:
print "Sorry, but you're broke."
return
else:
print "You have a total of %s." % (amount)
self.balance += amount
self.show_balance()
def withdraw(self,amount):
if amount > self.balance:
print "Invalid. Try again."
return
else:
print " The user is drawing $%.2f." % (amount)
self.balance -= amount
self.show_balance()
my_account = BankAccount("Jazmeen")
print my_account
my_account.show_balance
my_account.deposit(2000)
my_account.withdraw(1000)
print my_account
| true |
dde5c4982b3a03e1c44d086a5a86924d91e83b1b | kylejablonski/Python-Learning | /conditionals.py | 786 | 4.46875 | 4 | print("Hello, World! This is a conditionals program test.")
# prompts for a value and checks if its more or less than 100
maxValue = int(input("Please enter a value: "))
if maxValue > 100:
print("The max value of {0} is greater than 100!".format(maxValue))
elif maxValue < 100:
print("The max value of {0} is less than 100!".format(maxValue))
else:
print("Looks like the value you entered is not a max value!")
# grabs user input and using an expression to determine what to print
firstName = input("Now enter your first name: ")
firstName = firstName if firstName == 'Bill' else 'That was not a name'
print("Wow coolname, {0}".format(firstName))
if not len(firstName) > 10:
print("that is a medium size name")
else:
print("Whoa shorty, that name is not long.")
| true |
33de7e691ca65a230c76d269d1ae6f5a9e6647eb | Lonabean98/pands-problem-sheet | /es.py | 812 | 4.40625 | 4 | #This program reads in a text
#file and outputs the number of e's it contains.
#It can also take the filename from an argument on the command line.
#Author: Lonan Keane
#The sys module provides functions and variables used to
# manipulate different parts of the Python runtime environment.
import sys
# sys.argv returns a list of command line arguments
# passed to a Python script.
filename= sys.argv[1]
#opening the argument as f
with open(filename) as f:
#reads all the text from a file into a string.
x=f.read()
#This is the start of the e count
e_count= 0
#looping through every character in the file
for letter in x:
if letter =='e' or letter== 'E':
# if the letter is e or E, add one to the e count
e_count += 1
#print the final e count
print(e_count) | true |
028ef354ab87048c660f7c74c1d117f43b23b757 | elimbaum/euler | /002/002.py | 411 | 4.21875 | 4 | #! /usr/bin/env python3.3
"""
Project Euler problem 002
Even Fibonacci Numbers
by Eli Baum
14 April 2013
"""
print("Project Euler problem 002")
print("Even Fibonacci Numbers")
n = int(input("Upper Limit: "))
# Brute-Force calculate all of the fibonacci numbers
a, b = 0, 1
sum = 0
while True:
a, b = a + b, a
if a > n:
break # We have reached the upper limit; stop
if a % 2:
sum += a
print(sum) | true |
1f341dec6a19daad68ae3cd636a1d395d1c539dd | elimbaum/euler | /003/003.py | 687 | 4.25 | 4 | #! /usr/bin/env python3.3
"""
Project Euler problem 003
Largest Prime Factor
by Eli Baum
14 April 2013
"""
from math import *
print("Project Euler problem 003")
print("Largest Prime Factor")
n = float(input("n = "))
"""
We only need to find ONE prime factor.
Then we can divide, and factor that smaller number.
"""
largestPrime = 0
factored = False
while not factored:
upperLimit = floor(sqrt(n)) # We only need to check up to sqrt(n)
for i in range(2, upperLimit):
factored = True # If no more factors are found, while loop stops.
if not (n % i):
n /= i
factored = False
if i > largestPrime: # Add the highscore!
largestPrime = i
break
print(int(n)) | true |
e05d23b8f68f0fcf422ce4a91f5aed4fdfa7630c | samiatunivr/NLPMLprojects | /linearRegression.py | 1,821 | 4.53125 | 5 | __author__ = 'samipc'
from numpy import loadtxt
def linearRegression(x_samples, y_labels):
length = len(x_samples)
sum_x = sum(x_samples)
sum_y = sum(y_labels)
sum_x_squared = sum(map(lambda a: a * a, x_samples))
sum_of_products = sum([x_samples[i] * y_labels[i] for i in range(length)])
a = (sum_of_products - (sum_x * sum_y) / length) / (sum_x_squared - ((sum_x ** 2) / length))
b = (sum_y - a * sum_x) / length
return a, b
# lets work on one typical example example used of linear regression(our data file has two columns: column 1 represent the
# population of a city and column two represents a profit of a shop in the city) so we our goal is to find the relationship between these
# vairabiles in order to find out which city we will be sitting our business. So our objective function is is given as h(x) = lamda_t*x;
# the lamada is the parameter of our model, and we seek to minimize the cost fuction which
#can be done using different algorithms but commonly we use gredient descent algorithm.
# here is just a simple linear regression applying the function in wikipedia (works with two variables but if we want to work with multiple variabiles
# we need to do these steps:
# substact the mean of each feature from the entire data sets X= is dataset, m_i = mean(X(:,i)) i a samples,
# divid the feature values by the std deviation to understand how these features are deviated. X(:,i)-m_i/s_i, we will have a (normalized features)
#Load the dataset
toy_data_business = loadtxt('data.txt', delimiter=',')
x = toy_data_business[:, 0]
y = toy_data_business[:, 1]
print linearRegression(x, y) # https://en.wikipedia.org/wiki/Linear_regression
output = (1.1930336441895988, -3.8957808783119017) # W are loosing (our profite is decreasing if open a shop in this region)
| true |
91f974b6597229fe3904f31e9ebc98b52e966a5d | timfornell/PythonTricksDigitalToolkit | /Lesson4.py | 514 | 4.25 | 4 | """
Lesson 4: Implicit returns
"""
# Python will automatically return None, all following functions will return the same value
def foo1(value):
if value:
return value
else:
return None
def foo2(value):
""" Bare return statement implies 'return None'"""
if value:
return value
else:
return
def foo3(value):
""" Missing return statement implies 'return None'"""
if value:
return value
print(foo1(False))
print(foo2(False))
print(foo3(False))
| true |
5d54fac367fd107da96dbebc34f99ffa55188742 | geeta-kriselva/python_excercise | /Prime_number.py | 599 | 4.125 | 4 | # Checking, if user input number is prime a number. if not printing all the facors.
n= input("Enter the number: ")
try:
num = int(n)
except:
print("Enter only integer number")
quit()
if num > 1:
factor = []
a = 0
for i in range(2,num+1):
if (num % i) == 0:
factor.insert(a,i)
a = a + 1
#if len(factor) <= 1:
#print(num, "is a prime number")
else:
print(num, "is not a prime number")
for i in range (len(factor)):
print("The factor is: ", factor[i])
else:
print(num, "is a prime number")
| true |
bee70d6fa16e25998f08830db5669e8b260e93d7 | DriesDD/python-workshop | /Examples/guess.py | 1,237 | 4.21875 | 4 | """
This uses the random module: https://www.w3schools.com/python/module_random.asp
Exercises:
1. Can you make it a number between one and 100? Give more hints depending on whether the player is close or not? And change the number of guesses that the player can make?
2. Can you make the game into a function called startgame(difficulty) which starts a game and accepts the game difficulty as a parameter?
3. What do {0} and {1} do in the final lines of the program? How else could you write this?
4. How would you go about adding a computer opponent which also takes turns guessing?
"""
import random
guesses_made = 0
name = input('Hello! What is your name?\n')
number = random.randint(1, 20)
print ('Well, ' + name + ', I am thinking of a number between 1 and 20 (inclusive).')
while guesses_made < 6:
guess = int(input('Take a guess: '))
guesses_made += 1
if guess < number:
print ('Your guess is too low.')
if guess > number:
print ('Your guess is too high.')
if guess == number:
break
if guess == number:
print ('Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made))
else:
print ('Nope. The number I was thinking of was {0}'.format(number)) | true |
554f0ccf1ca0bd3bd7da513e690f74fa1f170f4e | Rockforge/python_training | /exercise17.py | 321 | 4.15625 | 4 | # exercise17.py
# Data type: tuple
denominations = ('pesos', 'centavos')
# denominations = ('pesos',) # this should be the syntax for one element tuples
print(denominations)
print(type(denominations))
print(denominations[1])
print('--- Entering loop ---')
for denomination in denominations:
print(denomination)
| true |
8e5c4b8fbcf49eb02931a653bbbba9d49be94611 | tazi337/smartninjacourse | /Class2_Python3/example_00630_secret_number_exercise_1.py | 771 | 4.21875 | 4 | # Modify the secret number game code below such
# that it shows the number of attempts
# after each failed attempt
# Modify the secret number game code below such
# that it shows the number of attempts
# after each failed attempt
secret = "1"
counter = 5
while counter > 0:
counter -= 1
guess = input("guess the number")
if guess == secret:
print("yes, the guess was right!")
else:
print(f"Sorry, thats not correct. Number of further guesses: {counter}")
else:
print("game over")
secret = "10"
counter = 0
while counter < 5:
guess = input("Guess the secret number")
counter += 1
if guess == secret:
print("You won!")
break
else:
print("Try again!")
else:
print("Game Over")
| true |
dae58627d930502a1a950949637285e6a1275921 | mjftw/design-patterns | /example-design-patterns/iterator/iterator_example.py | 240 | 4.40625 | 4 | '''Trivially simple iterator example - python makes this very easy!'''
def main():
a = 'a'
b = 'b'
c = 'c'
iterable = [a, b, c]
for element in iterable:
print(element)
if __name__ == '__main__':
main()
| true |
d0a2a502929ec839607ab88eb4fa6eca97141342 | jkoppel/QuixBugs | /python_programs/sqrt.py | 420 | 4.3125 | 4 |
def sqrt(x, epsilon):
approx = x / 2
while abs(x - approx) > epsilon:
approx = 0.5 * (approx + x / approx)
return approx
"""
Square Root
Newton-Raphson method implementation.
Input:
x: A float
epsilon: A float
Precondition:
x >= 1 and epsilon > 0
Output:
A float in the interval [sqrt(x) - epsilon, sqrt(x) + epsilon]
Example:
>>> sqrt(2, 0.01)
1.4166666666666665
"""
| true |
14857cf1f6d3397403c422ebad8994bc33848216 | jkoppel/QuixBugs | /correct_python_programs/mergesort.py | 2,389 | 4.15625 | 4 |
def mergesort(arr):
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:] or right[j:])
return result
if len(arr) <= 1:
return arr
else:
middle = len(arr) // 2
left = mergesort(arr[:middle])
right = mergesort(arr[middle:])
return merge(left, right)
"""
def mergesort(arr):
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:] or right[j:])
return result
if len(arr) == 0 or len(arr) == 1:
return arr
else:
middle = len(arr) // 2
left = mergesort(arr[:middle])
right = mergesort(arr[middle:])
return merge(left, right)
def mergesort(arr):
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:] or right[j:])
return result
if len(arr) == 1 or len(arr) == 0:
return arr
else:
middle = len(arr) // 2
left = mergesort(arr[:middle])
right = mergesort(arr[middle:])
return merge(left, right)
def mergesort(arr):
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:] or right[j:])
return result
if len(arr) < 2:
return arr
else:
middle = len(arr) // 2
left = mergesort(arr[:middle])
right = mergesort(arr[middle:])
return merge(left, right)
"""
| true |
23bf4b2a12455334e5fb0ffa4fce75a11cdb2378 | jkoppel/QuixBugs | /python_programs/hanoi.py | 1,138 | 4.40625 | 4 | def hanoi(height, start=1, end=3):
steps = []
if height > 0:
helper = ({1, 2, 3} - {start} - {end}).pop()
steps.extend(hanoi(height - 1, start, helper))
steps.append((start, helper))
steps.extend(hanoi(height - 1, helper, end))
return steps
"""
Towers of Hanoi
hanoi
An algorithm for solving the Towers of Hanoi puzzle. Three pegs exist, with a stack of differently-sized
disks beginning on one peg, ordered from smallest on top to largest on bottom. The goal is to move the
entire stack to a different peg via a series of steps. Each step must move a single disk from one peg to
another. At no point may a disk be placed on top of another smaller disk.
Input:
height: The height of the initial stack of disks.
start: The numbered peg where the initial stack resides.
end: The numbered peg which the stack must be moved onto.
Preconditions:
height >= 0
start in (1, 2, 3)
end in (1, 2, 3)
Output:
An ordered list of pairs (a, b) representing the shortest series of steps (each step moving
the top disk from peg a to peg b) that solves the puzzle.
"""
| true |
c0421854953fd6080d9eefc56fade47695ffa823 | Raghumk/TestRepository | /Functions.py | 1,076 | 4.46875 | 4 |
# Parameter functions is always pass by reference in Python
def fun1( Name ):
Name = "Mr." + Name
return Name
def fun2(Name = "Raghu"):
Name = "Mr." + Name
return Name
print (fun1("Raghu"))
print (fun1(Name="Kiran")) # Named argument
print (fun2()) # Default argument
#### Variable length arguments
def Multiple_Arguments(arg1, *vartuple):
"This prints "
print(arg1) ## First argument
for x in vartuple: ## Subsequent arguments
print(x)
return x
print ('multiple araguments = ', Multiple_Arguments(10, 20, 30))
## Anonymous functions
# not declared using 'def'
# use lamda keyword for anaonymous functions
# can take any number of arguments
# cannot access outside variables. will have local namespace
# syntax:
# lambda [ arg1, [,arg2, arg3..]] : expression
sum = lambda arg1, arg2, arg3 : arg1 + arg2 + arg3 # lambda function with 3 argument
sum2 = lambda : 10 # lambda function without argument
print ("Lambda sum = " , sum(10,20,30))
# Two types of variables. Global & Local | true |
24851e56fd5704a5693657d13cee92004aa81d7c | kneesham/cmp_sci_4250 | /Main.py | 2,458 | 4.25 | 4 | ###
# Name: Theodore Nesham
# Project: 4
# Date: 11/02/2019
# Description: This project was used to show inheritance, polymorphism, and encapsulation. The parent class is Product
# and the two children classes are Book and Movie. The two subclasses override the print_description
# function showing the use of polymorphism, as well as inherit functions and data members from product.
###
class Product:
__name = "Product Name"
__price = 0
__discount_percent = 0
def __init__(self, name, price, discount_percent):
self.__name = name
self.__price = price
self.__discount_percent = discount_percent
def get_name(self):
return self.__name
def get_discount_price(self):
return round(self.__price - self.__price * self. __discount_percent, 2)
def get_discount_amount(self):
return round(self.__price * self.__discount_percent, 3)
def print_description(self):
print("Product name: " + self.__name
+ "\nDiscount: $" + str(self.get_discount_amount())
+ "\nPrice: $" + str(self.get_discount_price())
+ "\n")
class Book(Product):
__author = ""
def __init__(self, name, author, price, discount_percent):
Product.__init__(self, name, price, discount_percent) # calling the Parent constructor.
self.__author = author
def print_description(self):
print("Book name: " + self.get_name()
+ "\nauthor: " + self.__author
+ "\ndiscount amount: $" + str(self.get_discount_amount())
+ "\nprice: $" + str(self.get_discount_price())
+ "\n"
)
class Movie(Product):
__year = ""
def __init__(self, movie_name, year, price, discount_percent ):
Product.__init__(self, movie_name, price, discount_percent)
self.__year = year
def print_description(self):
print("Movie name: " + self.get_name()
+ "\nYear: " + str(self.__year)
+ "\ndiscount amount: $" + str(self.get_discount_amount())
+ "\nprice: $" + str(self.get_discount_price())
+ "\n"
)
custom_product = Product("Popcorn", 4.99, 0.01)
batman_movie = Movie("Batman", 1999, 59.99, 0.05)
cool_book = Book("The Mythical Man Moth", "Frederick P. Brooks, JR.", 29.99, 0.01)
custom_product.print_description()
batman_movie.print_description()
cool_book.print_description()
| true |
c269df6a9e5ab28181e7073991e7fcd6756e1c6d | ahermassi/Spell-Checker | /src/trie/trie.py | 1,712 | 4.125 | 4 | from src.node.trie_node import TrieNode
class Trie:
def __init__(self):
self.root = TrieNode()
def __contains__(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
word = word.strip()
root = self.root
for c in word:
if c not in root: # This is equivalent to: if c not in root.children. See __contains__ method of TrieNode.
return False
root = root[c] # This is equivalent to: root = root.children[c]. See __getitem__ method of TrieNode.
return root.end_of_word
def __len__(self):
def helper(root):
nonlocal length
if root.end_of_word:
length += 1
else:
for node in root.children.values():
helper(node)
root, length = self.root, 0
if not root:
return 0
helper(root)
return length
def add(self, word):
"""
Traverse the trie and add new nodes as we go.
:type word: str
:rtype: None
"""
word = word.strip()
root = self.root # n is for "node"
for c in word:
if c not in root:
root[c] = TrieNode()
root = root[c]
root.end_of_word = True
def starts_with(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
root = self.root
for c in prefix:
if c not in root:
return False
root = root[c]
return True
| true |
580d41a8f9f430feaac5bdfbd8126afffa481d00 | Tochi-kazi/Unit3-10 | /calculate_average .py | 358 | 4.15625 | 4 | # Created by : Tochukwu Iroakazi
# Created on : oct-2017
# Created for : ICS3UR-1
# Daily Assignment - Unit3-10
# This program displays average
print('type in your score')
userinput = input()
counter = 0
numtotal = 0
for userinput in range (0,100):
numtotal = numtotal + userinput
counter = counter + 1
mark = numtotal / counter
else:
print(mark)
| true |
70277b5371bcdb5190de68567903b4ed8aade82f | thomasdephuoc/bootcamp_python | /day_00/ex_03/count.py | 651 | 4.4375 | 4 | def text_analyzer(text=None):
"""This function counts the number of upper characters, lower characters, punctuation and spaces in a given text."""
if text is None:
text = input("What is the text to analyse?")
nb_char = sum(1 for c in text if c.isalpha())
nb_upper = sum(1 for c in text if c.isupper())
nb_lower = sum(1 for c in text if c.islower())
nb_punc = sum(1 for c in text if c == "!")
nb_spaces = sum(1 for c in text if c == " ")
print("The text contains", nb_char, "characters:\n-", nb_upper, "upper letters\n-", nb_lower,
"lower letters\n-", nb_punc, "punctuation marks\n-", nb_spaces, "spaces") | true |
c696337cda0492a06385ab26fdff89cf8de0aa8f | irene-yi/Classwork | /Music.py | 2,108 | 4.28125 | 4 | class Music:
# if you pass in artists while calling your class
# you need to add it to init
def __init__(self, name, artists):
self.name = name
self.artists = artists
self.friends = {}
# Pushing information to the array
def display(self):
print()
print ("Your artists:")
for artists in self.artists:
print (artists)
def add (self):
# gather user input here
add_artist = input('What artist do you want to add?')
self.artists.append(add_artist)
print ("Your artists:")
for artists in self.artists:
print (artists)
def delete (self):
# Deletes the last artist last given
self.artists.pop()
print ("Your artists:")
for artists in self.artists:
print (artists)
# what are you comparing to?
# how do you get that info?
# Add to new datatype friend and shared song
def compare_array(self, friend):
compare = [thing for thing in self.artists if thing in friend.artists]
# add value of compare to artist_array
# setting the key in friends hash = to the value
self.friends[friend.name] = compare
print(self.friends)
def add_friend(self):
friend_name = input("Who do you want to add?")
artists_name = input("Who do you want to add?")
# adds the key #adds the value
self.friends[friend_name] = artists_name
print(self.friends)
# Add friends and shared songs
# for testing call your class and methods
# name = Music(pass in arguments)
estelle = Music('Estelle', ['La la las', 'Car Seat Head Rest'])
# name, #artist array
ben = Music('Ben', ['La la las', 'Food'])
catie = Music('Ben', ['Car Seat Head Rest', 'Food', 'Cat'])
while True:
print("Enter 1 to display the list of artists")
print("Enter 2 to add artists")
print("Enter 3 to delete artists")
print("Enter 4 to compare")
print("Enter 5 to add friends")
print("Enter 6 to quit")
userChoice = int(input())
if userChoice is 1:
estelle.display()
elif userChoice is 2:
estelle.add()
elif userChoice is 3:
estelle.delete()
elif userChoice is 4:
Music.compare_array(estelle, ben)
elif userChoice is 5:
estelle.add_friend()
elif userChoice is 6:
quit()
| true |
7c78cdd9a7c791a82adfe6e19f2f9e1a63f3a953 | IronManCool001/Python | /Guess The Number/main.py | 590 | 4.125 | 4 | import random
chances = 5
print("Welcome To Guess The Number Game")
no = random.randint(0,256)
run = True
while run:
guess = int(input("Enter your guess"))
if guess == no:
print("You Got It")
run = False
break
elif guess > no:
print("You guessed higher!")
chances -= 1
elif guess < no:
print("You guessed lower!")
chances -= 1
if chances == 0:
print("You Lose")
run = False
| true |
b8ecc471b73c1c9ff01b74835b490b29a803b8db | giovanna96/Python-Exercises | /Divisors.py | 279 | 4.125 | 4 | #Practice Python
#Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
divisor = []
value = int(input("enter a number: \n"))
for i in range(value):
if value%(i+1)==0:
divisor.append(i+1)
print(divisor)
| true |
b4b8658f9f4ad759f4111193d3763690ad9265b3 | wahome24/Udemy-Python-Bible-Course-Projects | /Project 10.py | 1,420 | 4.4375 | 4 | #This is a bank simulator project using classes and objects
class Bank:
#setting a default balance
def __init__(self,name,pin,balance=500):
self.name = name
self.pin = pin
self.balance = 500
#method to deposit money
def deposit(self,amount):
self.balance += amount
print(f'Your new balance is {self.balance}')
#method to withdraw money
def withdraw(self,amount):
if self.balance >= amount:
self.balance -= amount
print(f'{amount} Has been withdrawn, Your new balance is {self.balance}')
else:
print('Insufficient balance')
#method to display default balance
def statement(self):
print(f'Welcome {self.name},your current balance is {self.balance}')
print('Welcome to Ashton Bank! Provide your details below: ')
print()
#get user input
name = input('Enter Account Name: ')
pin = input('Enter pin: ')
#create a savings account object and pass in user input
savings= Bank(name,pin)
#display balance
savings.statement()
print()
#loop to simulate deposit and withdrawal of money
choice = input('Do you want to deposit or withdraw or quit?: ').lower()
while choice != 'quit':
if choice =='deposit':
amount = int(input('Enter amount: '))
savings.deposit(amount)
elif choice =='withdraw':
amount = int(input('Enter amount: '))
savings.withdraw(amount)
choice = input('Do you want to deposit or withdraw or quit?: ').lower()
| true |
cebc11a76eba589bec28dd26b3a4bab75e1e5ee8 | shashankmalik/Python_Learning | /Week_4/Modifying the Contents of a List.py | 787 | 4.34375 | 4 | # The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list.
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for i in elements:
# Does this element belong in the resulting list?
if elements!=new_list:
# Add this element to the resulting list
new_list = elements
# Increment i
i
return new_list[0::2]
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []
| true |
4d540640c41d61c2472b73dceac524eb6494797e | chao-shi/lclc | /489_robot_cleaner_h/main.py | 2,788 | 4.125 | 4 | # """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
#class Robot(object):
# def move(self):
# """
# Returns true if the cell in front is open and robot moves into the cell.
# Returns false if the cell in front is blocked and robot stays in the current cell.
# :rtype bool
# """
#
# def turnLeft(self):
# """
# Robot will stay in the same cell after calling turnLeft/turnRight.
# Each turn will be 90 degrees.
# :rtype void
# """
#
# def turnRight(self):
# """
# Robot will stay in the same cell after calling turnLeft/turnRight.
# Each turn will be 90 degrees.
# :rtype void
# """
#
# def clean(self):
# """
# Clean the current cell.
# :rtype void
# """
class Solution(object):
def cleanRoom(self, robot):
"""
:type robot: Robot
:rtype: None
"""
# Smart to use direction vector to determine where to turn
self.d = 0
dir_v = [(0, 1), (1, 0), (0, -1), (-1, 0)]
cleaned = set()
def orient(i_1, j_1, i, j):
v = (i_1 - i, j_1 - j)
idx = dir_v.index(v)
if (idx - self.d) % 4 == 1:
robot.turnRight()
elif (idx - self.d) % 4 == 2:
robot.turnRight()
robot.turnRight()
elif (idx - self.d) % 4 == 3:
robot.turnLeft()
self.d = idx
# Optimize here
def gen_direction():
# return [(0, 1), (1, 0), (0, -1), (-1, 0)]
# Optimization makes orient only one operation
# no matter result of the wall
return dir_v[self.d:] + dir_v[:self.d]
# moved to i, j, moved from i_prev, j_prev
def recur(i, j, i_prev, j_prev):
if (i, j) not in cleaned:
robot.clean()
cleaned.add((i, j))
for v in gen_direction():
i_1, j_1 = i + v[0], j + v[1]
if (i_1, j_1) not in cleaned:
orient(i_1, j_1, i, j)
if robot.move():
recur(i_1, j_1, i, j)
if i_prev != None and j_prev != None:
orient(i_prev, j_prev, i, j)
robot.move()
recur(0, 0, None, None)
# Key point is to use the index, fit the orient function is very universal.
# This approach is very efficient
# Better than top voted solution. The top voted will go back and forth but only clean once.
# Case of corner
#
# 1
# 0 -> 01
# 1
# Will go left.
# The turning is very efficient !!!! Check if yourself | true |
93897a144a08baf27692f9dd52da610be41c0ad3 | p-perras/absp_projects | /table_printer/tablePrinter.py | 788 | 4.1875 | 4 | # !python3
# tablePrinter.py
# ABSP - Chapter 6
def print_table(table):
"""
Summary:
Prints a table of items right justified.
Args:
table (list): A 2d list of items to print.
"""
# Get the max length string of each row.
rowMaxLen = []
for row in range(len(table)):
rowMaxLen.append(max([len(col) for col in table[row]]))
# Print table right justified.
for col in range(len(table[0])):
for row in range(len(table)):
print(table[row][col].rjust(rowMaxLen[row]), end=' ')
print()
if __name__ == '__main__':
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
print_table(tableData) | true |
fc607af81e8f640a2dce4593f55301346b268054 | rubenhortas/python_examples | /native_datatypes/none.py | 759 | 4.53125 | 5 | #!/usr/bin/env python3
# None is a null number
# Comparing None to anything other than None will always return False
# None is the only null number
# It has its own datatype (NoneType)
# You can assign None to any variable, but you can not create other NoneType objects
CTE_NONE1 = None
CTE_NONE2 = None
if __name__ == '__main__':
print("None:")
print(f"None == False -> {None == False}") # False
print(f"None == 0 -> {None == 0}") # False
print(f"None == '' -> {None == ''}") # False
print(f"None == var_none -> {None == CTE_NONE1}") # True
print(f"var_none == var_none2 -> {CTE_NONE1 == CTE_NONE2}") # True
# In a boolean context None is False
if not None:
print("In a boolean context None is always False")
| true |
cd22aa8ee2bc1ba44c8af3f5bd7d880c7edac4eb | krishnavetthi/Python | /hello.py | 817 | 4.5 | 4 | message = "Hello World"
print(message)
# In a certain encrypted message which has information about the location(area, city),
# the characters are jumbled such that first character of the first word is followed by the first character of the second word,
# then it is followed by second character of the first word and so on
#In other words, let’s say the location is bandra,mumbai
#The encrypted message says ‘bmaunmdbraai’
#Let’s say the size or length of the two words wouldn’t match then the smaller word is appended with # and then encrypted in the above format.
input_str = input("Enter")
message1 = input_str[0::2]
message2 = input_str[1::2]
print(message1.strip('#') + "," + message2.strip('#'))
#String Methods
# upper()
# lower()
# strip()
# lstrip()
# rstrip()
# count(substring, beg, end)
| true |
f4fad1000ed28895c819b3bc71a98e7a9f3e87b6 | ofreshy/interviews | /hackerrank/medium/merge_the_tools.py | 2,042 | 4.46875 | 4 | """
Consider the following:
A string,
, of length where
.
An integer,
, where is a factor of
.
We can split
into substrings where each subtring, , consists of a contiguous block of characters in . Then, use each to create string
such that:
The characters in
are a subsequence of the characters in
.
Any repeat occurrence of a character is removed from the string such that each character in
occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string
.
Given
and , print lines where each line denotes string
.
Example
There are three substrings of length to consider: 'AAA', 'BCA' and 'DDE'. The first substring is all 'A' characters, so . The second substring has all distinct characters, so . The third substring has different characters, so
. Note that a subsequence maintains the original order of characters encountered. The order of characters in each subsequence shown is important.
Function Description
Complete the merge_the_tools function in the editor below.
merge_the_tools has the following parameters:
string s: the string to analyze
int k: the size of substrings to analyze
Prints
Print each subsequence on a new line. There will be
of them. No return value is expected.
Input Format
The first line contains a single string,
.
The second line contains an integer,
, the length of each substring.
Constraints
, where is the length of It is guaranteed that is a multiple of .
"""
def merge_the_tools(string, k):
def remove_duplicate(chunk):
duplicates = set()
uniq = ""
for c in chunk:
if c not in duplicates:
duplicates.add(c)
uniq += c
return uniq
num_chunks = int((len(string)+1)/k)
chunks = [string[(i*k):((i+1)*k)] for i in range(num_chunks)]
removed = [remove_duplicate(chunk) for chunk in chunks]
return removed
print(merge_the_tools("ABCDEE", 3))
print(merge_the_tools("ABCDEE", 2))
| true |
06f8cf70cd26e9c71b989fcb63f7525fb4fc3fff | ofreshy/interviews | /interviewcake/apple_stock.py | 2,451 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Suppose we could access yesterday's stock prices as a list, where:
The values are the price in dollars of Apple stock.
A higher index indicates a later time.
So if the stock cost $500 at 10:30am and $550 at 11:00am, then:
stock_prices_yesterday[60] = 500
Write an efficient function that takes stock_prices_yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday.
For example:
stock_prices_yesterday = [10, 7, 5, 8, 11, 9]
get_max_profit(stock_prices_yesterday)
# returns 6 (buying for $5 and selling for $11)
No "shorting"—you must buy before you sell. You may not buy and sell in the same time step (at least 1 minute must pass).
"""
def get_max_profit(stock_prices_yesterday):
"""
:param stock_prices_yesterday: list of stock prices. Must have at least 2 elements
:return: best profit that could have been gained throughout the day
"""
min_price = stock_prices_yesterday[0]
max_profit = stock_prices_yesterday[1] - stock_prices_yesterday[0]
for current_price in stock_prices_yesterday[1:]:
# see what our profit would be if we bought at the
# min price and sold at the current price
potential_profit = current_price - min_price
# update max_profit if we can do better
max_profit = max(max_profit, potential_profit)
# update min_price so it's always
# the lowest price we've seen so far
min_price = min(min_price, current_price)
return max_profit
def get_max_profit_brute(stock_prices_yesterday):
"""
:param stock_prices_yesterday: list of stock prices. Must have at least 2 elements
:return: best profit that could have been gained throughout the day
"""
n = len(stock_prices_yesterday)
return max([
max([stock_prices_yesterday[j] - stock_prices_yesterday[i] for j in range(i + 1, n)])
for i in range(n - 1)
])
assert get_max_profit([10, 7, 5, 8, 11, 9]) == 6
assert get_max_profit([10, 10, 9, 7]) == 0
assert get_max_profit([10, 10, 9, 7]) == 0
assert get_max_profit([10, 3, 1, 16]) == 15
assert get_max_profit([10, 1, 3, 16]) == 15
assert get_max_profit_brute([10, 7, 5, 8, 11, 9]) == 6
assert get_max_profit_brute([10, 10, 9, 7]) == 0
assert get_max_profit_brute([10, 10, 9, 7]) == 0
assert get_max_profit_brute([10, 3, 1, 16]) == 15
assert get_max_profit_brute([10, 1, 3, 16]) == 15
| true |
7ddd97ed6cc317d4fdf9fc1731d8425d2eb3b6a4 | gunjan-madan/Namith | /Module4/1.3.py | 915 | 4.40625 | 4 | #Real Life Problems
'''Task 1: Delivery Charges'''
print("***** Task 1: *****")
print()
# Create a program that takes the following input from the user:
# - The total number of sand sack and cement sack
# - Weight of each sack [Hint: use for loop to get the weight]
# - Use a variable to which the weight of the sack gets added as entered [Hint: calculate this within the for loop]
# - Calculates the total cost if each sack cost INR 300 [ outside the for loop]
# So let's get started
'''Task 2: Lets go Outdoors'''
print("***** Task 2: *****")
print()
#Write a program that takes care of outdoor field trips for kids.
# The program needs to:
# - Take the total number of kids (Number cannot be more than 8)
# - Get the name, and address for each kid
# The program must display the total cost for the field trip where
# - Cost for food for each kid is INR 500
# - Cost for travel for each kid is INR 1000
| true |
c8b8060d5aeb1374f0ef0bb89f436884e1b32748 | gunjan-madan/Namith | /Module2/3.1.py | 1,328 | 4.71875 | 5 | # In the previous lesson, you used if-elif-else statements to create a menu based program.
# Now let us take a look at using nested if-elif statements in creating menu based programs.
'''Task 1: Nested If-else'''
print()
print("*** Task 1: ***")
print()
#Make a variable like winning_number and assign any number to it between 1 and 20.
#Ask user to guess a number between 1 and 20. (Take input)
#if user guessed correctly, print "YOU WIN"
#if user didn't guessed correctly then:
#if user guessed lower than actual number, then print "TOO LOW"
#if user guessed lower than actual number, then print "TOO HIGH"
'''Task 2: Nested If-else'''
print()
print("*** Task 2: ***")
print()
#This is a program to tell User the shipping cost based on the country and the weight.
#Write a Program that takes two inputs: country_code(AU/US) and weight of the product.
#Use the following conditions to find the shipping cost
#country Product Size Shippping cost
#US less than 1kg $5
#US between 1 and 2kg $10
#US greater than 2kg $20
#AU less than 1kg $10
#AU between 1 and 2kg $15
#AU greater than 2kg $25
# print("This Program will caluculate Shipping Cost") | true |
552c0f6239df522b27684179f216efe7b10a7037 | gunjan-madan/Namith | /Module2/1.3.py | 1,705 | 4.21875 | 4 | # You used the if elif statement to handle multiple conditions.
# What if you have 10 conditions to evaluate? Will you write 10 if..elif statements?
# Is it possible to check for more than one condition in a single if statement or elif statement?
# Let's check it out
"""-----------Task 1: All in One ---------------"""
print(" ")
print("*** Task 1: ***")
# Do you know what are isosceles and scalene triangles?
# Write a program to check if a triangle is equilateral, scalene or isosceles.
"""-----------Task 1.2: All in One ---------------"""
print(" ")
print("*** Task 1.2: ***")
#The program takes a number as an input
#Program shall check if the number is divisible by both 3 and 4
"""---------Task 2: Its raining Discount -------------"""
print(" ")
print("*** Task 2: ***")
# Your store is giving a discount on the total purchase amount based on customer membership.
# Write a program that calculates the discounted amount based on the below mentioned conditions:
# If membership is silver, 5% discount
# If membership is silver+ or gold, discount is 10%
# If membership is gold+ or diamond, discount is 15%
# if membership is platinum membership discount is 20%
"""---------Task 3: Theme Rides -------------"""
print(" ")
print("*** Task 3: ***")
# You are managing the ticket counter at Imaginika Theme Park. Based on the age of the entrant, you issue tickets for the rides"
# Age between 5 and 7 :Toon Tango, Net Walk
# Age between 8 and 12: Wonder Splash, Termite Coaster Train
# Age greater 13: Hang Glider, Wave Rider
# If the age criteria does not match they can go for the nature walks
# Write a program that grants access to the rides based on the age conditions. | true |
f36fd365929003b92229a08a013b4cf1af4cc5bd | NasserAbuchaibe/holbertonschool-web_back_end | /0x00-python_variable_annotations/1-concat.py | 383 | 4.21875 | 4 | #!/usr/bin/env python3
"""Write a type-annotated function concat that takes a string str1 and a
string str2 as arguments and returns a concatenated string
"""
def concat(str1: str, str2: str) -> str:
"""[Concat two str]
Args:
str1 (str): [string 1]
str2 (str): [string 2]
Returns:
str: [concatenated string]
"""
return str1 + str2
| true |
31bc1789c9cddfef609d48fc36f7c1ecb0542864 | Lionelding/EfficientPython | /ConcurrencyAndParallelism/36a_MultiProcessing.py | 2,434 | 4.46875 | 4 | # Item 36: Multi-processing
"""
* For CPU intensive jobs, multiprocessing is faster
Because the more CPUs, the faster
* For IO intensive jobs, multithreading is faster
Because the cpu needs to wait for the I/O despite how many CPUs available
GIL is the bottleneck.
* Multi-core multi-threading is worse than single core multithreading.
* Mutli-core multi-processing is better since each process has an independent GIL
* Example 1: single process
* Example 2: multiprocess
* Example 3: multiprocess + Pool
* Example 4: multiprocess shares data with Queue
"""
import os
import time
import random
from multiprocessing import Process, Pool, cpu_count, Queue
## Example 1: single process
print("######## Example 1 ########")
def long_time_task():
print(f'current process: {os.getpid()}')
time.sleep(2)
print(f"result: {8 ** 20}")
print(f'mother process: {os.getpid()}')
start = time.time()
for i in range(2):
long_time_task()
end = time.time()
print(f'Duration: {end-start}')
## Example 2: multi-process
print("######## Example 2 ########")
def long_time_task_i(i):
print(f'current process: {os.getpid()}, {i}')
time.sleep(2)
# print("result: {8 ** 20}")
print(f'mother process: {os.getpid()}')
start2 = time.time()
p1 = Process(target=long_time_task_i, args=(1, ))
p2 = Process(target=long_time_task_i, args=(2, ))
p1.start()
p2.start()
p1.join()
p2.join()
end2 = time.time()
print(f'Duration: {end2-start2}')
## Example 3: multiprocess + pool
print("######## Example 3 ########")
"""
1. process.join() needs to be after .close() and .terminate()
"""
print(f"num cpu: {cpu_count()}")
print(f'mother process: {os.getpid()}')
start3 = time.time()
pool3 = Pool(4)
for i in range(5):
pool3.apply_async(long_time_task_i, args=(i, ))
pool3.close()
pool3.join()
end3 = time.time()
print(f'Duration: {end3-start3}')
## Example 4: Share data between multi-process using Queue
print("######## Example 4 ########")
def write(q):
print(f'Process to write: {os.getpid()}')
for value in ['a', 'b', 'c']:
print(f'Put: {value}')
q.put(value)
time.sleep(0.2)
def read(q):
print(f'Process to read: {os.getpid()}')
while True:
value = q.get(True)
print(f'Get: {value}')
q = Queue()
pw = Process(target=write, args=(q, ))
pr = Process(target=read, args=(q, ))
pw.start()
pr.start()
pw.join()
pr.terminate()
## REF: https://zhuanlan.zhihu.com/p/46368084
## REF: https://zhuanlan.zhihu.com/p/37029560
| true |
368b25a3c24acd2bd61811676f685cb5083bbd46 | Lionelding/EfficientPython | /3_ClassAndInheritance/27_Private_Attributes.py | 1,778 | 4.28125 | 4 | # Item 27: Prefer Public Attributes Over Private Attributes
'''
1. classmethod has access to the private attributes because the classmethod is declared within the object
2. subclass has no direct access to its parent's private fields
3. subclass can access parents' private fields by tweeking its attribute names
4. Document protected fields in parent classes
5. Only use private attributes when to avoid naming conflicts between parent and subclasses
'''
class MyObject(object):
def __init__(self):
self.public_field = 3
self.__private_field1 = 'field1'
self.__private_field2 = 'field2'
def get_private_field1(self):
return self.__private_field1
def get_private_field2(self):
return self.__private_field2
@classmethod
def get_private_field_of_instance(cls, instance):
return instance.__private_field1
class MyChildObject(MyObject):
def __init__(self):
super().__init__()
self._private_field1 = 'kid_field1'
foo = MyObject()
kid = MyChildObject()
## `Statement 1`
print(f'public_field: {foo.public_field}')
print(f'access from parent class: {foo.get_private_field2()}')
print(f'access from classmethod: {MyObject.get_private_field_of_instance(foo)}')
## `Statement 2`
#print(f'kid: {kid.get_private_field1()}') #should fail
## `Statement 3`
## However, because the way that python translated private attributes, private attributes are accessible
print(f'illegal acess: {kid._MyObject__private_field1}')
## Hardcoding a private attribute, which is defined in a parent class, from a subclass is bad approach because there could be another
## layer of hierarchy added in the future.
## 'Statement 5`
print(f'access kid private field: {kid._private_field1}')
print(f'access parent private field from parent method: {kid.get_private_field1()}')
| true |
d1d051a33cc4da4eeec7a394394b976926ea51d8 | jenny-liang/uw_python | /week05/screen_scrape_downloader.py | 2,061 | 4.3125 | 4 | """
Assignment: choose one or both or all three. I suspect 2 is a lot harder, but
then you would have learned a lot about the GitHub API and JSON.
1. File downloader using screen scraping: write a script that scrapes
our Python Winter 2012 course page for the URLs of all the Python
source files, then downloads them all.
"""
import urllib2
import re
from pprint import pprint
from BeautifulSoup import BeautifulSoup
import os
import time
if os.path.exists("downloads"):
os.system("rm -rf downloads")
os.system("mkdir downloads")
# read a web page into a big string
page = urllib2.urlopen('http://jon-jacky.github.com/uw_python/winter_2012/index.html').read()
# parse the string into a "soup" data structure
soup = BeautifulSoup(page)
# find all the anchor tags in the soup
anchors = soup.findAll('a')
# find all the anchor tags that link to external web pages
externals = soup.findAll('a',attrs={'href':re.compile('http.*')})
# find all the anchor tags that link to Python files
pythonfiles = soup.findAll('a',attrs={'href':(lambda a: a and a.endswith('.py'))})
for files in pythonfiles:
s = str(files)
file_path = s[s.find('=') + 2 : s.find('>') -1]
time.sleep(1)
url = 'http://jon-jacky.github.com/uw_python/winter_2012/' + file_path
print url
fileContent = urllib2.urlopen(url)
dir = os.path.dirname(file_path)
if not os.path.exists("downloads/" + dir):
os.system("mkdir -p downloads/%s" %dir)
f = open("downloads/"+ dir + "/" + os.path.basename(file_path), "wb")
meta = fileContent.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_path, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = fileContent.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
| true |
86528dd845be83a71b90850b26a7880f85a0f758 | mk346/Python-class-Projects | /Guess_Game.py | 492 | 4.25 | 4 | secret_word ="trouser"
guess= ""
count=0
guess_limit = 3
out_of_guesses= False
print("HINT: I have two legs but i cant walk")
while guess!= secret_word and not(out_of_guesses):
if count<guess_limit:
guess = input("Enter Your Guess: ")
count+=1
else:
out_of_guesses= True
if out_of_guesses:
print("You are Remaining with: " + str(guess_limit - count) + "\t Guesses")
print("Out of Guesses, You Lose!")
else:
print("You Win!")
| true |
a8a4f8ecc948c07a6c8f96173bb2b6e32ee550aa | deepgautam77/Basic_Python_Tutorial_Class | /Week 1/Day 2/for_loop.py | 253 | 4.15625 | 4 | #for i in range(10):
# print("This is fun..")
#range() function
#print odd number from 0-100
for i in range(1,100,2):
print(i, end=' ')
#WAP to print even numbers from 2000-2500
#WAP to print odd numbers starting from 5200 and ending at 4800
| true |
d49cedb5535e851045d759e51e9a37f833f6c460 | deepgautam77/Basic_Python_Tutorial_Class | /Day 5/homework_1.py | 659 | 4.34375 | 4 |
#Create a phone directory with name, phone and email. (at least 5)
#WAP to find out all the users whose phone number ends with an 8.
#all the users who doesn't have email address. --done
d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'},
{'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'},
{'name':'Princess', 'phone':'555-3841', 'email':''},
{'name':'LJ', 'phone':'555-2718', 'email':'lj@mail.net'}]
#email
#phone that ends with an 8
for item in d:
if item['email']=='':
print("The name ",item['name'], "doesn't have email address.")
if item['phone'].endswith('8'):
print("The phone number ending at 8: ",item['phone'])
| true |
694759e96c8e1988ff347b36ff6c50b55b113639 | deepgautam77/Basic_Python_Tutorial_Class | /Week 1/Day 2/simple_task.py | 294 | 4.3125 | 4 | # -273 degree celsius < invalid..
temp = float(input("Enter the temperature: "))
while temp<-273:
temp = eval(input(("Impossible temperature. Please enter above -273 degree celsius: ")))
print("The temperature of ",temp," Celsius in Farenheit is: ", 9/5*temp+32)
#break
#continue
#pass
| true |
00af72c64e08a9f15b7f869ed9745e3130e676e7 | markap/PythonPlayground | /language_features/decorator.py | 535 | 4.375 | 4 | """
a decorator example to multiply to numbers before executing the decorated function
"""
def multiply(n, m):
def _mydecorator(function):
def __mydecorator(*args, **kw):
# do some stuff before the real
# function gets called
res = function(args[0] * n, args[1] * m, **kw)
# do some stuff after
return res
# returns the sub-function
return __mydecorator
return _mydecorator
@multiply(2,3)
def p(n, m):
return n, m
print p(3,3)
| true |
8c763d12a5708eaf31d2da130d47304f4414bd6b | sean-blessing/20210424-python-1-day | /ch07/classes/main.py | 640 | 4.1875 | 4 | from circle import Circle
class Rectangle:
"""Rectangle class holds length and width attributes"""
# above doctring is optional
area_formula = "area = length * width"
def __init__(self, length, width):
pass
self.length = length
self.width = width
def area(self):
""" calculate the area for this rectangle """
return self.length * self.width
rect_1 = Rectangle(5, 6)
rect_2 = Rectangle(10, 25)
print('rect_1 area: ', rect_1.area())
print('rect_2 area: ', rect_2.area())
circle_1 = Circle(3)
print('circle_1 area', circle_1.area())
print('circle_1 radius', circle_1.radius)
| true |
b8387b9ee340e02727a089494ef37a9d80ed5de5 | sean-blessing/20210424-python-1-day | /ch01/rectangle-calculator/main.py | 352 | 4.15625 | 4 | print("Welcome to the area and perimeter calculator!")
choice = "y"
while choice == "y":
length = int(input("enter length:\t"))
width = int(input("enter width:\t"))
perimeter = 2*length + 2*width
area = length * width
print(f"Area:\t\t{area}")
print(f"Perimeter\t{perimeter}")
choice = input("Try again?")
print("Bye")
| true |
de513e18abf270601e74fc0e738dc4f6ef7c5c1a | guam68/class_iguana | /Code/Richard/python/lab25-atm.py | 1,914 | 4.34375 | 4 | """
author: Richard Sherman
2018-12-16
lab25-atm.py, an ATM simulator, an exercise in classes and functions
"""
import datetime
class ATM():
def __init__(self, balance = 100, rate = 0.01):
self.balance = balance
self.rate = rate
self.transactions = []
def check_withdrawal(self, amount):
if amount > self.balance:
return False
return True
def withdraw(self, amount):
if self.check_withdrawal(amount):
self.balance -= amount
self.transactions.append(f'Withdrawal of {amount}, {datetime.datetime.now()}, Balance = {self.balance} ')
else:
print('Insufficient funds')
def deposit(self, amount):
self.balance += amount
self.transactions.append(f'Deposit of {amount}, {datetime.datetime.now()}, Balance = {self.balance}')
def check_balance(self):
self.calc_interest(self.balance)
self.transactions.append(f'Interest of {self.rate} added to balance, {datetime.datetime.now()}, Balance = {self.balance}')
return self.balance
def calc_interest(self, rate):
self.balance += self.balance * self.rate
return self.balance
def print_transactions(self):
print(self.transactions)
atm = ATM()
while True:
command = input('what would you like to do (deposit, withdraw, check balance, history, exit)? ')
if command == 'exit':
print('Thank you for banking with us!')
break
elif command == 'deposit':
amount = float(input('what is the amount you\'d like to deposit? '))
atm.deposit(amount)
elif command == 'withdraw':
amount = float(input('what is the amount you\'d like to withdraw? '))
atm.withdraw(amount)
elif command == 'check balance':
print(f'Your account balance is ${atm.check_balance()}')
elif command == 'history':
atm.print_transactions()
| true |
7a9349976447f50f8a54c6999aa1419e5e382f2e | guam68/class_iguana | /Code/Scott/Python/lab_11_simple_calculator_version2.py | 898 | 4.28125 | 4 | #lab_11_simple_calculator_version2.py
#lab_11_simple_calculator_lvl_1
#operator_dict = {'+': +,}
operator = input("What type of calculation would you like to do? Please enter '+', '-', '**', or '/' :")
operand_a = input('Please enter the first number:')
operand_b = input('Please enter the second number:')
operand_a = float(operand_a)
operand_b = float(operand_b)
if operator == '+':
result = operand_a + operand_b
print(f'Answer: {result}')
elif operator == '-':
result = operand_a - operand_b
print(f'Answer: {result}')
elif operator == '*':
result = operand_a * operand_b
print(f'Answer: {result}')
elif operator == '/':
result = operand_a / operand_b
print(f'Answer: {result}')
while True:
operator = input("Please enter '+', '-', '**', or '/' or if you are finished, type 'done'")
if operator == 'done':
print('Goodbye.')
break
| true |
b7816fc8efb71a1535030bc5c2a0dc583c29116c | yvette-luong/first-repo | /data-types.py | 668 | 4.1875 | 4 | """
Boolean = True or False
String = "Yvette"
Undefined = A value that is not defined
Integer = 132432
Camel Case = lower case first word and then capitalize each following word:
example: helloWorld
"""
"1231314"
Yvette = 123
Yvette
def helloYvette(): # this is a function, which is indicated by brackets
print("Hello my name is Yvette")
helloYvette() # calling the function
def helloAnyone(name): # accept a parameter
print(f"Hello my name is {name}")
helloAnyone("sjfajkhf") # sjfajkhf is an argument
def multiply(x, y):
return x * y
print(multiply(6, 2))
print("Hello this is print")
def add(a, b):
return a + b
print(add(4, 5))
| true |
2e7839e32546b9cf8a790c16b71c24986d8f12cb | stevenhughes08/CIT120 | /work/python/unit7/SuperMarket.py | 1,337 | 4.28125 | 4 | # SuperMarket.py - This program creates a report that lists weekly hours worked
# by employees of a supermarket. The report lists total hours for
# each day of one week.
# Input: Interactive
# Output: Report.
# Declare variables.
HEAD1 = "WEEKLY HOURS WORKED"
DAY_FOOTER = "Day Total "
SENTINEL = "done" # Named constant for sentinel value
hoursWorked = 0 # Current record hours
hoursTotal = 0 # Hours total for a day
prevDay = "" # Previous day of week
notDone = True # loop control
# Print two blank lines.
print("\n\n")
# Print heading.
print("\t" + HEAD1)
# Print two blank lines.
print("\n\n")
# Read first record
dayOfWeek = input("Enter day of week or done to quit: ")
if dayOfWeek == SENTINEL:
notDone = False
else:
hoursWorked = input("Enter hours worked: ")
prevDay = dayOfWeek
hoursTotal += int(hoursWorked)
print("\t" + DAY_FOOTER + str(hoursTotal))
while notDone == True:
dayOfWeek = input("Enter day of week or done to quit: ")
if dayOfWeek == SENTINEL:
break
# Implement control break logic here
# Include work done in the dayChange() function
if prevDay != dayOfWeek:
hoursTotal = 0
hoursWorked = input("Enter hours worked: ")
prevDay = dayOfWeek
hoursTotal += int(hoursWorked)
print("\t" + DAY_FOOTER + str(hoursTotal))
| true |
a3d6d0d7062c1452341c59741ea67aada4dc9ed8 | danangsw/python-learning-path | /sources/8_loops/4_else_loop.py | 640 | 4.3125 | 4 | # Python supports `else` with a loops.
# When the loop condition of `for` or `while` statement fails then code part in `else` is executed.
# If `break` statement is executed then `else` block will be skipped.
# Even any `continue` statement within a loops, the `else` block will be executed.
count = 0
while count < 5:
print(count)
count += 1
pass
else:
print("Reach maximum counting (%d)" % count)
pass
print()
for i in range(0,10):
if i % 5 == 0:
break
print(i)
pass
else:
print("this is not printed because for loop is terminated because of break but not due to fail in condition")
pass | true |
2e4761e091c6838cfdedbd8bdd48c727a606afd5 | hjhorsting/Bootrain2 | /PythonBasics.py | 549 | 4.4375 | 4 | # 1. Write a code that outputs your name and surname in one line.
print("Harald Horsting")
# or:
print("Harald", "Horsting")
# 2. Write a 1-line code that outputs your name and surname in two separate lines by using
# a single print() call.
print("Harald \n Horsting")
# 3. Use print() function that returns the following text.
# Notice the quotes in the text. Those quotes should be seen in the output!
# `I don't want to be an "artist". I want to be a "Data Scientist."`
print('''`I don't want to be an "artist". I want to be a "Data Scientist."`''') | true |
2c099c78fb2eff10a340d1ba214e333cfb17d720 | MarKuchar/intro_to_algorithms | /1_Variables/operators.py | 1,205 | 4.15625 | 4 | # Operators
# =, -, *, /, // (floor division)
# % (modulo): 'mod' remainder
# ** (power)
print(10 % 3) # 1
print(10 ** 2) # 100
print(100 // 3) # 33
print(100 - 5)
# = : assignment
number = 7
number = number + 3 # increment number by 3
number += 3 # increment number by 3
# -= : decrement operator
print("number = " + str(number)) # string concatenation (+)
# *= : multiply by
number *= 2
# /= : divide by
# Boolean Operators
# Comparison
# == : equality (equal)
print(3 == 4)
# != : not equal to
# > : greater than
# >= : greater than or equal to
# <= : less than or equal to
print(3 < 4)
x = 10
# check if x is greater than equal to 7 and less than 12
print(x >= 7 and x < 12) # and (both have to be true to return TRUE), or (either one has to be true to return TRUE)
print(7 <= x < 12) # only in python! same as "print(x >= 7 and x < 12)"
print((3 != 3) or (4 == 4))
# 4 == death (in chinnes), 13 == bad luck
# Exercise
num = 10
# print((num > 10) and (num / 0 = 0)) # ZeroDivisionError
print((num > 10) and (num / 0 == 0)) # False
print((num > 7) or (num / 0 == 0)) # True
# print((num > 10) or (num / 0 = 0)) # ZeroDivisionError
print(not True) # False
print(not False) # True
| true |
5b25724eae900e42228b5687f4f2691b7bb10031 | MarKuchar/intro_to_algorithms | /8_Functions/functions.py | 1,050 | 4.28125 | 4 | # Functions are a very convenient way to divide your code into useful blocks, make it more readable and help 'reuse' it.
# In python, functions are defined using the keyword 'def', followed by function's name.
# "input --> output", "A reusable block of code"
def print_menu():
print("----- Menu -----")
print("| 1. Tacos ")
print("| 2. Pizza ")
print("| 3. BBQ ")
print("| 4. Feijoada ")
print("| 5. Halusky ")
print("----------------")
print_menu() # call the function
# printing menu 5x
for i in range(5):
print_menu() # call execute the function
def score_to_letter_grade(mark):
if 100 >= mark >= 90:
return "A"
elif 90 > mark >= 80:
return "B"
elif 80 > mark >= 70:
return "C"
elif 70 > mark >= 60:
return "D"
elif 60 > mark >= 0:
return "F"
print(score_to_letter_grade(82))
print(score_to_letter_grade(63))
print(score_to_letter_grade(21))
letter = score_to_letter_grade(90)
print(letter)
print(score_to_letter_grade(95)) | true |
1d7501c04e7e41331f36b5085202c7c1da7aa91b | MarKuchar/intro_to_algorithms | /4_Tuples/tuples_basics.py | 970 | 4.34375 | 4 | # Tuples are almost identical to lists
# The only big difference between lists and tuples is that tuples cannot be modified (Immutable)
# You can NOT add(append), changed(replace), or delete "IMMUTABLE LIST"
# elements from the tuple
vowels = ("a", "e", "i", "o", "u") # consonants (b, c, d, ...)
print(vowels[0])
print("k" in vowels)
# vowels[0] = "A" # Error
# Methods
vowels.index("e")
vowels.count("i")
# Use cases
# 1. return multiple values from a function
def a():
return (1, "Mars")
# example
def get_combo(name):
if name == "Big-mac":
return ("Coke", "Big-mac", "Fries")
# 2. check if an item is in a tuple
print("a" in vowels)
# 3. multiple assignments
year, country = (2020, "Canada")
_, country, provice = (2020, "Canada", "BC") # underscore we use when we want to ignore part of assignment
# swap
x = 10
y = 20
# I want to swap x and y
# in python
x, y = y, x
# in other languages
temp = x # temporary variable
x = y
y = temp
| true |
e783da31a78d9b2f0f786c0a7f5b9a7bd707833e | MarKuchar/intro_to_algorithms | /1_Variables/variable_type.py | 883 | 4.3125 | 4 | # Data types
# There are many different data types in Python
# int: integer
# float: floating point (10.23, 3.14, etc)
# bool: boolean (True, False)
# str: a sequence of characters in quotes "aa", 'aa'
language = "en_us"
print(type(language)) # check the type of the variable
users = 10
"""
print(users + language) # ERROR - we must match the type
"""
print(str(users) + language)
# Type conversion (type changing): "changing types".
# There are several built-in functions that let you convert one data type to another.
# str(x): converts x into a string representation.
# int(x): converts x into an integer.
# float(x): converts x into a floating-point number.
#Ecercise: what is the type of following operations?
# 10. 1 / 2 -> float
print(str(1/2))
# 2. 10 // 4 -> int division
print(type(10 // 4))
# 3. float("a.12") -> Error
# 4. float(5) -> 5.0 (float)
print(float(5)) | true |
46f360e2ece2d5195fe417c92cc1b91cd1f467ae | Chauhan98ashish/Hacktoberfest_2020 | /newton_sqrt.py | 219 | 4.34375 | 4 | print("*****Square Root By Newton's Method*****")
x=int(input("Enter the number::>>"))
r=x
a=10**(-10)
while abs(x-r*r)>a:
r=(r+x/r)/2
print(r)
r=round(r,3)
print("Square root of {} is {}".format(x,r))
| true |
c7aa27a1bd3cb900533845dd60eada06f6773b7f | sairaj225/Python | /Regular Expressions/5Find_a_word_in_string.py | 307 | 4.28125 | 4 | import re
# if re.search("hello", "we have said hello to him, and he replied with hellora hello"):
# print("There is hello in the string")
# findall() returns list of all matches
words = re.findall("hello", "we have said hello to him, and he replied with hellora hello")
for i in words:
print(i)
| true |
6c7e393680152b14a04838a6406298cce3e9e3fb | sairaj225/Python | /Generators/1demo.py | 774 | 4.5625 | 5 | '''
Generators are used to create iterators,
but with a different approach.
Generators are simple functions which return an iterable set of items,
one at a time, in a special way.
'''
# If a function contains at least one yield statement
# It becames a Generator function.
# Generator function contains one or more yield statements.
'''
both 'yeild' and 'return' returns the same value.
'''
# when the function terminates, StopIteration is raised automatically on further calls.
# A simple generator function.
def first_generator():
n=1
print("First statement")
yield n
n=n+1
print("Second statement")
yield n
n=n+1
print("Third statement")
yield n
a = first_generator()
print(next(a))
print(next(a))
print(next(a))
print(next(a)) | true |
f7917d704ac0e45d8b0ffc804eeac7dc65eac66b | Dnavarro805/Python-Programming | /Data Structures - Arrays/StringReverse.py | 358 | 4.1875 | 4 | # Problem: Create a funciton that reverses a string.
# Input: "Hi My Name is Daniel"
# Output: "lienaD si emaN yM iH"
def reverse(str):
reversed = []
for x in range (len(str)-1, -1, -1):
reversed.append(str[x])
return ''.join(reversed)
def reverse2(str):
return str[::-1]
print(reverse("Daniel"))
print(reverse2("Daniel")) | true |
53f1c9eee659d35d7ed4b563d21a6e4502d811e5 | nolanroosa/intermediatePython | /hw21.py | 1,835 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 16:59:35 2020
@author: nolanroosa
"""
# Question 1
import pandas as pd
pop = pd.read_csv("/Users/nolanroosa/Desktop/Python/pop.csv")
def menu():
print ('''
Population Menu:
1. Display the entire table
2. Display the total population of all the states
3. Prompt for the name of a state. Display its population
4. Display the table sorted by state name
5. Dissplay the table grouped by region
6. Display the table sorted by population, largest to smallest
0. Quit
''')
menuRequest = int(input('Enter a menu option: '))
menuOption = []
for i in range(0,7):
menuOption.append(i)
if menuRequest not in menuOption:
print('\nEnter a valid menu item.')
else:
return(menuRequest)
def statereq():
stateRequest = input('Enter the name of a state: ')
namedPop = pop.set_index('NAME')
print('\nThe population of the entered state is', namedPop.loc[stateRequest][2])
def main():
continueFlag = True
while continueFlag:
menuRequest = menu()
if menuRequest == 1:
print(pop)
elif menuRequest == 2:
print(pop['POPULATION'])
elif menuRequest == 3:
statereq()
elif menuRequest == 4:
print(pop.sort_values(by = 'NAME'))
elif menuRequest == 5:
print(pop.sort_values(by = 'REGION'))
elif menuRequest == 6:
print(pop.sort_values(by = 'POPULATION', ascending = False))
elif menuRequest == 0:
print("You have quit.")
continueFlag = False
if __name__ == "__main__":
main()
| true |
e50af84ac8ce77f08597c3ef94481e5aef55fd48 | yogeshBsht/CS50x_Plurality | /Plurality.py | 1,469 | 4.34375 | 4 | # Plurality
max_candidates = 5
candidates = ['Lincoln', 'Kennedy', 'Bush', 'Obama', 'Trump', 'Biden']
# Taking number of candidates as input
flag = 1
while flag:
num_candidates = int(float(input("Enter number of candidates: ")))
if num_candidates < 2:
print("Value Error! At least 2 candidates must contest the election.")
elif num_candidates > max_candidates:
print(f"Value Error! Number of candidates must not exceed {max_candidates}.")
else:
flag = 0
# Randomly selecting contestants from candidates list
import random
contestants = [*random.sample(candidates, num_candidates)]
print("Contestants are: ", end=" ")
print(*contestants, sep=", ")
# Taking number of voters as input
voters = int(float(input("Enter number of voters: ")))
# Random voting based on number of voters
dict = {}
for _ in range(voters):
val = random.sample(contestants,1)[0]
if val in dict:
dict[val] += 1
else:
dict[val] = 1
# Winner selection based on vote count
winner, count = [], 0
for cont in dict:
if dict[cont] == count:
winner.append(cont)
count = dict[cont]
elif dict[cont] > count:
winner = [cont]
count = dict[cont]
if len(winner) == 1:
print(f"Winner {winner[0]} secured {count} votes out of {voters} votes.")
else:
print("Election tied among: ", end=" ")
print(*winner, sep = ", ") | true |
d8fd09cbd25c6fe085aacf33768aedcc713b7e04 | jurbanski/week2 | /solution_10.py | 2,721 | 4.34375 | 4 | #!/usr/local/bin/python3
# 2015-01-14
# Joseph Urbanski
# MPCS 50101
# Week 2 homework
# Chapter 8, Question 10 solution.
# Import the sys module to allow us to read the input filename from command line arguments
import sys
# This function will prompt the user for a filename, then check to see if the file exists. If the file does not exist, it prompts again. If the file does exist, it returns the name of the file.
def prompt_for_filename():
while True:
filename = input("Please enter an input filename: ")
try:
infile = open(filename, 'r')
return filename
except OSError:
print("File not found!")
# Check to see if the filename has been provided as a command line argument, if it hasn't, prompt for user input with the prompt_for_filename() function.
try:
filename = sys.argv[1]
infile = open(filename, 'r')
# CASE: File not found.
except OSError:
print("File not found!")
filename = prompt_for_filename()
# CASE: No filename provided on the command line.
except IndexError:
filename = prompt_for_filename()
# infile may not be set when the try block above finishes (out of scope if we have to prompt for a filename with prompt_for_filename()), so set it here.
infile = open(filename, 'r')
# Initialize some working variables.
leg = 0
odometer_prev = 0
miles_total = 0
gas_total = 0
# Loop over every line in the file.
for line in infile:
# Split the current line into an array of strings.
currline = line.split()
# Set the current odometer to the first value in the current line.
odometer_curr = float(currline[0])
# Test to see if this is the first line in the file.
if leg == 0:
# If so, then:
# Set the previous odometer to be the current odometer.
odometer_prev = odometer_curr
# Increment the leg counter.
leg += 1
else:
# If not the first line, then:
# Set the gas used to the second item in the current line.
gas_used = float(currline[1])
# Determine the miles traveled from the two odometer values.
miles_traveled = odometer_curr - odometer_prev
# Add the miles traveled on the current leg to the total.
miles_total += miles_traveled
# Add the gas used to the total.
gas_total += gas_used
# Calculate the MPG for this leg of the trip.
mpg_curr = miles_traveled / gas_used
# Output the MPG for this leg.
print("Leg", leg, "MPG:", round(mpg_curr, 2))
# Set the previous odometer to the current odometer for the next loop
odometer_prev = odometer_curr
# Increment the leg counter.
leg += 1
# Finally, calculate the total average MPG for the trip and output that value.
print("Total MPG:", round(miles_total / gas_total, 2))
| true |
e8e74b30ac6da31bb4907216ea45f4a3136c23cb | eembees/molstat_water | /rotation.py | 2,600 | 4.15625 | 4 | ## rotation.py Version 1.0
## Written by Magnus Berg Sletfjerding (eembees)
###########################################################
"""Rotation Functions, inspired by
http://paulbourke.net/geometry/rotate/
Verified as working 01/07/17 by eembees"""
"""Importing modules"""
import numpy as np
from math import pi, sin, cos, sqrt
def rotation3d(axis1, axis2, point, angle):
"""Rotates a point around an arbitrary axis in a 3D space
INPUTS:
*axis1 -- 3d (xyz) array of 1st axis point
*axis2 -- 3d (xyz) array of 2nd axis point
*point -- 3d (xyz) array of point to be rotated
*angle -- angle (radians) of rotation
Positive angles are counter-clockwise.
"""
#Translate axis to (virtual) origin, define new point ax
ax = point - axis1
axis1_neg = [-x for x in axis1]
axis2_neg = [-x for x in axis2]
#Initialize virtual rotation point rot
rot = [0.0, 0.0, 0.0]
# Axis direction vector (normalized)
N = map(sum, zip(axis2, axis1_neg)) # axis vector
sqsum = sqrt(sum((N[i]**2) for i in range(3)))
direction = [N[i]/sqsum for i in range(3)]
# Simplifying 3d rotation matrix factors - cosine, sine, translation factor
co = cos(angle)
tr = (1-cos(angle))
si = sin(angle)
x = direction[0]
y = direction[1]
z = direction[2]
# Matrix 'D'[3x3] 3D rotation matrix
d11 = tr*x**2 + co
d12 = tr*x*y - si*z
d13 = tr*x*z + si*y
d21 = tr*x*y + si*z
d22 = tr*y**2 + co
d23 = tr*y*z - si*x
d31 = tr*x*z - si*y
d32 = tr*y*z + si*x
d33 = tr*z**2 + co
# # Define rot
rot[0] = d11 * ax[0] + d12 * ax[1] + d13 * ax[2]
rot[1] = d21 * ax[0] + d22 * ax[1] + d23 * ax[2]
rot[2] = d31 * ax[0] + d32 * ax[1] + d33 * ax[2]
# # Define output point as rotation point transformed back
newpoint = rot + axis1
return newpoint
if __name__ == '__main__':
import extract as ex
a, b, c = ex.readfile("w6.xyz") # # reading file
# Test for distances > paste this after rotation to see if the rotation maintains accurate distance
'''
dlist = []
d = 0
for i in range(3):
d += c[1][i]-c[0][i]
d = np.sqrt(d)
dlist.append(d)
d = 0
for i in range(3):
d += c[1][i]-c[2][i]
d = np.sqrt(d)
dlist.append(d)
d = 0
for i in range(3):
d += c[0][i]-c[2][i]
d = np.sqrt(d)
dlist.append(d)
dist = np.sqrt(sum([i**2 for i in dlist]))
print "DISTANCE BEFORE: \n", dist
'''
c[1] = rotation3d(c[0], c[2], c[1], 1*pi)
ex.writefile("w6_rotated.xyz", a, b, c) # # Writing file
| true |
7c57ed755f03c05a03c281e2b9a03529f8b441a2 | Re-Creators/ScriptAllTheThings | /Temperature Scale Converter/temperature_scale_converter.py | 1,211 | 4.5 | 4 | """
Temperature Scale Converter
- Inputs the value from the user and converts it to Fahrenheit,Kelvin & Celsius
Author : Niyoj Oli
Date : 01/10/21
"""
temp = input("Input the temperature you would like to convert? (e.g., 45F, 102C, 373K ) : ")
degree = float(temp[:-1]) # the first value of the input is taken as the degree
i_convention = temp[-1] # second value becomes the unit
if i_convention.upper() == "C":
result_1 = float((degree*1.8)+32)
o_convention_1 = "Fahrenheit"
result_2 = float(degree+273.15)
o_convention_2 = "Kelvin"
elif i_convention.upper() == "F":
result_1 = float((degree-32)/1.8)
o_convention_1 = "Celsius"
result_2 = float(result_1+273.15)
o_convention_2 = "Kelvin"
elif i_convention.upper() == "K":
result_1 = float((degree-273.15)*1.8+32)
o_convention_1 = "Fahrenheit"
result_2 = float(degree-273.15)
o_convention_2 = "Celsius"
else:
print("Input proper convention.")
quit() # stops the program and code after this will not be executed
print("The temperature in", o_convention_1, "is", result_1, "degrees. \nThe temperature in", o_convention_2, "is",
result_2, "degrees.") # \n represents new line
| true |
efc8169de6a436f2ba9910ae37a8526d92bd7456 | JuliasBright/Python | /Simple Calculator.py | 1,685 | 4.3125 | 4 | import sys
while True:
print("Welcome To My Simple Calculator")
print("Enter this Abbreviations To Continue")
print("Enter + for Adding")
print("Enter - for Substractiing")
print("Enter * for Multiplication")
print("Enter / for Dividing")
print("Enter ** for Exponation")
print("To quit Enter Q")
user_input = input(":")
if user_input == "Q":
sys.exit()
elif user_input == "+":
print("You have Enter Adding")
num1 = (float(input("You have to Enter a number")))
num2 = (float(input("Enter another number")))
result = (str(num1 + num2))
print(result)
elif user_input == "-":
print("You have Enter Substraction")
num1 = (float(input("You have to Enter a number")))
num2 = (float(input("Enter another number")))
result = (str(num1 - num2))
print(result)
elif user_input == "*":
print("You have Enter Adding")
num1 = (float(input("Enter a number")))
num2 = (float(input("Enter a number")))
result = (str(num1 * num2))
print(result)
elif user_input == "/":
print("You have Enter Adding")
num1 = (float(input("Enter a number")))
num2 = (float(input("Enter a number")))
result = (str(num1 / num2))
print(result)
elif user_input == "**":
print("You have Enter Adding")
num1 = (float(input("Enter a number")))
num2 = (float(input("Enter a number")))
result = (str(num1 ** num2))
print(result)
else:
sys.exit()
print("You have enter the wrong choice Goodbye")
| true |
5a5bfac15fdf423e125b8aa56655bdb3dbccff7a | Gagan-453/Python-Practicals | /Searching names from a list.py | 1,103 | 4.1875 | 4 | # Searching elements in a list
lst=['Gagan Adithya', 'Advith', 'Harsha', 'Praveen']
for i in range(len(lst)):
lst[i] = lst[i].lower() #Converting all the names in the list into lower case letters
print(lst)
x = input("enter element to search:")
x = x.lower() #Converting all the letters into lower case letters from the input
x = x.lstrip() #Removing all the spaces from the input at left
x = x.rstrip() #Removing all the spaces from the input at right
for i in lst:
if x in i:
print(i)
continue
# Alternate Method
lst=['Gagan Adithya', 'advith', 'Harsha', 'Praveen', 'Ranjeet']
x = input("Enter element to search:") #taking input from the user
x = x.strip() #Removing the spaces from beginning or end of the name from the input
for i in range(len(lst)):
for j in lst:
if x.lower() in lst[i].lower(): #Converting all letters into lower case letters from the input and all elements in the list and checking if input is in the list
print(lst[i]) #if input is in list print the name which is in lst
break # Stopping the loop
| true |
3756486b3c91b557bff353dff8708ef25cca9a32 | Gagan-453/Python-Practicals | /GUI/Canvas/Creating oval.py | 1,375 | 4.875 | 5 | # Creating Oval using Canvas
from tkinter import *
#Create a root window
root = Tk()
# var c is Canvas class object
# root is the name of the parent window, bg is background colour, height is the height of the window and width is the breadth of window, cursor represents the shape of the cursor in the canvas
c = Canvas(root, bg = 'green', height = 700, width = 1200, cursor = 'star')
# create_oval() function can used to create oval or circle
# (100, 100, 400, 300) are pixels, which creates an oval in the rectangular area defined by the top left coordinates (100, 100) and bottom lower coordinates (400, 300)
# (100, 100) represents 100 pixels from the top left corner and 100 pixels to down from that point, this is where an oval is made
# (400, 300) represents 400 pixels from top left corner and 300 pixels down from that point(400 pixels from top left corner), these are measurements of the oval
# Width specifies the width of the line, fill specifies the colour of the line, outline specifies the colour of the border, activefill represents the colour to be filled when the mouse is placed on the oval
id = c.create_oval(100, 100, 400, 300, width = 5, fill='yellow', outline = 'red', activefill = 'green')
#Once the Canvas is created, it should be added to the root window. Then only it will be visible. This is done using pack() method
c.pack()
root.mainloop() | true |
44c151aff1f59e0ca9418405b9a4d7ba2ce98f30 | Gagan-453/Python-Practicals | /GUI/Canvas/Creating images.py | 939 | 4.125 | 4 | #We can display an image with the help of create_image function
from tkinter import *
#Create a root window
root = Tk()
#Create Canvas as a child to root window
c = Canvas(root, bg='white', height=700, width=1200)
#Copy images into files
file1 = PhotoImage(file="Peacock.png")
file2 = PhotoImage(file='Screenshot (40).png')
#The image is displayed relative to the point represented by the coordinates (500, 200)
#The image can be placed in any direction from this point indicated by anchor (8 Directions - NW, N, NE, E, SE, S, SW, W, CENTER)
#Image to be displayed is file1 and 'activeimage' is the image to be shown when the cursor is placed on the image
id = c.create_image(500,200, anchor=NE, image=file1, activeimage=file2)
#Create some text
id = c.create_text(800, 500, text='This is a thrilling photo', font=('Helvetica', 30, 'bold underline'), fill='blue')
#Add canvas to the root
c.pack()
#Wait for any events
root.mainloop() | true |
554f38054fbb5da57d3a88668beb4acae711007d | Gagan-453/Python-Practicals | /GUI/Frame/Frame and Widget.py | 1,701 | 4.375 | 4 | # FRAME Container
#a frame is similar to canvas that represents a rectangular area where some text or widgets can be displayed
from tkinter import *
#Create root window
root = Tk()
#Give a title for root window
root.title('Gagan\'s frame')
#Create a frame as child to root window
f = Frame(root, height=400, width=500, bg='yellow', cursor='cross')
# f is the object of Frame class
# The options 'height' and 'width' represent the height and width of the frame in pixels
# 'bg' represents the back ground colour to be displayed and 'cursor' indicates the type of the cursor to be displayed in the frame
#Attach the frame to the root window
f.pack()
#Let the root window wait for any events
root.mainloop()
# WIDGETS
#A widget is a GUI component that is displayed on the screen and can perform a task as desired by the user
#To create widget suppose Button widget, we can create an object of the Button class as:
# b = Button(f, text='My Button') # 'f' is frame object to which the button is added, 'My Button is the text that is displayed on the button
#When the user interacts with a widget, he will generate an event, these events should be handled by writing functions or routines, these are called event handlers
# Event handler example:
#def ButtonClick(self):
# print('You have clicked me') #This message should be displayed when the user clicks on Button 'My Button'
# When user clicks on the button, that clicking event should be linked with the 'event handler' function
# This is done using bind() method
#Example for bind():
# b.bind('<Button-1>, ButtonClick) # 'b' represents the push button and <Button-1> indicates the left mouse button, linked to the function ButtonClick()
| true |
21e92d5add01747577aac38d6d9e46180f0492eb | Gagan-453/Python-Practicals | /GUI/Frame/Listbox Widget.py | 2,547 | 4.40625 | 4 | # LISTBOX WIDGET
# It is useful to display a list of items, so that he can select one or more items
from tkinter import *
class ListBox:
def __init__(self, root):
self.f = Frame(root, width=700, height=400)
#Let the frame will not shrink
self.f.propagate(0)
# Attach the frame to the root window
self.f.pack()
# Create a label
self.lbl = Label(self.f, text='Click one or more universities below:', font=('Calibri 14'))
self.lbl.place(x=50, y=50)
#Create List box with university names
# 'fg' option represents the colour of the text in the list box, 'bg' represents the back ground colour, 'height' represents the height of the list box, 'selectmode' option represents to select single or multiple items from the box
# 'selectmode' can be 'BROWSE', 'SINGLE', 'MULTIPLE', 'EXTENDED'
self.lb = Listbox(self.f, font='Arial 12 bold', fg='green', bg='yellow', height=10, selectmode=MULTIPLE)
self.lb.place(x=50, y=100)
#Using for loop, insert items into list box
for i in ["Standford University", "Oxford University", "Texas A&M University", "Cambridge University", "University of California"]:
self.lb.insert(END, i) #We can insert items into list box using insert() method
# Bind the ListboxSelect event to on_select() method
self.lb.bind('<<ListboxSelect>>', self.on_select)
# Create a text box to display selected items
self.t = Text(self.f, width=40, height=6, wrap=WORD)
self.t.place(x=300, y=100)
def on_select(self, event):
#Create an empty list
self.lst = [ ]
#Know the indexes of the selected items
# We can know the selected items in the list box using curselection() method
indexes = self.lb.curselection()
# Retrieve the items names depending on indexes
# Append the items names to the list
# We can get the selected items from indexes using get(index) method
for i in indexes:
self.lst.append(self.lb.get(i))
# Delete the previous content of the text box
self.t.delete(0.0, END)
# Insert the new contents into the text box
self.t.insert(0.0, self.lst)
# Create root window
root = Tk()
# title for the root window
root.title("List box")
# Create object to ListBox class
obj = ListBox(root)
# Handle any events
root.mainloop() | true |
d96e1b7876aebe651540e50fa717d03bd162c853 | Gagan-453/Python-Practicals | /GUI/Frame/Button Widget/Arranging widgets in a frame/Place layout manager.py | 1,899 | 4.5625 | 5 | # PLACE LAYOUT MANAGER
# Place layout manager uses place() method to arrange widgets
#The place() method takes x and y coordinates of the widget along with width and height of the window where the widget has to be displayed
from tkinter import *
class MyButton:
#Constructor
def __init__(self, root):
#Create a frame as child to root window
self.f = Frame(root, height=400, width=500)
#Let the frame will not shrink
self.f.propagate(0)
#Attach the frame to root window
self.f.pack()
#Create 3 push buttons and bind them to buttonClick method and pass a number
self.b1 = Button(self.f, text='Red', command= lambda: self.buttonClick(1))
self.b2 = Button(self.f, text='Green', width=15, height=2, command= lambda: self.buttonClick(2))
self.b3 = Button(self.f, text='Blue', width=15, height=2, command= lambda: self.buttonClick(3))
#Attach buttons to the frame
self.b1.place(x=20, y=30, width=100, height=50) #Display at (20, 30), coordinates in the window 100 px width and 50 px height
self.b2.place(x = 20, y = 100, width=100, height=50) # Display at (20, 100)
self.b3.place(x=200, y=100, width=100, height=50) #Display at (200, 100)
#Method to be called when the Button is clicked
def buttonClick(self, num):
#Set background color of the frame depending on the button clicked
if num==1:
self.f["bg"] = 'red'
print('You have chosen Red')
if num==2:
self.f["bg"] = 'green'
print('You have chosen Green')
if num==3:
self.f["bg"] = 'blue'
print('You have chosen Blue')
#Create root window
root = Tk()
#Create an object to MyButton class
mb = MyButton(root)
#The root window handles the mouse click event
root.mainloop() | true |
c0309348cb3d4dba07c8d321cbc157e5dbdd6d0f | Gagan-453/Python-Practicals | /GUI/Frame/Menu Widget.py | 1,979 | 4.1875 | 4 | # MENU WIDGET
# Menu represents a group of items or options for the user to select from.
from tkinter import *
class MyMenu:
def __init__(self, root):
# Create a menubar
self.menubar = Menu(root)
# attach the menubar to the root window
root.config(menu=self.menubar)
# create file menu
# 'tearoff' can be 0 or 1
self.filemenu = Menu(root, tearoff=0)
# create menu items in the file menu
# Add options and bind it to donothing() method
self.filemenu.add_command(label="New", command=self.donothing)
self.filemenu.add_command(label="Open", command=self.donothing)
self.filemenu.add_command(label="Save", command=self.donothing)
# add a horizontal line as separator
# This creates a separator after the 3 options "New", "Open", "Save"
self.filemenu.add_separator()
# create another menu item below the separator
self.filemenu.add_command(label='Exit', command=root.destroy)
# add the file menu with a name "file" to the menubar
self.menubar.add_cascade(label="File", menu=self.filemenu)
# create edit menu
self.editmenu = Menu(root, tearoff=0)
# create menu items in edit menu
self.editmenu.add_command(label="Cut", command=self.donothing)
self.editmenu.add_command(label="Copy", command=self.donothing)
self.editmenu.add_command(label="Paste", command=self.donothing)
# add the edit menu with a name 'Edit' to the menubar
self.menubar.add_cascade(label="Edit", menu=self.editmenu)
def donothing(self):
pass
# create root window
root = Tk()
# title for the root window
root.title("A Menu Example...")
# Create object to MyMenu class
obj = MyMenu(root)
# define the size of the root window
root.geometry('600x500')
# handle any events
root.mainloop() | true |
56b0a0a2582b0e26197affa6d27865dbfe5abb26 | Gagan-453/Python-Practicals | /Date and Time.py | 2,356 | 4.5625 | 5 | #The epoch is the point where the time starts
import time
epoch = time.time() #Call time function of time module
print(epoch) #Prints how many seconds are gone since the epoch .i.e.Since the beginning of the current year
#Converting the epoch into date and time
# locatime() function converts the epoch time into time_struct object
import time
t = time.localtime(epoch)
#Retrieve the date from the structure t
d = t.tm_mday
m = t.tm_mon
y = t.tm_year
print('Current date is: %d - %d - %d' %(d, m, y))
#Retrieve the time from the structure t
h = t.tm_hour
m = t.tm_min
s = t.tm_sec
print('Current time is: %d:%d:%d' %(h, m, s))
print('----------------------------------------------')
import time
t = time.ctime(epoch) #ctime() with epoch seconds
print(t)
#Using ctime() without epoch
import time
t = time.ctime() #ctime() without epoch time
print(t) #Current date and time
print('----------------------------------------------')
#Using datetime module to know current date and time
# now() method can be used to access day, month and year using the attributes day, month, year. Similarly, we can use hour, minute, second
from datetime import * #import datetime module
now = datetime.now()
print(now)
print('Date now: {}/{}/{}' .format(now.day, now.month, now.year)) #Retrieve current date using now() method
print('Time now: {} : {} : {}' .format(now.hour, now.minute, now.second)) #Retrieve current time using now() method
print('----------------------------------------------')
#Program to know today's date and time
from datetime import *
tdm = datetime.today() #today() of datetime class gives date and time
print("Today's date and time = ", tdm)
td = date.today() # today() of date class gives date only
print("Today's date = ", td)
print('----------------------------------------------')
#Combining date and time
from datetime import *
d = date(2020, 5, 27) #Create date class object and store some date
t = time(15, 30, 24)
dt = datetime.combine(d, t) #Combine method of 'datetime' class used to combine date and time objects
print(dt)
print('----------------------------------------------')
#Create a datetime object and then change its contents
from datetime import *
dt1 = datetime(year = 2020, month = 10, day = 27, hour = 9, minute = 45) #Create a datetime object
print(dt1)
dt2 = dt1.replace(year = 2008, hour = 17, month = 5)
print(dt2) | true |
ec4fc0042d9e6100b485588b60be49413925bcb7 | Gagan-453/Python-Practicals | /Exceptions.py | 2,030 | 4.59375 | 5 | # Errors which can be handled are called 'Exceptions'
# Errors cannot be handled but exceptions can be handled
#to handle exceptions they should be written in a try block
#an except block should be written where it displays the exception details to the user
#The statements in thefinally block are executed irrespective of whether there is an exception or not
# SYNTAX:
#try:
# statements
#except exceptionname1:
# handler1
#except exceptionname2: #A try block can be followed by several except blocks
# handler2
#else:
# statements
#finally:
# statements
try:
2/0
except ZeroDivisionError as ZDE:
print('Division by zero is not possible')
print('Please don\'t input zero as input')
else:
print('Solution is calculated') #if zero is not given as input print 'Solution is calculated
finally:
print('Problem Solved') # else block and finally block are optional
print('--------------------')
# Using the try block with finally block
try:
x = int(input('Enter a number: '))
y = 1/x
finally:
print('No exception')
print('The inverse is: ', y)
print('--------------------')
# The assert statement
# This statement is used to check whether a condition is True or not
# If the condition is False then an AssertionError is raised
try:
x = int(input('Enter a number between 5 and 10:'))
assert x>=5 and x<=10 #If these conditions fulfill the input
print('The number entered: ', x) #Print the number
except AssertionError:
print('Wrong input Entered: ', x)
print('--------------------')
#Passing message if the input is not correct
try:
x = int(input('Enter a number between 5 and 10:'))
assert x>=5 and x<=10, 'Your input is incorrect' #If these are False, print('Your input is incorrect')
print('The number entered: ', x) #Print the number
except AssertionError as obj: #We can catch the expression as an object that contains some description about the exception
print(obj)
# except:
# statements
# 👆This catches all types of exceptions
| true |
58d37c8c9a0be25faee85b7d15e6a1958cbf466f | harshbhardwaj5/Coding-Questions- | /Allsubarrayrec.py | 501 | 4.15625 | 4 | # Python3 code to print all possible subarrays
def printSubArrays(arr, start, end):
# Stop if we have reached the end of the array
if end == len(arr):
return
# Increment the end point and start from 0
elif start > end:
return printSubArrays(arr, 0, end + 1)
# Print the subarray and increment the starting
# point
else:
print(arr[start:end + 1])
return printSubArrays(arr, start + 1, end)
# Driver code
arr = ["1, 2, 3,4"]
printSubArrays(arr, 0, 0)
| true |
93fe621719192fd6fc2a29f328bdb0181be8ba54 | ncamperocoder1017/CIS-2348 | /Homework1/ZyLabs_2_19.py | 1,885 | 4.125 | 4 | # Nicolas Campero
# 1856853
# Gather information from user of ingredients and servings amount
print('Enter amount of lemon juice (in cups):')
l_juice_cups = float(input())
print('Enter amount of water (in cups):')
water_cups = float(input())
print('Enter amount of agave nectar (in cups):')
agave_cups = float(input())
print('How many servings does this make?')
servings = int(input())
# output amount of ingredients for x amount of servings
print('\n', end='')
print('Lemonade ingredients - yields', '{:.2f}'.format(servings), 'servings')
print('{:.2f}'.format(l_juice_cups), 'cup(s) lemon juice')
print('{:.2f}'.format(water_cups), 'cup(s) water')
print('{:.2f}'.format(agave_cups), 'cup(s) agave nectar')
print('\n', end='')
print('How many servings would you like to make?')
servings_to_make = float(input())
# adjust amounts of each ingredient to match servings amount
print('\n', end='')
print('Lemonade ingredients - yields', '{:.2f}'.format(servings_to_make), 'servings')
multiple_of_servings = float(servings_to_make / servings)
lemon_after_servings = l_juice_cups * multiple_of_servings
water_after_servings = water_cups * multiple_of_servings
agave_after_servings = agave_cups * multiple_of_servings
print('{:.2f}'.format(lemon_after_servings), 'cup(s) lemon juice')
print('{:.2f}'.format(water_after_servings), 'cup(s) water')
print('{:.2f}'.format(agave_after_servings), 'cup(s) agave nectar')
# convert ingredient measurements from part 2 to gallons
lemon_gallons = lemon_after_servings / 16.00
water_gallons = water_after_servings / 16.00
agave_gallons = agave_after_servings / 16.00
print('\n', end='')
print('Lemonade ingredients - yields', '{:.2f}'.format(servings_to_make), 'servings')
print('{:.2f}'.format(lemon_gallons), 'gallon(s) lemon juice')
print('{:.2f}'.format(water_gallons), 'gallon(s) water')
print('{:.2f}'.format(agave_gallons), 'gallon(s) agave nectar')
| true |
e38197efcd64d6ad928d207bf789273cb0a6fb08 | cr8ivecodesmith/basic-programming-with-python | /lpthw/ex11.py | 756 | 4.25 | 4 | # Exercise 11: Asking questions
print('How old are you?', end=' ')
age = input()
print('How tall are you?', end=' ')
height = input()
print('How much do you weigh?', end=' ')
weight = input()
print("So you're %r old, %r tall and %r heavy." % (age, height, weight))
# Note
# Notice that we put an end=' ' after the string in the print command. This so
# we can change the default way Python ends a print command from a newline (\n)
# to just using a space (' ').
# Study Drills
# 1. Go online and find out what Python's input() does.
# 2. Can you find other ways to use it? Try some of samples you find.
# 3. Write another "form" like this to ask some other questions.
# Personal Challenge
# 4. Remove the end=' ' in the print command. What happens?
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.