blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3867392dee2e78d71c9a8bf99e1372a46a0eb726 | beyondvalence/thinkpython | /tp.05.py | 1,537 | 4.15625 | 4 | #! Thinking Python, Chp05, conditionals and recursion
#5.1 modulus operator
print("5.1")
print("156%100=")
print(156%100)
#5.9 E2 stack diagrams for recursive functions
print("5.9 E2")
def do_n(f,n):
if n<=0:
return
f()
do_n(f, n-1)
def print_now(s='now'):
print(s)
do_n(print_now,6)
#5.11 keyboard input
print("5.11")
text=input('type a number here:\n')
print(text)
#5.14 exercises
#5.14 E3, Fermat's Last Theorem
def fermat_check(a=1,b=1,c=1,n=3):
a=int(input('a= '))
b=int(input('b= '))
c=int(input('c= '))
n=int(input('n= '))
if a < 1 or b < 1 or c < 1:
print("a,b,c need to be positive integers")
fermat_check()
elif n < 3:
print("n needs to be greater than 2:")
fermat_check()
left=a**n+b**n
right=c**n
yn = (left==right)
return yn
def fermat_prompt():
result = fermat_check()
if result:
print("Holy smokes, Fermat was wrong!")
return
else:
print("No, that doesn't work. Theorem still holds.")
text = input('Try again? ')
if text=='yes':
fermat_prompt()
else:
return
#5.14 E4, Triangles
def is_triangle(a=3,b=4,c=5):
a=float(input("a= "))
b=float(input("b= "))
c=float(input("c= "))
if a < 1 or b < 1 or c < 1:
print("a,b,c must be positive integers")
is_triangle()
elif (a >= b + c) or (b >= a + c) or (c >= a + b):
print("Sides values not viable")
is_triangle()
else:
print("Sides make a valid triangle!")
return True
if __name__ == "__main__":
print("5.14 E3, Fermat's Last Theorem")
fermat_prompt()
print("5.14 E4, Triangles")
is_triangle() | true |
d59b573a9bc93897e130ad223c08f0b22b99bf0b | ankarn/groupIII_twintrons | /groupIII_3'_motif_search.py | 2,605 | 4.125 | 4 | ################################################################################
#
# Search for Group III twinton 3' motifs
# ______________________________________
#
# A program to to find 3' motifs for group III twintrons, given the external
# intron in FASTA format.
#
# ** Program must be in same location as fasta file. **
#
# Assumption: only one sequence submitted in fasta file.
#
# by: Matthew Bennett, Michigan State University
#
################################################################################
# Function to complement a sequence
def complement(sequence):
complement = ""
for i in sequence:
if i == "A":
complement += "T"
elif i == "T":
complement += "A"
elif i == "C":
complement += "G"
elif i == "G":
complement += "C"
return complement
matches = [] #Blank list for potential 3' matches.
while True:
try:
file_nm = input("FASTA file containg your external intron: ")
file = open(file_nm, "r")
break
except FileNotFoundError:
print ("\n", "FASTA file not found", "\n", sep = "")
#First line in FASTA is sequence name, strip of white space and get rid of ">"
seq_name = file.readline().strip()[1:]
# Second fasta line is sequence, strip of white space
seq = file.readline().strip()
# Strip the first 5 bases and last 5 bases, they only apply to external intron
seq = seq[5:-5]
# Reverse the sequence
rev_seq = seq[::-1]
# iterate through sequence and find an "A" to look for pattern:
# abcdef (3–8 nucleotides) f'e'd' A c'b'a' (four nucleotides)
for i, base in enumerate(rev_seq):
if base == "A":
index = i
search_seq_rev = rev_seq[(index-3):index] + rev_seq[(index+1):(index+4)]
search_area_rev = rev_seq[(index+7):(index + 18)]
search_seq_rc = complement(search_seq_rev)
if len(search_seq_rev) == 6:
search_area = search_area_rev[::-1]
check = search_area.find(search_seq_rc)
if check != -1:
total_area_rev = rev_seq[(index-3):(index + 18)]
total_area = total_area_rev[::-1]
match_area = total_area[check:]
match = (match_area)
matches.append(match)
print ("\n", len(matches), " potential 3' motif(s) found in ",\
file_nm, ":", "\n", sep = "")
for i in matches:
print (i)
if len(matches) > 0:
print ("\n", "*** Remember to add 4 bases to the end of any accepted\
matching sequence ***", "\n", sep = "") | true |
ca55b480b5735b4bc0bcb9feb1bb810de93a1007 | andrewrisse/Exercises | /ArrayAndStringProblems/URLify.py | 1,727 | 4.1875 | 4 | """
URLify.py
Creator: Andrew Risse
Drew heavily from example 1.3 in "Cracking the Coding Interview" in attempt to understand and
write their Java version in Python.
This program replaces spaces in a string with '%20'.
Assumptions: the string has sufficient space at the end to hold the additional characters and we are given
the "true" string length.
"""
def URLify(str, trueLength):
numSpaces = countChar(str, 0, trueLength, ' ') # count number of spaces in string
newLength = trueLength - 1 + (numSpaces * 2) # requires 2 spaces to insert %20 since we already have a ' '
lst = list(str) # convert string into a list because Python strings are immutable
if newLength + 1 < len(str): #if there are extra spaces at the end of the string, don't replace those with %20, replace with null
lst[newLength + 1] = '\0'
oldLength = trueLength - 1 # adjust length for next for loop and the fact tha the first index is 0
# work from end of list to front
for oldLength in range(oldLength, -1, -1):
#replace spaces
if lst[oldLength] == ' ':
lst[newLength] = '0'
lst[newLength - 1] = '2'
lst[newLength - 2] = '%'
newLength -= 3
else: #copy character
lst[newLength] = lst[oldLength]
newLength -= 1
str =''.join(lst) #turn list back into a string
return str
# count how many target characters are in the string
def countChar(str, start, end, target):
count = 0
for i in range(start, end):
if (str[i] == target):
count += 1
return count
#test case
print(URLify ("Mr John Smith ", 13))
print(URLify (" This is a test ", 15))
| true |
ac4be20f003f5e94d72f2251cc53f7ef384d02f0 | chunhuayu/Python | /Crash Course/06. Operators.py | 616 | 4.3125 | 4 | # Multiply 10 with 5, and print the result.
>>> print(10*5)
# Divide 10 by 2, and print the result.
>>> print(10/2)
# Use the correct membership operator to check if "apple" is present in the fruits object.
>>> fruits = ["apple", "banana"]
>>> if "apple" in fruits:
print("Yes, apple is a fruit!")
# Use the correct comparison operator to check if 5 is not equal to 10.
>>> if 5 != 10:
print("5 and 10 is not equal")
# Use the correct logical operator to check if at least one of two statements is True.
>>> if 5 == 10 or 4 == 4:
print("At least one of the statements is true")
| true |
0d303b898e689b0460aecb8d16248106d3a0073e | chunhuayu/Python | /Crash Course/0702. Tuple.py | 2,436 | 4.78125 | 5 | # Tuple is immutable
# A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
# Create a Tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple)
('apple', 'banana', 'cherry')
# Access Tuple Items: You can access tuple items by referring to the index number, inside square brackets:
# Return the item in position 1:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple[1])
banana
# Loop Through a Tuple: You can loop through the tuple items by using a for loop.
# Iterate through the items and print the values:
>>> thistuple = ("apple", "banana", "cherry")
>>> for x in thistuple:
print(x)
# Check if Item Exists, To determine if a specified item is present in a tuple use the in keyword:
# Check if "apple" is present in the tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
# Tuple Length : To determine how many items a tuple has, use the len() method:
# Print the number of items in the tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(len(thistuple))
# Add Items: Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
# You cannot add items to a tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> thistuple[3] = "orange" # This will raise an error
>>> print(thistuple)
TypeError: 'tuple' object does not support item assignment
# Remove Items : You cannot remove items in a tuple.
# Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
# The del keyword can delete the tuple completely:
>>> thistuple = ("apple", "banana", "cherry")
>>> del thistuple
>>> print(thistuple) #this will raise an error because the tuple no longer exists
NameError: name 'thistuple' is not defined
# The tuple() Constructor: It is also possible to use the tuple() constructor to make a tuple.
# Using the tuple() method to make a tuple:
>>> thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
>>> print(thistuple)
('apple', 'banana', 'cherry')
>>> t[0] = 'NEW'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-97e4e33b36c2> in <module>()
----> 1 t[0] = 'NEW'
TypeError: 'tuple' object does not support item assignment
| true |
57c29ce26289441922f017c49a645f8cbe9ce17f | rajatpachauri/Python_Workspace | /While_loop/__init__.py | 260 | 4.25 | 4 | # while loop is mostly used for counting
condition = 1
while condition < 10:
print(condition)
condition += 1
# condition -= 1
# to create out own infinite loop
while True:
print('doing stuff')
# for breaking use control+c | true |
1aa840435f3eaabb240f81d193c62b3381f52110 | Aminaba123/LeetCode | /477 Total Hamming Distance.py | 1,306 | 4.1875 | 4 | #!/usr/bin/python3
"""
The Hamming distance between two integers is the number of positions at which
the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the
given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010
(just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2)
= 2 + 2 + 2 = 6.
Note:
Elements of the given array are in the range of 0 to 10^9
Length of the array will not exceed 10^4.
"""
class Solution:
def totalHammingDistance(self, nums):
"""
Brute force, check every combination O(n^2 * b)
check bit by bit
For each bit, the distance for all is #0 * #1
O(n * b)
:type nums: List[int]
:rtype: int
"""
ret = 0
while any(nums): # any not 0
z, o = 0, 0
for i in range(len(nums)):
if nums[i] & 1 == 0:
o += 1
else:
z += 1
nums[i] >>= 1
ret += z * o
return ret
if __name__ == "__main__":
assert Solution().totalHammingDistance([4, 14, 2]) == 6
| true |
0674b8d7de1b0a1f417b11be2eac016d459c8be5 | Aminaba123/LeetCode | /063 Unique Paths II.py | 1,948 | 4.1875 | 4 | """
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
"""
__author__ = 'Danyang'
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
"""
dp
:param obstacleGrid: a list of lists of integers
:return: integer
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
# trivial
if obstacleGrid[0][0]==1 or obstacleGrid[m-1][n-1]==1:
return 0
path = [[0 for _ in range(n)] for _ in range(m)] # possible to optimize by [[0 for _ in range(n+1)]]
path[0][0] = 1 # start
# path[i][j] = path[i-1][j] + path[i][j-1]
for i in range(m):
for j in range(n):
if i==0 and j==0:
continue
if i==0:
path[i][j] = path[i][j-1] if obstacleGrid[i][j-1]==0 else 0
elif j==0:
path[i][j] = path[i-1][j] if obstacleGrid[i-1][j]==0 else 0
else:
if obstacleGrid[i][j-1]==0 and obstacleGrid[i-1][j]==0:
path[i][j] = path[i-1][j]+path[i][j-1]
elif obstacleGrid[i][j-1]==0:
path[i][j] = path[i][j-1]
elif obstacleGrid[i-1][j]==0:
path[i][j] = path[i-1][j]
else:
path[i][j]=0
return path[m-1][n-1]
if __name__=="__main__":
grid = [[0, 0], [1, 1], [0, 0]]
assert Solution().uniquePathsWithObstacles(grid)==0
| true |
a8e56295e5b3d81fc6b63eb549d4a4d4f51dd7ea | Aminaba123/LeetCode | /433 Minimum Genetic Mutation.py | 2,041 | 4.15625 | 4 | #!/usr/bin/python3
"""
A gene string can be represented by an 8-character long string, with choices
from "A", "C", "G", "T".
Suppose we need to investigate about a mutation (mutation from "start" to
"end"), where ONE mutation is defined as ONE single character changed in the
gene string.
For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
Also, there is a given gene "bank", which records all the valid gene mutations.
A gene must be in the bank to make it a valid gene string.
Now, given 3 things - start, end, bank, your task is to determine what is the
minimum number of mutations needed to mutate from "start" to "end". If there is
no such a mutation, return -1.
Note:
Starting point is assumed to be valid, so it might not be included in the bank.
If multiple mutations are needed, all mutations during in the sequence must be
valid.
You may assume start and end string is not the same.
"""
class Solution:
def is_neighbor(self, p, q):
diff = 0
for a, b in zip(p, q):
if a != b:
diff += 1
if diff > 1:
return False
return True
def minMutation(self, start, end, bank):
"""
BFS, record level and avoid loop
Similar to 127 Word Ladder
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
q = [start]
visited = {start}
lvl = 0
while q:
cur_q = []
for e in q:
if e == end:
return lvl
for t in bank:
if t not in visited and self.is_neighbor(e, t):
visited.add(t)
cur_q.append(t)
lvl += 1
q = cur_q
return -1
if __name__ == "__main__":
assert Solution().minMutation("AACCTTGG", "AATTCCGG", ["AATTCCGG","AACCTGGG","AACCCCGG","AACCTACC"]) == -1
assert Solution().minMutation("AACCGGTT", "AAACGGTA", ["AACCGGTA", "AACCGCTA", "AAACGGTA"]) == 2
| true |
64ebeedfbf3d242316451493e0407916896c2f77 | Aminaba123/LeetCode | /403 Frog Jump.py | 2,164 | 4.28125 | 4 | """
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The
frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river
by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.
If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can
only jump in the forward direction.
Note:
The number of stones is >= 2 and is < 1,100.
Each stone's position will be a non-negative integer < 231.
The first stone's position is always 0.
Example 1:
[0,1,3,5,6,8,12,17]
There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.
Return true. The frog can jump to the last stone by jumping
1 unit to the 2nd stone, then 2 units to the 3rd stone, then
2 units to the 4th stone, then 3 units to the 6th stone,
4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:
[0,1,2,3,4,8,9,11]
Return false. There is no way to jump to the last stone as
the gap between the 5th and 6th stone is too large.
"""
__author__ = 'Daniel'
class Solution(object):
def canCross(self, stones):
"""
F, step table
Let F[i] be stone at position i,
dp with a set as the table cell.
:type stones: List[int]
:rtype: bool
"""
F = {}
for stone in stones:
F[stone] = set()
F[0].add(0)
for stone in stones:
for step in F[stone]:
for i in (-1, 0, 1):
nxt = stone+step+i
if nxt != stone and nxt in F:
F[nxt].add(step+i)
return True if F[stones[-1]] else False
if __name__ == "__main__":
assert Solution().canCross([0, 2]) == False
assert Solution().canCross([0, 1, 3, 5, 6, 8, 12, 17]) == True
assert Solution().canCross([0, 1, 2, 3, 4, 8, 9, 11]) == False
| true |
24ba1fb74133913ff4642b3168f44b775cf64b7c | Aminaba123/LeetCode | /384 Shuffle an Array.py | 1,372 | 4.28125 | 4 | """
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
"""
import random
__author__ = 'Daniel'
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type size: int
"""
self.original = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return list(self.original)
def shuffle(self):
"""
Returns a random shuffling of the array.
like shuffle the poker cards
in-place shuffling and avoid dynamic resizing the list
:rtype: List[int]
"""
lst = self.reset()
n = len(lst)
for i in xrange(n):
j = random.randrange(i, n)
lst[i], lst[j] = lst[j], lst[i]
return lst
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle() | true |
13684394a6e93a3c95c3c7916fcb88113a22e7a0 | Aminaba123/LeetCode | /088 Merge Sorted Array.py | 1,122 | 4.125 | 4 | """
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The
number of elements initialized in A and B are m and n respectively.
"""
__author__ = 'Danyang'
class Solution(object):
def merge(self, A, m, B, n):
"""
array, ascending order.
basic of merge sort.
CONSTANT SPACE: starting backward. Starting from the end.
:param A: a list of integers
:param m: an integer, length of A
:param B: a list of integers
:param n: an integer, length of B
:return:
"""
i = m-1
j = n-1
closed = m+n
while i >= 0 and j >= 0:
closed -= 1
if A[i] > B[j]:
A[closed] = A[i]
i -= 1
else:
A[closed] = B[j]
j -= 1
# either-or
# dangling
if j >= 0: A[:closed] = B[:j+1]
# if i >= 0: A[:closed] = A[:i+1]
| true |
36bd7b053f22dbde6145ee948b168bb114a1bcfe | Aminaba123/LeetCode | /225 Implement Stack using Queues.py | 1,673 | 4.28125 | 4 | """
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is
empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque
(double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
"""
__author__ = 'Daniel'
class Stack:
def __init__(self):
"""
initialize your data structure here.
One queue cannot mimic the stack, then you should use two queues.
"""
self.q = [[], []]
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
t = 0
if not self.q[t]:
t ^= 1
self.q[t].append(x)
def pop(self):
"""
:rtype: nothing
"""
t = 0
if not self.q[t]:
t ^= 1
while len(self.q[t]) > 1:
self.q[t^1].append(self.q[t].pop(0))
return self.q[t].pop()
def top(self):
"""
:rtype: int
"""
popped = self.pop()
t = 0
if not self.q[t]:
t ^= 1
self.q[t].append(popped)
return popped
def empty(self):
"""
:rtype: bool
"""
return not self.q[0] and not self.q[1]
| true |
85068b845fc62bc3ca6b9307072225de0f5d380f | Aminaba123/LeetCode | /353 Design Snake Game.py | 2,043 | 4.4375 | 4 | """
Design a Snake game that is played on a device with screen size = width x height.
"""
from collections import deque
__author__ = 'Daniel'
class SnakeGame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
:type width: int
:type height: int
:type food: List[List[int]]
"""
self.w = width
self.h = height
self.food = deque(food)
self.body = deque([(0, 0)])
self.dirs = {
'U': (-1, 0),
'L': (0, -1),
'R': (0, 1),
'D': (1, 0),
}
self.eat = 0
def move(self, direction):
"""
Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
:type direction: str
:rtype: int
"""
x, y = self.body[0]
dx, dy = self.dirs[direction]
x += dx
y += dy
fx, fy = self.food[0] if self.food else (-1, -1)
if x == fx and y == fy:
self.food.popleft()
self.eat += 1
else:
self.body.pop()
if (x, y) in self.body or not (0 <= x < self.h and 0 <= y < self.w):
# possible to use set to accelerate check
return -1
self.body.appendleft((x, y))
return self.eat
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction)
if __name__ == "__main__":
game = SnakeGame(3, 2, [[1, 2], [0, 1]])
for char, expect in zip('RDRULU', [0, 0, 1, 1, 2, -1]):
assert game.move(char) == expect
| true |
0f0c2b71165908b69143488b544ec20e7192961b | jiankangliu/baseOfPython | /PycharmProjects/02_Python官方文档/一、Python初步介绍/03_Python控制流结构/3.2判断结构.py | 1,030 | 4.125 | 4 | #3.2.1 if-else语句
#例1 求较大值
num1=eval(input("Enter the first number: "))
num2=eval(input("Enter the second number: "))
if num1>num2:
print("The larger number is:",num1)
else:
print("The larger number is: ",num2)
#3.2.2 if语句
firstNumber=eval(input("Enter the first number: "))
secondNumber=eval(input("Enter the second number: "))
thirdNumber=eval(input("Enter the third number: "))
max=firstNumber
if secondNumber>firstNumber:
max=secondNumber
if thirdNumber>max:
max=thirdNumber
print("The largest number is: ",max)
#3.2.3 嵌套的if-else语句
#例4 灯标的意义
color=input("Enter a color (BLUE or RED): ")
mode=input("Enter a mode (STEADY or FLASHING): ")
result=""
color=color.upper()
mode=mode.upper()
if color=="BLUE":
if mode=="STEADY":
result="Clear View"
else:
result="Clouds Due"
else:
if mode=="STEADY":
result="Rain Ahead"
else:
result="Snow Ahead"
print("The weather forecast is",result)
| true |
5a391b6015b94af3800dba89cf6ed07e94d1f445 | daniyaniazi/Python | /COLLECTION MODULE.py | 2,510 | 4.25 | 4 | """COLLECTION MODULE IN PYTHON """
#LIST TUPLE DICTIONARY SET ARE CONTAINER
#PYTHON HAS COLLECTION MODULE FOR THE SHORTCOMMING OF DS
#PRVIDES ALTERNATIVES CONTAINER OF BUILTIN DATA TYPES
#specializex collection datatype
"""nametupele(), chainmap, deque, counter, orderedDict, defaultdic , UserDict, UserList,UserString"""
"""** namedtuple()**"""
# return a tuple with named entry there will be named assigned to each value inside tuple to overcome the peoblem of acessing with the index
from collections import namedtuple
a=namedtuple('courses','name,technology')
b=a('machine learning','python')
print(b)
#using list
c=a._make(["artificial intelligence","python"])
print(c)
"""** deque**"""
#pronounced as deck
#is an optimised list to perform insertion and deletion easily
#way to precisely
from _collections import deque
l=['e','d','u','c','a','t','i','o','n']
d=deque(l)
print(d)
d.append("python") #at the end
print(d)
d.appendleft("version") #at the end
print(d)
d.pop()
print(d) #aT THE END REMOVE
d.popleft()
print(d)
"""**chain map **"""
#is a dictionary like class for creating a single view of multiple mapping
#return a list of several other dictionaries
from collections import ChainMap
dic1 ={1:"course",2:"python"}
dic2={3:"collection mpdule",4:"chainmap"}
cm=ChainMap(dic1,dic2)
print(cm)
"""Counter"""
#dictionary subclass for counting hashable objects
from collections import Counter
c1=[1,1,22,2,3,3,4,5,6,6,7,7,3,9]
c2=Counter(c1)
print(c2)
print(list(c2.elements())) #show elements and the times of their occurence
print(c2.most_common())
sub={3:1 , 6:1 , 22:1} #subtrac elemets times
print(c2.subtract(sub))
print(c2.most_common())
""""OrderedDict """
#dict subclass which remembers the order in which entries is done
#postion will not change
from collections import OrderedDict
od=OrderedDict()
od[1]="e"
od[2]="d"
od[3]="u"
print(od)
print(od.keys())
print(od.items())
print(od)
od[1]="k"
print(od)
""" defaultdic"""
#dic subclass which cALLS A FACTORY FUNCTION TO SUPPLY MISSING VALUE
#doesnt show any error when a missing key value is call in a dictionary
from collections import defaultdict
defdic=defaultdict(int)
defdic[1]='python'
defdic[2]='numpy'
defdic[3]='matplotlib'
print(defdic)
print(defdic[4]) #no error 0 o/p
#keyerror
""" UserDict """
#wrapper around dic object for easier dic sub classing
""" Userlist """
#wrapper around list object for easier lisxt sub classing
""" Userstring """
#wrapper around string object for easier string sub classing
| true |
aca916cd7150ccdc1dc3ddad48f5b41d53007f7f | StealthAdder/SuperBasics_Py | /functions.py | 2,101 | 4.46875 | 4 | # function is collection of code
# they together work to do a task
# they are called using a function call.
# to create a function we use a keyword called "def"
# --------------------------------------------------
# create a function.
def greetings():
print("Hello Dude!")
greetings() #calling the function
# OUTPUT: Hello Dude!
# ---------------------------------------------------------------------------------------
# passing a parameter
def greetings(name): #here we are telling the function to use the argument "name" while calling the function.
print("Hello " + name)
greetings("StealthAdder") #calling the function with a parameter.
# OUTPUT: Hello StealthAdder
# --------------------------------------------------------------------------------------
# passing multiple parameters
def func1(para1, para2):
print("Going to print the first parameter here " + para1 + " the next over here " + para2)
func1("parameter1", "parameter2")
# OUTPUT: Going to print the first parameter here parameter1 the next over here parameter2
# ----------------------------------------------------------------------------------------------
# useful example printing name of that persons with dob
def greets(name, dob):
print("Hey " + name + ", You Birthday is " + dob)
greets("StealthAdder", "07Aug")
# OUTPUT:Hey StealthAdder, You Birthday is 07Aug
# ----------------------------------------------------------------------------------------------
# Return function in function
# Using return we return some imformation back from the function
# Nothing after return function inside a function will be execute, it just breaks the code.
def cube(num):
return num * num * num
print("Hey") #this is not going to be printed (code is out of reach)
result = cube(3) #value returned from cube() is saved to variable result.
print(result) #prints the value
print(str(result)) #can print even in string format.
# OUTPUT: 27
# ------------------------------------------------------------------------------------------------
| true |
89edd52a8e28902a6331f7d939e3a369e3e14e69 | Aravind-2001/python-task | /4.py | 242 | 4.15625 | 4 | #Python program to divided two numbers using function
def divided_num(a,b):
sum=a/b;
return sum;
num1=int(input("input the number one: "))
num2=int(input("input the number one :"))
print("The sum is",divided_num(num1,num2))
| true |
bf2443eb20578d0e4b5765abc5bd6d3c46fabdc6 | leelaram-j/pythonLearning | /com/test/package/lists.py | 1,231 | 4.125 | 4 | """
List in python
written inside []
sequence type, index based starts from 0
mutable
"""
a = [1, 2, 3, 4, 5]
print(a)
print(type(a))
print(a[1])
# array slicing
print("Slicing")
print(a[0:3])
print(a[2:])
print(a[:3])
print("-------------")
a = [1, "sample", True, 10.45, [1, 2, 3, 4]]
print(a)
print(type(a))
print(type(a[1]))
print(a[4][2])
print("-------------")
b = a.copy()
print(b)
print(a)
a.clear()
print(a)
print("-------------")
a = [10, 20, 30, 10, 20, 40, 50, 10]
print(a.count(10))
print(a.index(20))
print(len(a))
print(max(a))
print(min(a))
print(a)
a.pop(0) # values are removed based on index
print(a)
a.remove(10) # values are removed based on actual value
print(a)
print("-------------")
names = ["Ram"]
print(names)
names.append("Sam")
names.append("Kumar")
print(names)
name2 = ["Sara", "Mike"]
names.extend(name2)
print(names)
names.insert(0, "Kiran")
print(names)
print("-------------")
print(list(range(5)))
print(list("leelaram"))
a = [10,50,100, 25, 85]
print(a)
a.sort()
print(a)
a.sort(reverse=True)
print(a)
a = ["z", "a", "y", "b"]
a.sort()
print(a)
a = ["mango", "zebra", "apple"]
a.sort()
print(a)
a = ["mangoes", "zebra", "apples"]
a.sort(key=len)
print(a)
| true |
934f9b2581ab5fa583aaf274d068448b9cc4f0de | sharpchris/coding352 | /8.py | 2,259 | 4.375 | 4 | # Codebites URL: https://codechalleng.es/bites/21/
cars = {
'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk', 'Hawktrailer']
}
space = '+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+'
# 1. Get all Jeeps
def get_all_jeeps(cars=cars):
#produces a list of jeeps
jeeps = cars['Jeep']
#converts list to string, ref: https://stackoverflow.com/questions/5618878/how-to-convert-list-to-string
jeeps_str = ', '.join(jeeps)
#returns the jeeps string
return jeeps_str
#calls the function
print(get_all_jeeps())
print(space)
# 2. Get the first car of every manufacturer
def get_first_of_type(cars=cars):
# loops through the cars dictionary and grabs the keys
first_cars = []
for key in cars.keys():
first_cars.append(cars[key][0])
return first_cars
print(get_first_of_type())
print(space)
# 3. Get all vehicles containing the string 'Trail' in their names
def get_trails(cars=cars):
# makes an empty string that we'll insert trail cars into
trail_cars = []
# loops through teh values in cars
for v in cars.values():
# loops through v, which is the list containing specific models
for i in v:
# Checks if "Trail" is included in name: ref: https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method
if "Trail" in i:
trail_cars.append(i)
elif "trail" in i:
trail_cars.append(i)
return trail_cars
print(get_trails())
print(space)
# 4. Sort the models (values) alphabetically
def sort_models(cars=cars):
# empty list to store all models
all_cars = []
# loop through car models and grab values
for v in cars.values():
# loop through list of cars and extract specific models
for i in v:
# push all models into single list
all_cars.append(i)
# sort dat list bruh
all_cars.sort()
# return dat shat
return all_cars
print(sort_models())
| true |
a017de5cb43b53b1f7c796ab015b91a68f09efdf | abhishekratnam/Datastructuresandalgorithmsinpython | /DataStructures and Algorithms/Recursion/Reverse.py | 445 | 4.1875 | 4 | def reverse(S, start, stop):
"""Reverse elements in emplicit slice S[start:stop]."""
if start < stop - 1:
S[start], S[stop-1] = S[stop - 1], S[start]
reverse(S, start+1, stop - 1)
def reverse_iterative(S):
"""Reverse elements in S using tail recursion"""
start,stop = 0,len(S)
while start < stop - 1:
S[start],S[stop-1] = S[stop - 1], S[start]
start,stop = start+1, stop -1
| true |
e03f40711cfe8a26b38de0c63faaee30e1b0e336 | pragatishendye/python-practicecode | /FahrenheitToCelsius.py | 338 | 4.40625 | 4 | """
This program prompts the user for a temperature in Fahrenheit and returns
the Celsius equivalent of it.
Created by Pragathi Shendye
"""
tempInFahrenheit = float(input('Enter a temperature in Fahrenheit:'))
tempInCelsius = (tempInFahrenheit - 32) * (5 / 9)
print('{} Fahrenheit = {:.2f} Celsius'.format(tempInFahrenheit, tempInCelsius)) | true |
23a9baab1b0308bde129e6d01894f56ea79e3c64 | iresbaylor/codeDuplicationParser | /engine/utils/printing.py | 921 | 4.1875 | 4 | """Module containing methods for pretty-printing node trees."""
def print_node_list(node_list):
"""
Print a list of TreeNodes for debugging.
Arguments:
node_list (list[TreeNode]): a list of tree nodes
"""
for node in node_list:
if node.parent_index is None:
print_node(node, "", 0, node_list)
def print_node(node, indent, level, node_list):
"""
Print a TreeNode for debugging.
Arguments:
node (TreeNode): node to print
indent (str): space to print before node
level (int): depth of node within the tree (0 for root)
node_list (list[TreeNode]): list of TreeNodes to reference children of TreeNode
"""
print(indent, "(", level, ")", node)
for index in node.child_indices:
for node in node_list:
if node.index == index:
print_node(node, indent + " ", level + 1, node_list)
| true |
433453e34c036cf7b04079f06debd27ba3c31e69 | amarish-kumar/Practice | /coursera/coursera_data_structures_and_algorithms/course_1_algorithmic_toolbox/Week_4/binarysearch/binary_search.py | 2,180 | 4.15625 | 4 | #python3
'''Implementation of the binary search algoritm.
Input will contain two lines. First line will
have an integer n followed by n integers in
increasing order. Second line will have an
integer n again followed by n integers. For
each of the integers in the second line, you
have to perform binary search and output the
index of the integer in the set on the first
line else output -1 if it is not there.
'''
sorted_array = list()
def binary_search(num, l, h):
#value containing the index where num resides.
#it will be -1 in case num is not found.
valueToReturn = -1
#if high end is less than the low end, end
#search and return -1.
if h < l :
return valueToReturn
#get the middle element.
mid = int((l+h)/2)
#if num is equal to be searched, return index
#of middle element.
if int(num) == int(sorted_array[mid]):
valueToReturn = mid
#if num is greater than the middle element,
#implement binary search on the upper half
#of the sorted array.
elif int(num) > int(sorted_array[mid]):
valueToReturn = binary_search(num,mid+1,h)
#if num is smaller than the middle element,
#implement binary search on the lower half
#of the sorted array.
elif int(num) < int(sorted_array[mid]):
valueToReturn = binary_search(num,l,mid-1)
return valueToReturn
#read the first line
first_line = input()
#extract the number and the sorted array from
#the first line.
num_first = first_line.split()[0]
sorted_array = first_line.split()[1:]
#read the second line.Put the numbers to be
#searched in a separate list.
second_line = input()
num_second = second_line.split()[0]
input_array = second_line.split()[1:]
#parse the second list and call binary search
#utility for each of the number in the list.
#Save the output of the binary search for each
#of the number in a separate list.
output_array = list()
for num_to_be_searched in input_array:
#search for the index of the number.
output_array.append(binary_search(num_to_be_searched,0,len(sorted_array)-1))
for element in output_array:
print(element,end='')
print(" ",end='')
| true |
a58e51493d43ad0df89b3836366ef7b729223d57 | jnoriega3/lesson-code | /ch6/printTableFunctions.py | 2,680 | 4.59375 | 5 | # this is the printTable function
# parameter: tableData is a list of lists, each containing a word
# we are guaranteed that each list is the same length of words
# this function will print our table right-justified
def printTable( tableData ):
#in order to be able to right-justify each word, we'll need to know the size of all the words. This creates a placeholder that will hold those lengths
colWidths = [0] * len( tableData )
#this for-loop, cycles through each of the lists, and stores the size of the maximum value on each list in colWodths
for eachList in range( len( tableData ) ):
#this utilizes a helper function I created called getMaxSize of List, you'll see how this function works further down on this code
colWidths[eachList] = getMaxSizeofList( tableData[eachList] )
#the line below has been commented so it won't run, but you can take the comment out if you'd like to see the list of values inside colWidths
#print(colWidths)
#this for-loop cycles through each of the words on each list, and right-justifies each of those words using the information acquired about the lengths of each word
for eachWord in range( len( tableData[eachList]) ):
for eachList in range( len( tableData ) ):
#the end=' ' argument allows us to print more than one word side-by-side rather than forcing a newline
print( tableData[eachList][eachWord].rjust( colWidths[eachList]), end=' ' )
#but at the end of each line, we'll need to add a newline
print()
# this is the getMaxSizeofList function, it was created to help us calculate the maximum size of the words on a given list
# parameter: theList is a single list containing words
# this function will determine the size of the largest word on the given list, it is designed to be called repeatedly with different lists
def getMaxSizeofList( theList ):
#this is a local variable called max, that will hold the maximum length of the word as we look through each word on the list. It is initialized to zero and will be replaced below as we determine the size of each word
max = 0
#this for-loop cycles through each word on the list
for word in range(len(theList)):
#if the length of the word we are examining is greater than max (initially, max is 0, but the value of max will change as this loop gets executed
if len(theList[word]) > max:
#the max value will be replaced with the length of this word, if the length of this word is greater than max
max = len(theList[word]);
#return the final max value to the caller of this function
return max | true |
72218d09cd2c9a05bae3d9a2f22eccba436a554d | jnoriega3/lesson-code | /ch4/1-list-print.py | 638 | 4.46875 | 4 | #this defines a function with one parameter, 'theList'
def printList( theList ):
# this for loop iterates through each item in the list, except the last item
for i in range( len(theList)-1 ): #can you remember what this line does?
#this will add a comma after each list item
print( str(theList[i]) + ',', end=' ')
#the last list item doesn't need to be followed by a comma
print( 'and ' + str(theList[ len(theList)-1 ]) )
#this is the end of what was asked in the question, the following lines are just to test the function we wrote
spam = ['apples', 'bananas', 'tofu', 'cats']
printList( spam ) | true |
db8cc0d6b26b66a57b5db9b2478bedb0b463e5a6 | burakdemir1/BUS232-Spring-2021-Homeworks | /hw7.py | 407 | 4.21875 | 4 | names = ("Ross","Rachel","Chandler","Monica","Joey","Phoebe")
friends_list = set()
for name in names:
names_ = input(f'{name}, enter the names of the friends you invited: ')
name_list = names_.split()
for name in name_list:
friends_list.add(name)
print('This is final list of people invited:')
for count, name in enumerate(friends_list, start=1):
print(count, '.', name) | true |
e0c8f24b3fd76f748f8aff3e31c04ec314ab6bba | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/IntroToObjects_List.py | 741 | 4.53125 | 5 | #Lists - An unordered sequence of items
groceryList = ['Greens', 'Fruits', 'Milk']
print("My Grocery list is ", groceryList)
#You can iterate over lists. What's Iterate?
#Iterate means go one by one element traverssing the full list
#We may need to iterate the list to take some action on the given item
#e.g. what is we want to check if the list has 'Carrots'. If not add it.
carrotFound = False
for item in groceryList:
if(item=='Carrots'):
carrotFound = True
break
if(carrotFound == False):
groceryList.append('Carrots')
print('Revised grocery list',groceryList)
#Other operations on a list
groceryList.reverse()
print("remove a item ",groceryList)
groceryList.sort()
print("sort a item ",groceryList)
| true |
19a636342dcb726c0a3c1ac89dab78319e4ca0c7 | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/Files_Reading.py | 1,152 | 4.28125 | 4 | #Opening a file using the required permissions
f = open("data/drSeuss_green_eggs_n_ham.txt","r")
#Reading a file using readline() function
print("== Using for loop to read and print a file line by line ==")
#Default print parameters
for line in f:
print(line)
#Extra new lines after the every line. Why?
#Specify print parameters for exactly printing as in file
#How to fix that - dont need an extra new line after every line
#Specify the end of line for print function. By default its the "newline".
for line in f:
print(line,end='')
f.close()
#Reading a file using readline() function
print("== Read a file using readline() ==")
f = open("data/drSeuss_green_eggs_n_ham.txt","r")
line = f.readline()
print(line)
while(line!=""):
line = f.readline()
print(line,end='')
f.close()
#Reading a file with read() function
print("\n === START Read a file using read() ==")
f = open("data/drSeuss_green_eggs_n_ham.txt","r")
txt = f.read(10)
print(txt)
f.close()
print("=== END Read a file using read() ==\n")
#Detour ;-)
#How to get help within from the programming topics.
#pydocs and help utility in python shell. Demo!
| true |
01dc63ff29161279ab8cb689d375895180efc241 | skoolofcode/SKoolOfCode | /The Geeks/modules/IntroToModule.py | 780 | 4.15625 | 4 |
#introduction to Modules
#Let's create a module hello that has 2 function helloWorld() and helloRedmond()
#Diffirent ways of importing the module
#1. Import module as is with its name. Note the usage <module>.<function>
import hello
hello.helloIssaquah()
hello.helloRedmond()
hello.helloSeattle()
hello.helloBangalore()
#2. Import module and give it name. Usage <module given name>.<function>
import hello as myHello
myHello.helloIssaquah()
myHello.helloRedmond()
myHello.helloSeattle()
myHello.helloBangalore()
#3. Import specific items in a module. Usage <function_name>()
from hello import helloSeattle
helloSeattle()
#4. Import specific items in a module and give it a name. Usage <module_given_name>()
from hello import helloRedmond as angadsHello
angadsHello()
| true |
fac14e0cfee5d22b65ca14fce29909c03c5a4f83 | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/Class_3_2_Live.py | 820 | 4.15625 | 4 | #Print a decimal number as binary
#"{0:b}".format(number)
j = 45
print("The number j in decimal is ",j)
print("{0:b}".format(j))
#Use ord() to get Ascii codes for a given character
storeACharacter = 'a'
print("I am printing a character ", storeACharacter)
print("The ASCII code for a is ", ord(storeACharacter))
#Lets convert a whole sentence to ascii
tmp = "This is a live coding demo"
for m in tmp:
print("Ascii for character ", m , "is ", ord(m))
# Let's write a secret message ;-)
# Part - 1 - Let's just write Ascii
letter = "This is a secret This is a secret This is a secret This is a secret"
count = 0
for m in letter:
print("",10+ord(m),end='')
# Part 2 - Ascii may be too simple and easily infered
# So we will jumble up
# Part 3 - More complex code. Note you have to also decode
| true |
83e14b2a1a0b7d360c9ef3b979b5ac1c6fff630f | skoolofcode/SKoolOfCode | /CodeNinjas/SimplifiedHangMan.py | 1,441 | 4.46875 | 4 | #Simplified Hangman
#Present a word with only first 3 characters. Rest everything is masked
#The user would be asked to guess the word. He/She wins if the word is correctly guessed.
#A user get a total of 3 tires. At every try a new character is shown.
#Let's have a global word list.
worldList = ["batman","jumpsuit", "tennis","horses","skoolofcode"]
def initWordList():
lenghtOfWords = 6 #
print("initiWordList : this function initializes the word list")
# Write the code to initialize the world list
#...
#print("initWordList : The world list is ",worldList)
print("initWordList : The world list is initialized with word of lenght", lenghtOfWords)
def selectWord():
word = "dummyy"
print("selectWord : Selects a word to play with")
# ...
# ...
return word
def creexateWordToDisplay(word,firstN):
wordFirstN = "dum***"
print("This function writes out the given word with N characters hideen with *")
#..
#..
#..
return wordFirstN
def about():
print("about: This function tells the users what the program does")
print("Hey user! Welcome to the Hangman. You are now playing a word guessing game")
print("Guess the word in 3 tries!")
#Main
initWordList()
about()
sWord = selectWord()
print("The selected word for this game is ", sWord)
displayWord = createWordToDisplay(sWord,3)
print("User : Guess the word ", displayWord)
| true |
dbf8ea3834665ffc7df5953b5974455849501e16 | skoolofcode/SKoolOfCode | /The Geeks/list_methods.py | 1,042 | 4.59375 | 5 | # This file we'll be talking about Lists.
#Create a list
print("\n *** printing the list ***")
groceryList = ['Milk', 'Oranges', "Cookies", "Bread"]
print(groceryList)
#Append to the list. This also means add a item to the list
print("\n*** Add pumpkin to the list")
groceryList.append("pumpkin")
print(groceryList)
#Lenght of the list.
print("\n*** Lenght of the list after adding pumpkin")
print(len(groceryList))
#Remove an item from the list
print("\n*** let's remove pumpkin from the list")
groceryList.remove("pumpkin")
print(groceryList)
#Find the position of a given element
print("\n*** Let's find the position of Oranges in the list")
print(groceryList.index("Oranges"))
#Lets access Orange using its position
print("\n*** Lets access Orange using its position")
element = groceryList[1]
print(element)
#Let's use index to find the position of Oranges and then print it
i = groceryList.index('Oranges')
element = groceryList[i]
print("\n*** Let's use index to find the position of Oranges and then print it")
print(element)
| true |
ac998b57fae60f1088db024c902ec8a9994b00d3 | skoolofcode/SKoolOfCode | /TrailBlazers/maanya/practice/caniguessyourage.py | 1,024 | 4.125 | 4 | def thecoolmathgame ():
print("Hello. I am going to guess your age today! I promise I will not cheat :)")
startnum = int(input("Pick a number from 1-10:"))
print("Now I will multiply your chosen number by 2.")
age = startnum * 2
print ("Now I will add 5 to the new number.")
age = age + 5
print("Now I will multiply this total by 50")
age = age * 50
bday = (input("Have you already had your birthday this year? Enter '1 for YES' and '2 for NO':"))
if bday == '1':
age = age + 1768
elif bday == '2':
age = age + 1767
else:
print("Your input is not valid. Go ahead and try again!")
print(bday)
byear = int(input("Enter the year you were born:"))
age = age - byear
print("Okay. Your age is ready. Keep in mind through out this game you have NOT told me your age.")
print(" ")
print("Your number is a three-digit result. The first number (left to right) is the number you choose in the beginning . The second and third numbers (left to right) are your age. ")
print(age)
return
thecoolmathgame()
| true |
315e47a3d80ac5835bb40dcc890b7bc924c08c1e | martyav/algoReview | /pythonSolutions/most_frequent_character.py | 878 | 4.1875 | 4 | # Frequency tables, frequency hashes, frequency dictionaries...
#
# Tomayto, tomahto, we're tracking a character alongside how many times it appears in a string.
#
# One small optimization is to update the most-frequently-seen character at the same time as
# we update the dictionary.
#
# Otherwise, we'd have to write a little more code to loop through the dictionary, to see where
# the most frequent character is.
def most_frequent_character(string):
if len(string) == 0:
return None
if len(string) == 1:
return 1
frequency_dict = {}
most_frequent_so_far = ("", 0)
for char in string:
if char in frequency_dict:
frequency_dict[char] += 1
else:
frequency_dict[char] = 1
if frequency_dict[char] > most_frequent_so_far[1]:
most_frequent_so_far = (char, frequency_dict[char])
return most_frequent_so_far[0]
| true |
07482b5f7f8b1ba25dbedc9a1f4398bb66ebd04a | SamuelNgundi/programming-challenges-with-python | /3.11. Book Club Points.py | 1,264 | 4.21875 | 4 | """
11. Book Club Points
Serendipity Booksellers has a book club that awards points to its customers
based on the number of books purchased each month.
The points are awarded as follows:
- If a customer purchases 0 books, he or she earns 0 points
- If a customer purchases 2 books, he or she earns 5 points
- If a customer purchases 4 books, he or she earns 15 points
- If a customer purchases 6 books, he or she earns 30 points
- If a customer purchases 8 or more books, he or she earns 60 points
Write a program that asks the user to enter the number of books that he
or she has purchased this month and displays the number of points awarded.
Reference:
(1) Starting out with Python, Third Edition, Tony Gaddis Chapter 3
(2) https://youtu.be/1n8T4JOd9s4
"""
# Get the User Input and Convert to int
number_of_books = int(input("Please Enter number of books Purchased " + \
"this month : "))
# now let check all the condition and print the result
if number_of_books < 2:
print("You have earn 0 Point")
elif number_of_books < 4:
print("You have earn 5 Points")
elif number_of_books < 6:
print("You have earn 15 Points")
elif number_of_books < 8:
print("You have earn 30 Points")
else:
print("You have earn 60 Points")
| true |
bb5d1cdeede1ec0a878ad5ee0f023e331f75d2dd | SamuelNgundi/programming-challenges-with-python | /3.2. Areas of Rectangles.py | 1,179 | 4.46875 | 4 | """
2. Areas of Rectangles
The area of a rectangle is the rectangles length times its width.
Write a program that asks for the length and width of two rectangles.
The program should tell the user which rectangle has the greater area,
or if the areas are the same.
Reference:
(1) Starting out with Python, Third Edition, Tony Gaddis Chapter 3
(2) https://youtu.be/7be9HlHRB-E
"""
# Get User Input(the length and width of two rectangles.)
# Convert User input to float
rectangle1_length = float(input("Please Enter the length of Rectangle 1 : "))
rectangle1_width = float(input("Please Enter the Width of Rectangle 1 : "))
rectangle2_length = float(input("Please Enter the length of Rectangle 2 : "))
rectangle2_width = float(input("Please Enter the Width of Rectangle 2 : "))
# Compute Area of Rectangle for both
rectangle1_area = rectangle1_length * rectangle1_width
rectangle2_area = rectangle2_length * rectangle2_width
# check all the conditions
if rectangle1_area > rectangle2_area:
print("Rectangle 1 is Bigger than Rectangle 2")
elif rectangle2_area > rectangle1_area:
print("Rectangle 2 is Bigger than Rectangle 1")
else:
print("the areas are the same")
| true |
afe32f4de9c73b431f8e20694a975a45ae993b34 | SamuelNgundi/programming-challenges-with-python | /3.1. Day of the Week.py | 1,136 | 4.46875 | 4 | """
1. Day of the Week
Write a program that asks the user for a number in the range of 1 through 7.
The program should display the corresponding day of the week, where 1 = Monday,
2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday,
and 7 = Sunday.
The program should display an error message if the user enters a number
that is outside the range of 1 through 7.
Reference:
(1) Starting out with Python, Third Edition, Tony Gaddis Chapter 3
(2) https://youtu.be/jx8y647CMsI
"""
# Get User Input(a number in the range of 1 through 7)
# Convert User input to int
user_number = int(input("Enter a number in the range of 1 through 7 : "))
# check all the conditions
if user_number == 1:
print("Monday")
elif user_number == 2:
print("Tuesday")
elif user_number == 3:
print("Wednesday")
elif user_number == 2:
print("Tuesday")
elif user_number == 4:
print("Thursday")
elif user_number == 5:
print("Friday")
elif user_number == 6:
print("Saturday")
elif user_number == 7:
print("Sunday")
# for all the else cases
else:
print("Error a number is outside the range of 1 through 7")
| true |
7e1205f5489688438da50bb992c737eaaf9504fa | rickydhanota/Powerset_py | /powerset_med.py | 1,006 | 4.15625 | 4 | #Powerset
#Write a function that takes in an array of unique integers and returns its powerset.
#The powerset P(X) of a set X is the set of all the subsets of X. for example, the powerset of [1, 2] is [[], [1], [2], [1, 2]]
#Note that the power sets do not need to be in any particular order
#Array = [1, 2, 3]
#[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
#O(n*2^n) time | O(n*2^n) space
# def powerset(array, idx = None):
# if idx is None:
# idx = len(array) - 1
# if idx < 0:
# return [[]]
# ele = array[idx]
# subsets = powerset(array, idx - 1)
# for i in range(len(subsets)):
# currentSubset = subsets[i]
# subsets.append(currentSubset + [ele])
# return subsets
#O(n*2^n) time | O(n*2^n) space
def powerset(array):
subsets = [[]]
for ele in array:
for i in range(len(subsets)):
currentSubset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets
print(powerset([1, 2, 3]))
| true |
9b010ff1877e1ef42db1fe2f8d630dff72b2c544 | JakobHavtorn/algorithms-and-data-structures | /data_structures/stack.py | 1,975 | 4.1875 | 4 | class Stack(object):
def __init__(self, max_size):
"""Initializes a Stack with a specified maximum size.
A Stack incorporates the LIFO (Last In First Out) principle.
Args:
max_size (int): The maximum size of the Stack.
"""
assert type(max_size) is int and max_size >= 0, '`max_size` must be 0 or large but was {}'.format(max_size)
self._max_size = max_size
self._top = -1
self._stack = [None] * self._max_size
def is_full(self):
"""Checks if the stack is full.
Returns:
bool: Whether or not the stack is full.
"""
return self._top == self._max_size - 1
def is_empty(self):
"""Checks if the stack is empty.
Returns:
bool: Whether or not the stack is empty.
"""
return self._top == -1
def peek(self):
"""Returns the top element of the stack without removing it.
Returns:
[type]: The top element
"""
return self._stack[self._top]
def push(self, data):
"""Pushes an element to the top of the stack.
Args:
data (type): The data to push.
Raises:
IndexError: If the stack is full.
"""
if not self.is_full():
self._top += 1
self._stack[self._top] = data
else:
msg = 'Stack overflow at index {} with max size of {}'.format(self._top + 1, self._max_size)
raise IndexError(msg)
def pop(self):
"""Returns the top element of the stack, removing it from the stack.
Raises:
IndexError: If the stack is empty.
Returns:
[type]: The top element of the stack.
"""
if not self.is_empty():
data = self._stack[self._top]
self._top -= 1
return data
else:
msg = 'Stack is empty'
raise IndexError(msg)
| true |
0cac7a90f5b2e66b12400a09cb98a0028eda2883 | Utkarsh016/fsdk2019 | /day4/code/latline.py | 426 | 4.15625 | 4 | """
Code Challenge
Name:
Last Line
Filename:
lastline.py
Problem Statement:
Ask the user for the name of a text file.
Display the final line of that file.
Think of ways in which you can solve this problem,
and how it might relate to your daily work with Python.
"""
file_name=input("enter the name of text file")
with open(file_name,"r") as fp:
a=fp.readlines()
b=a[-1]
print(b) | true |
8662bda8ca8c11a857c90048e588861d7eb475c7 | rshandilya/IoT | /Codes/prac2d.py | 1,523 | 4.3125 | 4 | ############# EXPERIMENT 2.D ###################
# Area of a given shape(rectangle, triangle, and circle) reading shape and
# appropriate values from standard input.
import math
import argparse
import sys
def rectangle(x,y):
"""
calculate area and perimeter
input: length, width
output: dict - area, perimeter
"""
perimeter = 2*(x+y)
area = x*y
return {"area": area, "perimeter": perimeter}
def triangle(a, b, c):
p = a + b + c
s = p/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
return {"area": area, "perimeter": p}
def circle(r):
perimeter = 2*math.pi*r
area = math.pi*r*r
return {"area": area, "perimeter": perimeter}
if __name__ == "__main__":
choices = ["tri", "circ", "rect"]
parser = argparse.ArgumentParser(
description="Calculate Area of Basic geometry")
parser.add_argument("geom", choices=choices, help="Geometry type")
parser.add_argument('para', type=float, nargs='*',
help="parameters for geometry")
args = parser.parse_args()
if args.geom=="tri":
ret = triangle(args.para[0], args.para[1], args.para[2])
print(f"Perimeter: {ret['perimeter']}")
print(f"Area: {ret['area']}")
elif args.geom=="rect":
ret = rectangle(args.para[0], args.para[1])
print(f"Perimeter: {ret['perimeter']}")
print(f"Area: {ret['area']}")
else:
ret = circle(args.para[0])
print(f"Perimeter: {ret['perimeter']}")
print(f"Area: {ret['area']}")
| true |
3d120963e6082fc867cb0b2266e0f4aa63ff458e | wensheng/tools | /r2c/r2c.py | 1,795 | 4.25 | 4 | #!/bin/env python
"""
Author: Wensheng Wang (http://wensheng.com/)
license: WTFPL
This program change change rows to columns in a ASCII text file.
for example:
-----------
hello
world
!
-----------
will be converted to:
-----------
h w!
e o
l r
l l
o d
-----------
If you specify '-b', vertical bars will be added to non-empty line to fill up spaces,
empty lines will still become empty columns, for example:
-----------
goodbye
world
-------------
will be converted to:
-----------
g w
o o
o r
d l
b d
y |
e |
-----------
By default, output will be printed to screen, use > to redirect output to a file.
If "-o filename" is specified, the output will be saved to the specified file.
"""
import sys
import os
from optparse import OptionParser
usage = "Usage: %prog [options] name"
parser = OptionParser(usage=usage)
parser.set_defaults(columns="",rows="1",delay_type=None)
parser.add_option("-b", "--bars", dest="bars", action="store_true", help="add bars")
parser.add_option("-o", "--output", dest="ofile", help="output file name")
(coptions,cargs) = parser.parse_args()
if len(cargs) == 0:
print("ERROR: Must supply file name.")
sys.exit()
fname = cargs[0]
if coptions.ofile:
ofile = open(coptions.ofile,'w')
else:
ofile = sys.stdout
# lines = [a[:-1] for a in file(fname).readlines()]
f = open(fname)
lines = [a[:-1] for a in f.readlines()]
f.close()
maxlen = max([len(line) for line in lines])
if coptions.bars:
for i in range(len(lines)):
if not lines[i]:
lines[i]=" "*maxlen
else:
lines[i]="%s%s"%(lines[i],'|'*(maxlen-len(lines[i])))
else:
lines = ["%s%s"%(line,' '*(maxlen-len(line))) for line in lines]
for i in range(maxlen):
for j in lines:
ofile.write(j[i])
ofile.write('\n')
ofile.close()
| true |
0b44b64de6e6b1c1e58b40b4d793d4e5bb14cbc2 | zertrin/zkpytb | /zkpytb/priorityqueue.py | 2,082 | 4.25 | 4 | """
An implementation of a priority queue based on heapq and
https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes
Author: Marc Gallet
Date: 2018-01
"""
import heapq
import itertools
class EmptyQueueError(Exception):
pass
class PriorityQueue:
"""Based on https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes"""
def __init__(self, name=''):
self.name = name
self.pq = [] # list of entries arranged in a heap
self.entry_finder = {} # mapping of tasks to entries
self.counter = itertools.count() # unique sequence count
self.num_tasks = 0 # track the number of tasks in the queue
def __len__(self):
return self.num_tasks
def __iter__(self):
return self
def __next__(self):
try:
return self.pop_task()
except EmptyQueueError:
raise StopIteration
@property
def empty(self):
return self.num_tasks == 0
def add_task(self, task, priority=0):
'Add a new task or update the priority of an existing task'
if task in self.entry_finder:
self.remove_task(task)
count = next(self.counter)
removed = False
entry = [priority, count, task, removed]
self.entry_finder[task] = entry
heapq.heappush(self.pq, entry)
self.num_tasks += 1
def remove_task(self, task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = self.entry_finder.pop(task)
entry[-1] = True # mark the element as removed
self.num_tasks -= 1
def pop_task(self):
'Remove and return the lowest priority task. Raise KeyError if empty.'
while self.pq:
priority, count, task, removed = heapq.heappop(self.pq)
if not removed:
del self.entry_finder[task]
self.num_tasks -= 1
return task
raise EmptyQueueError('pop from an empty priority queue')
| true |
ccb58c3b3faee4d0b2a14e600c2881a3d5ecb362 | atravanam-git/Python | /DataStructures/tuplesCodeDemo_1.py | 1,133 | 4.6875 | 5 | """tuples have the same properties like list:
#==========================================================================
# 1. They allow duplicate values
# 2. They allow heterogeneous values
# 3. They preserve insertion order
# 4. But they are IMMUTABLE
# 5. tuple objects can be used as keys in Dictionaries
#==========================================================================
"""
# Declaring empty tuples
tupleA = ()
tupleB = tuple()
# initializing the values using tuple()
tupleA = tuple(range(1, 10, 2))
tupleB = tuple(range(2, 8))
# printing complete tuple data set
print("tupleA values: ", tupleA)
print("tupleB values: ", tupleB)
# tuple' object does not support item assignment
"""tupleA[0] = 'AddnewValue'
tupleB[1] = 2"""
# Mathematical Operator * and + for tuple
tupleA = tupleA + tupleB
tupleB = 3 * tupleB
print("Concatenation Operator - tupleA + tupleB: ", tupleA)
print("Repetition Operator - tupleB * 3: ", tupleB)
# Sorting a tuple
tupleA = sorted(tupleA, key=None, reverse=False)
print("Sorted tupleA: ", tupleA)
tupleA = sorted(tupleA, key=None, reverse=True)
print("Reverse Sorted tupleA: ", tupleA) | true |
0160126d1a2e614c95b844adb1524a6982f50493 | atravanam-git/Python | /FunctionsDemo/globalvarDemo.py | 902 | 4.53125 | 5 | """
#==========================================================================
# 1. global vs local variables in functions
# 2. returning multiple values
# 3. positional args vs keyword args
# 4. var-args, variable length arguments
# 5. kwargs - keyword arguments
#==========================================================================
"""
# any variable defined outside the function is global
a = 10
print("Demo on global vs. Local variables")
# this function has local variable hence local values is taken
def f1():
a = 20
print("Prints local variable ", a)
# this function has No local variable hence global values is taken
def f2():
print("Prints global variable ", a)
# this function has global keyword explicitly mentioned and its value modified
def f3():
global a
a = 100
print("prints modified global value ", a)
# calling functions
f1()
f2()
f3()
f2() | true |
964c6e0588f5e3ca4aabb1cd861357f6d935a595 | cuongdv1/Practice-Python | /Python3/database/create_roster_db.py | 2,652 | 4.125 | 4 | """
Create a SQLite database using the data available in json stored locally.
json file contains the users, courses and the roles of the users.
"""
# Import required modules
import json # to parse json
import sqlite3 # to create sqlite db
import sys # to get coomand line arguments
# Get command line arguments
def print_cmd_line_args():
print(sys.argv)
# print_cmd_line_args()
# Get File name
json_fname = sys.argv[1]
# Open & read json data as string
try:
with open(json_fname, "r") as json_fhand:
json_str = json_fhand.read()
except:
print("[ERROR]", json_fname, ": No such file or directory.")
# print("[DEBUG] JSON Data string :\n---------------------------")
# print(json_str)
# Parse json data
json_data_list = json.loads(json_str)
print(len(json_data_list))
# Create/open database
roster_db = sqlite3.connect("roster.sqlite")
# Get command cursor
curr = roster_db.cursor()
# Drop/Wipe-out existing tables, if exist
curr.executescript(
"""
DROP TABLE IF EXISTS Users;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXISTS Member;
"""
)
# Create new tables
curr.executescript(
"""
CREATE TABLE Users (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
"""
)
# Fill database with data
for item in json_data_list:
user_name = item[0]
course_title = item[1]
user_role = int(item[2])
# print("[DEBUG]", "{:<15}{:<10}{:}".format(user_name, course_title, user_role))
# Insert user
curr.execute("insert or ignore into Users (name) values (?)", (user_name,))
# Get user ID
curr.execute("select id from Users where name = ?", (user_name,))
user_id = curr.fetchone()[0]
# Insert course
curr.execute("insert or ignore into Course (title) values (?)", (course_title,))
# Get course ID
curr.execute("select id from Course where title = ?", (course_title,))
course_id = curr.fetchone()[0]
# Insert role, user_id & course_id in Member table
curr.execute("insert or replace into Member (user_id, course_id, role) values (?, ?, ?)", (user_id, course_id, user_role))
# Done : End of for loop
# Commit/Save database to Filesystem
roster_db.commit()
# Close cursor
curr.close()
| true |
b0436a9cd1ab679ac92b3fa3bd75786a3cb52067 | spectrum556/playground | /src/homework_1_additional/h_add.7.py | 566 | 4.25 | 4 | __author__ = 'Ihor'
month_num = int(input('enter the number of month\n'))
def what_season(month_num):
if month_num == 1 or month_num == 2 or month_num == 12:
return 'Winter'
elif month_num == 3 or month_num == 4 or month_num == 5:
return 'Spring'
elif month_num == 6 or month_num == 7 or month_num == 8:
return 'Summer'
elif month_num == 9 or month_num == 10 or month_num == 11:
return 'Autumn'
else:
return 'Error. The number of month must be in the range from 1 to 12'
print (what_season(month_num)) | true |
c1e0a3c70cfd90f4753bc9b46c101c2e7ad1227d | wardk6907/CTI110 | /P5T2_FeetToInches_KaylaWard.py | 520 | 4.3125 | 4 | # Feet to Inches
# 1 Oct 2018
# CTI-110 P5T2_FeetToInches
# Kayla Ward
#
# Constant for the number of inches per foot.
inches_per_foot = 12
# Main Function
def main():
# Get a number of feet from the user.
feet = int(input("Enter a number of feet: "))
# Convert that to inches.
print(feet, "equals", feet_to_inches(feet), "inches.")
# The feet_to_inches function convets feet to inches.
def feet_to_inches(feet):
return feet * inches_per_foot
# Call the min function.
main()
| true |
55accbf96df3236d8b55ada121259a0cf95daf99 | PraveenMut/quick-sort | /quick-sort.py | 783 | 4.15625 | 4 | # QuickSort in Python using O(n) space
# tester array
arr = [7,6,5,4,3,2,1,0]
# partition (pivot) procedure
def partition(arr, start, end):
pivot = arr[end]
partitionIndex = start
i = start
while i < end:
if arr[i] <= pivot:
arr[i],arr[partitionIndex] = arr[partitionIndex],arr[i]
partitionIndex += 1
i += 1
else:
i += 1
arr[end],arr[partitionIndex] = arr[partitionIndex],arr[end]
return partitionIndex
# parent Quicksort algorithm
def quickSort(arr, start, end):
if (start < end):
partitionIndex = partition(arr, start, end)
quickSort(arr, start, partitionIndex-1)
quickSort(arr, partitionIndex+1, end)
## testers
n = len(arr)
quickSort(arr, 0, n-1)
for i in range(n): # print the elements in a new line
print arr[i] | true |
ed4bf2d14601305473a0e708b7933c28c679aed5 | bscott110/mthree_Pythonpractice | /BlakeScott_Mod2_TextCount.py | 1,366 | 4.3125 | 4 | import string
from string import punctuation
s = """Imagine a vast sheet of paper on which straight Lines, Triangles, Squares, Pentagons, Hexagons, and other figures,
instead of remaining fixed in their places, move freely about, on or in the surface,
but without the power of rising above or sinking below it, very much like shadows - only hard and with luminous edges -
and you will then have a pretty correct notion of my country and countrymen. Alas, a few years ago, I should have said "my universe":
but now my mind has been opened to higher views of things."""
print("original str: " + s)
s_lower = s.lower()
print("str in all lowercase:")
print(s_lower)
words = list()
words = s_lower.split()
print("str in a list:")
print(words)
print("str word count:")
count = len(words)
print(count)
uni_count = len(set(words))
print("str distinct word count:")
print(uni_count)
j = []
for i in words:
word_count = words.count(i)
j.append((i, word_count))
freq_occur = dict(j)
print("str word freq dict:")
print(freq_occur)
#punctuation_list = list(string.punctuation)
#print(punctuation_list)
w_clean = list()
new=[i.strip(punctuation) for i in s_lower.split()]
w_clean = " ".join(new).split()
print("str list w no punct:")
print(w_clean)
print("str w no punct word count:")
print(len(w_clean))
| true |
b54d309379486f336fcd189b81a9a1df5fba77d0 | AnirbanMukherjeeXD/Explore-ML-Materials | /numpy_exercise.py | 2,818 | 4.28125 | 4 | # Student version : https://tinyurl.com/numpylevel1-280919
# Use the numpy library
import numpy as np
def prepare_inputs(inputs):
# TODO: create a 2-dimensional ndarray from the given 1-dimensional list;
# assign it to input_array
n = len(inputs)
input_array = np.array(inputs).reshape(1,n)
# TODO: find the minimum value in input_array and subtract that
# value from all the elements of input_array. Store the
# result in inputs_minus_min
inputs_minus_min = input_array - np.amin(input_array)
# TODO: find the maximum value in inputs_minus_min and divide
# all of the values in inputs_minus_min by the maximum value.
# Store the results in inputs_div_max.
inputs_div_max = inputs_minus_min / np.amax(inputs_minus_min)
# return the three arrays we've created
return input_array, inputs_minus_min, inputs_div_max
def multiply_inputs(m1, m2):
# TODO: Check the shapes of the matrices m1 and m2.
# m1 and m2 will be ndarray objects.
#
# Return False if the shapes cannot be used for matrix
# multiplication. You may not use a transpose
# TODO: If you have not returned False, then calculate the matrix product
# of m1 and m2 and return it. Do not use a transpose,
# but you swap their order if necessary
if m1.shape[1] == m2.shape[0]:
return np.matmul(m1, m2)
elif m2.shape[1] == m1.shape[0]:
return np.matmul(m2, m1)
else:
return False
def find_mean(values):
# TODO: Return the average of the values in the given Python list
return np.mean(values)
input_array, inputs_minus_min, inputs_div_max = prepare_inputs([-1,2,7])
print("Input as Array: {}".format(input_array))
print("Input minus min: {}".format(inputs_minus_min))
print("Input Array: {}".format(inputs_div_max))
m1 = multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1],[2],[3],[4]]))
m2 = multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1],[2],[3]]))
m3 = multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1,2]]))
print("Multiply 1:\n{}".format(m1))
print("Multiply 2:\n{}".format(m2))
print("Multiply 3:\n{}".format(m3))
print("Mean == {}".format(find_mean([1,3,4])))
def test_module():
score = 0
if np.array_equal(input_array,np.array([[-1,2,7]])):
score += 10
if np.array_equal(inputs_minus_min, np.array([[0,3,8]])):
score += 15
if np.array_equal(inputs_div_max, np.array([[0.,0.375, 1.]])):
score += 15
if not m1:
score += 15
if np.array_equal(m2, np.array([[14],[32]])):
score += 15
if np.array_equal(m3, np.array([[9,12,15]])):
score += 15
if round(find_mean([1,3,4])) == 3:
score += 15
print("--------------------------\nYour Total Score: ", score)
test_module()
| true |
f7754142cebe7e721ca0cd13187d4025a625cdba | cbira353/buildit-arch | /_site/writer1.py | 445 | 4.15625 | 4 | import csv
from student import Student
students = []
for i in range(3):
print('name:', end='')
name = input()
print('dorm:', end='')
dorm = input()
students.append(Student(name, dorm))
for student in students:
print("{} is in {}.".format(student.name, student.dorm))
file =open("students.csv", "w")
writer = csv.writer(file)
for student in students:
writer.writerow((student.name, student.dorm))
file.close()
| true |
94908555a5067b29f51bc69eb397cb1f3aace887 | onizenso/College | /classes/cs350/wang/Code/Python/coroutines.py | 1,990 | 4.5 | 4 | #!/usr/bin/env python
# demonstrate coroutines in Python
# coroutines require python 2.5
"""
this simple example is a scheduler for walking dogs
the scheduler subroutine and main() act as coroutines
yield hands off control, next() and send() resumes control
"""
def printdog(name): # auxilliary print function
print "It's %s's turn to go for a walk." % name
"""
this is the scheduler coroutine
'yield stuff' passes control back to main with a message in variable stuff
when control resumes, a message (it may be empty) is available from the caller
as the return value from yield
"""
def scheduler(dogs):
doglist = list(dogs) # create a list object of dogs
current = 0
while len(doglist):
# yield passes control back to caller with a dog name
getRequest = yield doglist[current] # on resume, get a request
current = (current + 1) % len(doglist) # circular traversal of the list
if getRequest:
request, name = getRequest
if request == "add":
doglist.append(name)
elif request == "remove" and name in doglist:
doglist.remove(name)
"""
the code below acts as a coroutine with the scheduler
next resumes control in the schedule with no message passing
send resumes control in the schedule with a message as the parameter
"""
if __name__ == "__main__": # initialize once from main only
dogs = ["spot", "rusty", "bud", "fluffy", "lassie"]
s = scheduler(dogs) # start the scheduler s
for i in range(5):
printdog(s.next()) # next resumes control in s w/ no msg
printdog(s.send(("add", "fifi"))) # send resumes control and passes msg
for i in range(6):
printdog(s.next()) # resume control in s
printdog(s.send(("remove","fluffy"))) # send remove request to s
for i in range(6):
printdog(s.next())
| true |
2696488fbf8a0c27b5c410bdca8fab666eeaa213 | BeniyamL/alx-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py | 1,166 | 4.34375 | 4 | #!/usr/bin/python3
"""
class definition of Rectangle
"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
"""
class implementation for rectangle
"""
def __init__(self, width, height):
"""initialization of rectangle class
Arguments:
width: the width of the rectangle
height: the height of the rectangle
Returns:
nothing
"""
self.integer_validator("width", width)
self.__width = width
self.integer_validator("height", height)
self.__height = height
def area(self):
""" function to find area of the rectanngle
Arguments:
nothing
Returns:
return the area of the rectangle
"""
return (self.__width * self.__height)
def __str__(self):
""" function to print the rectangle information
Arguments:
nothing
Returns:
the string representation of a rectangle
"""
rect_str = "[Rectangle] "
rect_str += str(self.__width) + "/" + str(self.__height)
return (rect_str)
| true |
37f0162910ed4541fbad07ba16b71d71b406449f | BeniyamL/alx-higher_level_programming | /0x03-python-data_structures/2-replace_in_list.py | 384 | 4.3125 | 4 | #!/usr/bin/python3
def replace_in_list(my_list, idx, element):
"""
replace_in_list - replace an element of a list
@my_list: the given list
@idx: the given index
@element: element to be replaced
@Return : the replaced element
"""
if idx < 0 or idx >= len(my_list):
return my_list
else:
my_list[idx] = element
return my_list
| true |
a7ce1f8eca0bed05c35f6cbaa0671ec1febea9df | BeniyamL/alx-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 311 | 4.40625 | 4 | #!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
"""function to sort a dictionary
Arguments:
a_dictionary: the given dictionary
Returns:
nothing
"""
sorted_dict = sorted(a_dictionary.items())
for k, v in sorted_dict:
print("{0}: {1}".format(k, v))
| true |
0497d2f931697ad17a338967d629b2c430ece31b | BeniyamL/alx-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 660 | 4.28125 | 4 | #!/usr/bin/python3
""" function defintion for append_after
"""
def append_after(filename="", search_string="", new_string=""):
""" function to write a text after search string
Arguments:
filename: the name of the file
search_string: the text to be searched
new_string: the string to be appended
Returns:
nothing
"""
result_string = ""
with open(filename) as file:
for line in file:
result_string += line
if search_string in line:
result_string += new_string
with open(filename, mode="w", encoding="utf-8") as file:
file.write(result_string)
| true |
ee769eb6ad867b1e9b7cb2462c2b48ac2abaf5b8 | BeniyamL/alx-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 485 | 4.46875 | 4 | #!/usr/bin/python3
""" print_square function """
def print_square(size):
""" function to print a square of a given size
Arguments:
size: the size of the square
Returns:
nothing
"""
if type(size) is not int:
raise TypeError("size must be an integer")
if type(size) is int and size < 0:
raise ValueError("size must be >= 0")
for i in range(size):
for j in range(size):
print("#", end="")
print()
| true |
2d55b3451ad2d1d344cb614b0b8ab8eb085fb125 | JanhaviMhatre01/pythonprojects | /flipcoin.py | 618 | 4.375 | 4 | '''
/**********************************************************************************
* Purpose: Flip Coin and print percentage of Heads and Tails
* logic : take user input for how many times user want to flip coin and generate head or
* tail randomly and then calculate percentage for head and tail
*
* @author : Janhavi Mhatre
* @python version 3.7
* @platform : PyCharm
* @since 21-12-2018
*
***********************************************************************************/
'''
from utilities import utility
n = int(input("number of times to flip coin: ")) # number of times user want to flip coin
utility.flips(n)
| true |
8cb108ab7d77ee8f7d7e44b68b2d0b0fdd77849b | rodrigo-meyer/python_exercises | /odd_numbers_selection.py | 340 | 4.3125 | 4 | # A program that calculates the sum between all the odd numbers
# that are multiples of 3 and that are in the range of 1 to 500.
# Variables.
adding = 0
counter = 0
for c in range(1, 501, 2):
if c % 3 == 0:
counter = counter + 1
adding = adding + c
print('The total sum of {} values is {}'.format(counter, adding))
| true |
34c3bec34c7d4c18596381f3ac1c7164a183091f | gulnarap1/Python_Task | /Task3_allincluded.py | 2,822 | 4.1875 | 4 | #Question 1
# Create a list of the 10 elements of four different types of Data Types like int, string,
#complex, and float.
c=[2, 6, 2+4j, 3.67, "Dear Client", 9, 7.9, "Hey!", 4-3j, 10]
print(c)
#Question 2
#Create a list of size 5 and execute the slicing structure
my_list=[10, 20, ["It is me!"], 40, 50]
#Slicing
S1=my_list[:3]
print(S1)
S2=my_list[1:]
print(S2)
S3=my_list[::2]
print(S3)
S4=my_list[2][0]
print(S4)
S5=my_list[2][0][1]
print(S5)
#Question 3
list = list(range(1,21)) # use argument-unpacking operator i.e. *
sum_items = 0
multiplication = 1
for i in list:
sum_items = sum_items + i
multiplication = multiplication * i
print ("Sum of all items is: ", sum_items)
print ("Multiplication of all items is: ", multiplication)
# Question 4: Find the largest and smallest number from a given list.
x=[3,2,7,4,5,10,1,8,9]
print(max(x))
print(min(x))
#Question 5: Create a new list that contains the specified numbers after removing
# the even numbers from a predefined list.
my_list=list(range(1,91))
for i in my_list:
if i%2==0:
my_list.remove(i)
print(my_list)
# Question 6: Create a list of first and last 5 elements where the values
# are square of numbers between 1 and 30 (both included).
initial_list=range(1,31)
x=[]
for i in initial_list:
x=i**2
print(x)
#Slicing - I couldnt do the slicing part but tried beneath code which didnt work out
a= list(([x[:4], x[-4:]]))
print(a)
# Question 7: Write a program to replace the last element in a list with another list.
# Sample data: [[1,3,5,7,9,10],[2,4,6,8]]
# Expected output: [1,3,5,7,9,2,4,6,8]
sample_list=[[1,3,5,7,9,10],[2,4,6,8]]
begin= sample_list[0][:5]
end= sample_list[1][:]
a=sample_list[0][:]+sample_list[1][:]
print(a)
a.remove(10)
print(a)
#Question 8: Create a new dictionary by concatenating the following two dictionaries:
#a={1:10,2:20}
#b={3:30,4:40}
#Expected Result: {1:10,2:20,3:30,4:40}
a={1:10,2:20}
b={3:30,4:40}
concatenate={}
for i in (a,b): concatenate.update(i)
print(concatenate)
#Question 8: Create a dictionary that contains a number (between 1 and n) in the form(x,x*x).
#Expected Output: {1:1,2:4,3:9,4:16,5:25}
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
#Question 9: Create a dictionary that contains a number (between 1 and n) in the form(x,x*x).
#Expected Output: {1:1,2:4,3:9,4:16,5:25}
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
#Question 10: Write a program which accepts a sequence of comma-separated numbers from the console and generate
# a list and a tuple which contains every number. Suppose the following input is supplied to the program:
#34,67,55,33,12,98
ln = str(input())
li = ln.split(',')
tup = tuple(li)
li = list(li)
print(tup)
print(li)
| true |
46f0f7ed004db78260c547f99a3371bb64ce6b08 | MemeMasterJeff/CP1-programs | /9-8-payroll-21.py | 2,572 | 4.125 | 4 | #William Wang & Sophia Hayes
#9-8-21
#calculates payroll for each employee after a week
#defins the employee class
try:
class employee:
def __init__(self, name, pay):
self.name = name
self.pay = pay
#inputted/calculated values
self.rate = float(input(f'How many hours did {self.name} work?\n>'))
self.gross = self.pay * self.rate
self.social = 0.07 * self.gross
self.tax = 0.15 * self.gross
#calculates net pay
self.net = self.gross - (self.tax + self.social)
#defines objects
employee1 = employee("Everett Dombrowski", float(8.35))
employee2 = employee('Anagha Nittalia', float(15.50))
employee3 = employee('Luke Olsen', float(13.25))
employee4 = employee('Emily Lubek', float(13.50))
#defines lists
people = [employee1.name, employee2.name, employee3.name, employee4.name]
payRate = [employee1.pay, employee2.pay, employee3.pay, employee4.pay]
hours = [employee1.rate, employee2.rate, employee3.rate, employee4.rate]
grossPay = [employee1.gross, employee2.gross, employee3.gross, employee4.gross]
socialSecurity = [employee1.social, employee2.social, employee3.social, employee4.social]
federalTax = [employee1.tax, employee2.tax, employee3.tax, employee4.tax]
netPay = [employee1.net, employee2.net, employee3.net, employee4.net]
#used a for loop that iterates through multiple lists to print 4 different sets of information
for a, b, c, d, e, f, g in zip(people, payRate, hours, grossPay, socialSecurity, federalTax, netPay):
print("{:<15}{:>15}".format("Name:", a))
print("{:<12}{:>15}".format("Pay Rate:", b))
print("{:<12}{:>15}".format("Hours worked", c))
print("{:<12}{:>15}\n".format("Gross pay:", f'${d}'))
print("{:<20}".format("Deductions"))
print("{:<19}{:<18}".format("\t\tSocial Security:", f'${round(e, 2)}'))
print("{:<19}{:<18}\n".format("\t\tFederal Tax:", f'${round(f,2)}'))
print("{:<25}{:<18}".format("Net Pay:", f'${round(g,2)}'))
print("{:<40}\n".format("----------------------------------"))
print(f"Miller Co.\n440 W.Aurora Avenue\nNaperville, IL.60565\n\n")
print('{:<40}{:>20}'.format(f"Pay to the Order of: {a}", f'${round(f,2)}\n'))
print('{:>80}'.format("----------------------------------"))
print('{:>80}\n\n'.format('Mr. Miller, the Boss'))
input('press enter key to exit')
except:
print('program errored out, please check your inputs.') | true |
b7c53f9f71b18e7b850c9d6327507cd6590a43e3 | gomezquinteroD/GWC2019 | /Python/survey.py | 557 | 4.1875 | 4 | #create a dictionary
answers = {}
# Create a list of survey questions and a list of related keys that will be used when storing survey results.
survey = [
"What is your name?",
"How old are you?",
"What is your hometown?",
"What is your date of birth? (DD/MM/YYYY)"]
keys = ["name", "age", "hometown", "DOB"]
# Iterate over the list of survey questions and take in user responses.
i = 0 #index
for question in survey:
response = input(survey[i] +": ")
answers[keys[i]] = response
i += 1 #increase index by 1
print(answers)
| true |
4e808368dcb9f4e791aca828f31a17b47c6947dc | macrespo42/Bootcamp_42AI | /day00/ex03/count.py | 1,009 | 4.375 | 4 | import sys
import string
def text_analyzer(text=None):
"""
This functions count numbers of upper/lower letters, punctuation spaces
and letters in a string
"""
upper_letters = 0
lower_letters = 0
punctuation = 0
spaces = 0
text_len = 0
if (text == None):
print("What is the text ton analyze ?")
text = sys.stdin.readline()
spaces -= 1
text_len = len(text) - 1
else:
text_len = len(text)
for char in text:
if (char.isupper()):
upper_letters += 1
if (char.islower()):
lower_letters += 1
if char in (string.punctuation):
punctuation += 1
if char.isspace():
spaces += 1
print("The text contains {} characters:".format(text_len))
print("- {} upper letters".format(upper_letters))
print("- {} lower letters".format(lower_letters))
print("- {} punctuation marks".format(punctuation))
print("- {} spaces".format(spaces))
| true |
26d14c6b1786baf307400f126ca9c81f183d0aa3 | AndrewBatty/Selections | /Selection_development_exercise_2.py | 368 | 4.125 | 4 | # Andrew Batty
# Selection exercise:
# Development Exercise 2:
# 06/102014
temperature = int(input("Please enter the temperature of water in a container in degrees centigrade: "))
if temperature <= 0:
print("The water is frozen.")
elif temperature >=100:
print("The water is boiling.")
else:
print("The water is neither boiling or frozen.")
| true |
3b4608f02475a5cb37397511b3fa5bad4c4007e2 | earth25559/Swift-Dynamic-Test | /Number_3.py | 530 | 4.1875 | 4 | test_array = [-2, -3, 4, -6, 1, 2, 1, 10, 3, 5, 6, 4]
def get_index(max_val):
for index, value in enumerate(test_array):
if(value == max_val):
return index
def find_index_in_array(arr):
max_value = arr[0]
for value in arr:
if value > max_value:
max_value = value
index = get_index(max_value)
print('The greatest value in the array is', max_value)
print('The index of the greatest value in the array is', index)
return index
find_index_in_array(test_array)
| true |
e4ad61b609bed028b402265b224db05ceef7e2de | itaditya/Python | /Maths/toPostfixConv.py | 937 | 4.125 | 4 | from stack import Stack
def prec(operator):
if(operator == '^'):
return 3
elif(operator == '*' or operator == '/'):
return 2
elif(operator == '+' or operator == '-'):
return 1
else:
return -1
# print("Not a valid operator")
def postfixConv():
s = Stack()
expression = list(raw_input())
i = 0
postfixExp = ""
l = len(expression)
while(i < l):
if(prec(expression[i]) != -1):
# means we get operations
if(prec(s.peek()) < prec(expression[i])):
# simple situation
s.push(expression[i])
else:
postfixExp += s.pop()
s.push(expression[i])
else:
# means we get operands
postfixExp += expression[i]
i += 1
while(prec(s.peek()) != -1):
postfixExp += s.pop()
print postfixExp
postfixConv()
# a + b + c
| true |
275fe7b79c7c091237ce170cb043b4983a1fc1b2 | SweLinHtun15/GitFinalTest | /Sets&Dictionaries.py | 1,520 | 4.1875 | 4 | #Sets
#include a data type for sets
#Curly braces on the set() function can be used create sets.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
#Demonstrates set operations on unique letters from two words
a = set('abracadabra')
b = set('alacazm')
a # unique letter in a
a - b # letter in a but not in b
a | b # letters in a or b or both
a & b # letters in both a and b
a ^ b # letters in a or b but not both
a = {x for x in 'abracadabra' if x not in 'abc'}
a
fruits = {"apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"}
print("cherry" in fruits)
fruits.add("cucumber")
fruits
fruits.update("grape", "water melon")
fruits
fruits.remove("banana")
fruits
fruits.discard("kiwi")
fruits
>>>Dictionaries
#Dictionaries
#Another useful data type bulit into python is the dictionary
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
tel
del tel['sape']
tel['irv'] = 4127
tel
list(tel)
sorted(tel)
dict([('sape', 4098,),('guido', 4139), ('irv', 3123)])
dict(sape=4139, guido=4127, jack=4098)
{x: x**2 for x in (2,4,6)}
{x: x**3 for x in (1,2,3,4,5)}
#when looping through dictionaries
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k,v)
for i, v in enumerate(['tic','toc','toe']):
print(i,v)
questions = ['name', 'quest', 'favourite color']
answers = ['lancelot', 'the holy graill', 'blue']
for q, a in zip(questions, answers):
... print('What is your{0}? It is {1}.'.format(q,a))
| true |
885d43c1619d5ddd8166a60492eb74f026778c5f | Candy-Robot/python | /python编程从入门到实践课后习题/第七章、用户输入与循环/while.py | 1,683 | 4.15625 | 4 | """
prompt = "\nwhat Pizza ingredients do you want: "
prompt += "\n(Enter 'quit' when you are finished) "
while True:
order = input(prompt)
if order == 'quit':
break
print("we will add this "+order+" for you")
prompt = "\nwhat Pizza ingredients do you want: "
prompt += "\n(Enter 'quit' when you are finished) "
massage = ''
while massage != 'quit':
massage = input(prompt)
if massage != 'quit':
print("we will add this "+massage+" for you")
prompt = "\nhow old are you,tell me: "
flag = True
while flag:
age = input(prompt)
age = int(age)
if age <= 3:
price = 0
elif age <= 12:
price = 10
elif age > 12:
price = 15
print("your ticket price is "+str(price))
sandwich_orders = ['pastrami','tuna','pastrami','turkey'
,'pig','pastrami','salad']
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
finished_sandwiches.append(sandwich)
print("I made your "+sandwich+" sandwich")
print(finished_sandwiches)
print(sandwich_orders)
print("-------------------------------")
print('pastrami is sold out')
while 'pastrami' in finished_sandwiches:
finished_sandwiches.remove('pastrami')
print(finished_sandwiches)
"""
dream_place = {}
massage = "If you could visit one place in the world,where would you go?\n"
active = True
while active:
name = input("what's your name: ")
place = input(massage)
dream_place[name] = place
print("did you finished?")
flag = input("YES/NO\n")
if flag == 'YES':
active = False
for name,place in dream_place.items():
print(name+" want to go to "+place)
print(dream_place)
| true |
07df07e0d977f286a3cb28c187f5a4adbbd2fd12 | samyhkim/algorithms | /56 - merge intervals.py | 977 | 4.25 | 4 | '''
sort by start times first
if one interval's end is less than other interval's start --> no overlap
[1, 3]: ___
[6, 9]: _____
if one interval's end is greater than other interval's started --> overlap
[1, 3]: ___
[2, 6]: _____
'''
def merge(intervals):
merged = []
intervals.sort(key=lambda i: i[0]) # sort by start times
for interval in intervals:
# add to merged if the list of merged intervals is empty
# or if the curr interval does not overlap with the prev
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
# otherwise, there is overlap: prev end > curr start
# merge the greater between curr's end and prev's end
# ex: [1, 3] and [2, 6] or [1, 5] and [2, 4]
else:
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
input = [[1, 3], [2, 6], [8, 10], [15, 18]]
output = [[1, 6], [8, 10], [15, 18]]
print(merge(input) == output)
| true |
79ca667df5a747c3926ca8806022df645789d6d5 | abisha22/S1-A-Abisha-Accamma-vinod | /Programming Lab/27-01-21/prgm4.py | 437 | 4.25 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> def word_count(str):
counts=dict()
words=str.split()
for word in words:
if word in counts:
counts[word]+=1
else:
counts[word]=1
return counts
>>> print(word_count('Think before you do'))
{'Think': 1, 'before': 1, 'you': 1, 'do': 1}
>>> | true |
a00231b5aaa06630c3237083ca1650384ce7d71b | FJLRivera86/Python | /Dictionary.py | 1,118 | 4.53125 | 5 | #DICTIONARY {}: Data structure Like Tuple or List
#It's possible save elements,list or tuples in a dictionary
firstDictionary = {"Germany":"Berlin", "France":"Paris", "England":"London", "Spain":"Madrid"}
#To print a value, It's necessary say its KEY
print(firstDictionary)
print(firstDictionary["England"])
#ADD element
firstDictionary["México"]="León"
print(firstDictionary)
#MODIFY element value
firstDictionary["México"]="Ciudad de México"
print(firstDictionary)
#DELETE element
del firstDictionary["France"]
print(firstDictionary)
secondDictionary = {"Team":"Chicago Bulls", 1:"23", 23:"Michael Jordan"}
print(secondDictionary)
#TUPLE for use as KEY and asign VALUES in a DICTIONARY
languageTuple = ["México", "France", "Brazil", "Italy"]
languageDictionary = {languageTuple[0]:"Spanish", languageTuple[1]:"French", languageTuple[2]:"Portuguese", languageTuple[3]:"Italian"}
print(languageDictionary)
print(languageDictionary["Brazil"])
#
alumnDictionary = {1:"Aguirre", 2:"Biurcos", 3:"Cazares", 4:"Durazo", "Group":{"year":["1st F", "2nd F", "3th F"]}}
print(alumnDictionary["Group"])
print[alumnDictionary.keys()] | true |
2d042a110b5642719a60a1d5aedc4528bb40cb86 | momentum-cohort-2019-05/w2d1-house-hunting-redkatyusha | /house_hunting.py | 754 | 4.1875 | 4 | portion_down_payment = .25
current_savings = 0
r = .04
months = 0
annual_salary_as_str = input("Enter your annual salary: ")
portion_saved_as_str = input(
"Enter the percent of your salary to save, as a decimal: ")
total_cost_as_str = input("Enter the cost of your dream home: ")
annual_salary = int(annual_salary_as_str)
portion_saved = float(portion_saved_as_str)
total_cost = int(total_cost_as_str)
down_payment = total_cost / portion_down_payment
if annual_salary > 0:
monthly_savings = (annual_salary / 12) * portion_saved
else:
print("You have no income, buddy.")
while current_savings < down_payment:
months += 1
current_savings += monthly_savings + (current_savings * (r / 12))
print("Number of months:", str(months)) | true |
f2ce62028c31efdc396f3209e1c30681daa87c17 | pmxad8/cla_python_2020-21 | /test_files/test_1.py | 769 | 4.21875 | 4 | ################### code to plot some Gaussians ####################################
#### import libraries ####
import math
import numpy as np #import numerical library
import matplotlib.pyplot as plt #allow plotting
n = 101 # number of points
xx = np.linspace(-10,10,n) #vector of linearly spaced points
s = 0.5,1,1.5,2,5 # vector of sigma values
g = np.zeros(n) # making vector of n zeros
## reoding stupid python syntax. This syntax is clunky and I hate it...
PI = math.pi
EXP = np.exp
SQRT= math.sqrt
## loop over all sigma values
for sig in s: #this is apparently how loops work in python?
g = 1/(sig*SQRT(2*PI)) * EXP(-xx**2/(2*sig**2)) # formula of Gaussian curve
plt.plot(xx,g,linestyle = '--') # update python plot
plt.show() # actually show the figure
| true |
7deff2841c1b9164ff335a4b1cb11c3266482a00 | SuryaDhole/tsf_grip21 | /main.py | 2,683 | 4.125 | 4 | # Author: Surya Dhole
# Technical TASK 1: Prediction using Supervised ML (Level - Beginner)
# Task Description: in this task, we will predict the percentage of marks that a student
# is expected to score based upon the number of hours
# they studied. This is a simple linear regression task as it involves just two variables.
# Importing required libraries
import pandas as pd
import numpy as np
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# Importing and Reading the dataset from remote link
data = pd.read_csv('http://bit.ly/w-data')
print(data)
print("data imported successfully!")
# Plotting the distribution of score
data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Scored')
plt.show()
# dividing the data into "attributes" (inputs) and "labels" (outputs)
x = data.iloc[:, :-1].values
y = data.iloc[:, 1].values
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)
# Training the model
reg = LinearRegression()
reg.fit(x_train.reshape(-1, 1), y_train)
print("Trained!!")
# Plotting the regression line
line = reg.coef_ * x + reg.intercept_
# Plotting for the test data
plt.scatter(x, y)
plt.plot(x, line, color='Black')
plt.show()
# Testing data - In Hours
print(x_test)
# Predicting the scores
y_predict = reg.predict(x_test)
# Comparing Actual vs Predicted
data = pd.DataFrame({'Actual': y_test, 'Predicted': y_predict})
print(data)
# Estimating the Training Data and Test Data Score
print("Training score:", reg.score(x_train, y_train))
print("Testing score:", reg.score(x_test, y_test))
# Plotting the line graph to depict the difference between actual and predicted value.
data.plot(kind='line', figsize=(8, 5))
plt.grid(which='major', linewidth='0.5', color='black')
plt.grid(which='major', linewidth='0.5', color='black')
plt.show()
# Testing the model.
hours = 8.5
test_data = np.array([hours])
test_data = test_data.reshape(-1, 1)
own_predict = reg.predict(test_data)
print("Hours = {}".format(hours))
print("Predicted Score = {}".format(own_predict[0]))
# Checking the efficiency of model
# This is the final step to evaluate the performance of an algorithm.
# This step is particularly important to compare how well different algorithms
# perform on a given dataset
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_predict))
print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_predict))
print('Root mean squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_predict)))
| true |
eeb9ffe5b8ebe9beb9eda161b15b61ccea90ba9a | RezaZandi/Bank-App-Python | /old_code/switch_satements.py | 758 | 4.15625 | 4 |
"""
def main():
print("hi")
main_console = ("\nSelect an option to begin:")
main_console += ("\nEnter 0 to Create a new account")
main_console += ('\nEnter 1 to Deposit')
main_console += ('\nEnter 2 to Withdraw')
main_console += ('\n What would you like to do?: ')
while True:
user_option = int(input(main_console))
"""
def action_1():
print("action1")
def action_2():
print("action2")
def action_3():
print("i'm happy with option 3")
def unknown_action():
print("unknown")
main_console = ("choose a number ")
number_choice = int(input("choose a number: "))
switcher = {
1:
action_1,
2:
action_2,
3:
action_3
}
switcher.get(number_choice,unknown_action)()
| true |
382fbdd4d1b95633025b9f2951ddaa904a1727f1 | AdaniKamal/PythonDay | /Day2/Tuple.py | 2,762 | 4.53125 | 5 | #Tuple
#1
#Create a Tuple
# Set the tuples
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
weekend = "Saturday", "Sunday"
# Print the tuples
print('-------------------------EX1---------------------------------')
print(weekdays)
print(weekend)
#2
#Single Item Tuples
a = ("Cat")
b = ("Cat",)
print('-------------------------EX2---------------------------------')
print(type(a))
print(type(b))
#3
#Tuple containing a List
# Set the tuple
t = ("Banana", ['Milk', 'Choc', 'Strawberry'])
print('-------------------------EX3---------------------------------')
# Print the tuple
print(t)
#4
#Access the Values in a Tuple
# Set the tuple
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
print('-------------------------EX4---------------------------------')
# Print the second element of the tuple
print(weekdays[1])
#range
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
print(weekdays[1:4])
#5
#Access a List Item within a Tuple
t = (101, 202, ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"])
print('-------------------------EX5---------------------------------')
print(t[2][1])
#6
#Update a Tuple
# Set and print the initial tuple
weekend = ("Saturday", "Sunday")
print('-------------------------EX6---------------------------------')
print(weekend)
# Reassign and print
weekend = ("Sat", "Sun")
print(weekend)
#7
#Update a List Item within a Tuple
# Assign the tuple
t = (101, 202, ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"])
print('-------------------------EX7---------------------------------')
print(t)
# Update the third list item
t[2][2] = "Humpday"
print(t)
#8
#Concatenate Tuples (Combine)
#Can also use a tuple as the basis for another tuple.
#For example, can concatenate a tuple with another one to create a new a tuple that contains values from both tuples.
# Set two tuples
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
weekend = ("Saturday", "Sunday")
# Set a third tuple to the value of the previous two
alldays = weekdays + weekend
print('-------------------------EX8---------------------------------')
# Print them all
print(weekdays)
print(weekend)
print(alldays)
#9
#Delete a Tuple
t = (1,2,3)
del t
#10
#Named Tuples
#Need to import modules
# Import the 'namedtuple' function from the 'collections' module
from collections import namedtuple
# Set the tuple
individual = namedtuple("Individual", "name age height")
user = individual(name="R3in3", age=20, height=160)
print('-------------------------EX10---------------------------------')
# Print the tuple
print(user)
# Print each item in the tuple
print(user.name)
print(user.age)
print(user.height)
print('-------------------------THANK YOU---------------------------------')
| true |
9ffe03358e681158af1452776150deb8057eaa29 | violetscribbles/Learn-Python-3-the-Hard-Way-Personal-Exercises | /Exercises 1 - 10/ex9.py | 791 | 4.28125 | 4 | # Here's some new strange stuff, remember type it exactly.
# Defines 'days' variable as a string
days = "Mon Tue Wed Thu Fri Sat Sun"
# Defines 'months' variable as a string. Each month is preceded by \n, which
# is an escape character that tells python to create a new line before the
# text.
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
# Prints a string and then variable 'days'
print("Here are the days: ", days)
# Prints a string and then variable 'months'
print("Here are the months: ", months)
# Prints a multi-line string using """, which achieves the same effect as
# /n but is more readable.
print("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
| true |
974f629117846daae4de8b0e22b1d68407763078 | study-material-stuff/Study | /Study/Python/Assignments/Assignment 8/Assignment8_5.py | 570 | 4.28125 | 4 | #5.Design python application which contains two threads named as thread1 and thread2.
#Thread1 display 1 to 50 on screen and thread2 display 50 to 1 in reverse order on
#screen. After execution of thread1 gets completed then schedule thread2.
import threading;
def DispNumbers():
for no in range(1,51):
print(no);
def DispReverseNumbers():
for no in range(50,0,-1):
print(no);
thread1 = threading.Thread(target = DispNumbers );
thread2 = threading.Thread(target = DispReverseNumbers);
thread1.start();
thread1.join();
thread2.start(); | true |
2fb056ddefd2368f9947f213e92627b9e09071e1 | study-material-stuff/Study | /Study/Python/Assignments/Assignment 4/Assignment4_1.py | 238 | 4.28125 | 4 | #1.Write a program which contains one lambda function which accepts one parameter and return
#power of two.
powerof2 = lambda num : num * num;
num = int(input("Enter the number :"));
print("power of the number is ",powerof2(num)); | true |
d023f2fe5bfb44a3ca32176ad557542eeaf0883b | Devil-Rick/Advance-Task-6 | /Inner and Outer.py | 506 | 4.1875 | 4 | """
Task
You are given two arrays: A and B .
Your task is to compute their inner and outer product.
Input Format
The first line contains the space separated elements of array A .
The second line contains the space separated elements of array B .
Output Format
First, print the inner product.
Second, print the outer product.
Sample Input
"""
import numpy as np
A, B = [np.array([input().split()], int) for _ in range(2)]
print(np.inner(A, B)[0][0], np.outer(A, B), sep="\n")
| true |
e9ff6b17552a2cc278d5817ce0ced6ef730cc144 | ilakya-selvarajan/Python-programming | /mystuff/4prog2.py | 353 | 4.21875 | 4 | #a program that queries the user for number, and proceeds to output whether the number is an even or an odd number.
number=1
while number!=0:
number = input("Enter a number or a zero to quit:")
if number%2==0 and number!=0:
print "That's an even number"
continue
if number%2==1:
print "That's an odd number"
if number==0:
print "bye"
| true |
876eb77d4a81863b5d478f37827c0298a4270cf2 | ilakya-selvarajan/Python-programming | /mystuff/7prog6.py | 440 | 4.125 | 4 | #A function which gets as an argument a list of number tuples, and sorts the list into increasing order.
def sortList(tupleList):
for i in range( 0,len(tupleList) ):
for j in range(i+1, len(tupleList) ):
if tupleList[j][0]*tupleList[j][1]<tupleList[i][0]*tupleList[i][1]:
temp=tupleList[j]
tupleList[j]=tupleList[i]
tupleList[i]=temp
myList = [(2, 3.0), (3, 1.0), (4, 2.5), (1, 1.0)]
sortList(myList)
print myList
| true |
eee40d974a515868c2db25c959e1cfa303002d00 | ilakya-selvarajan/Python-programming | /mystuff/8prog4.py | 433 | 4.21875 | 4 | # A function to find min, max and average value
from __future__ import division
def minMaxAvg(dict):
sum=0
myTuple=()
myValues= dict.values() #extracting the values
for values in myValues:
sum+=values
avg=sum/len(myValues) #Calculating the average
myTuple=(min(myValues),max(myValues),avg) #Returning the min, max, and avg
return myTuple
d = {"a":0, "b":-1, "c":3, "d":6, "e":11, "f":8}
print minMaxAvg(d) | true |
68b01adeba8e433530175f0c39a80c5c336d1ce3 | thinboy92/HitmanFoo | /main.py | 2,562 | 4.21875 | 4 | ### Animal is-a object (yes, sort of confusing) look at the extra credit
class animal(object):
def __init__(self, type):
self.type = type
def fly(self):
print "This %s can fly" %(self.type)
## Dog is-a animal
class Dog(animal):
def __init__(self, name):
# class Doh has-a __init__ that accepts self and name parameters
## Dog has-a name
self.name = name
## cat is-a animal
class Cat(animal):
def __init__(self, name):
## class Cat has-a __init__ that accepts self and name parameters
self.name = name
## Person is-a object
class Person(object):
def __init__(self, name):
## class Person has-a __init__ that accepts self and name parameters
self.name = name
## Person has-a pet of some kind
self.pet = None
## Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
super(Employee, self).__init__(name) ## this
## gives access to the name attribute
## of Employee's parent object i.e. Person.
## apparently useful in the case of multiple inheritance.
## Employee has-a salary
self.name = name
self.salary = salary
print "%s's salary is %d" % (self.name,self.salary)
def write(self,name,salary):
print "This is invoked by using function in a class. %s's salary is %d" % (name,salary)
## Fish is-a object
class Fish(object):
def __init__(self,steam):
self.steam = steam()
def fry():
print "Whether to steam or fry %s" %(self.steam)
## Salmon is-a Fish
class Salmon(Fish):
pass
## Halibut is-a Fish
class Halibut(Fish):
pass
## rover is-a Dog
rover = Dog("Rover")
## Satan is-a Cat
satan = Cat("Satan")
## Mary is-a Person
mary = Person("Mary")
## From mary, take the attribute pet and set it to variable satan.
mary.pet = satan # Now, mary's pet is-a cat object named satan
## frank is-a Employee with parameters Frank and 120000
frank = Employee("Frank", 120000)
frank.write("Frank", 120000)
## from frank, take the pet attribute and set it to rover.
frank.pet = rover # frank's pet is-a dog object named rover
## set flipper to an instance of class Fish
# flipper is-a fish
#flipper = Fish(steam)
##afeez, When I run it in python or Terminal this is what I get:
##Traceback (most recent call last):
## File "ex42.py", line 85, in <module>
## flipper = Fish()
##TypeError: __init__() takes exactly 2 arguments (1 given)
## setting crouse to an instance of class Salmon
# course is-a salmon and salmon is-a fish
#crouse = Salmon()
## set harry to an instance of class Halibut
# harry is-a halibut and halibut is-a fish
#harry = Halibut()
| true |
03bc0cf52a337355dc9d829995465da3778f8531 | bulsaraharshil/MyPyPractice_W3 | /class.py | 1,071 | 4.40625 | 4 | class MyClass:
x = 5
print(MyClass)
#Create an object named p1, and print the value of x
class MyClass:
x=5
p1=MyClass()
print(p1.x)
#Create a class named Person, use the __init__() function to assign values for name and age
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
p1 = Person("John",36)
print(p1.name)
print(p1.age)
#Insert a function that prints a greeting, and execute it on the p1 object
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is "+ self.name)
p1 = Person("John",36)
p1.myfunc()
#Use the words mysillyobject and abc instead of self
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
#Set the age of p1 to 40
p1.age = 40
print(p1.age)
#Delete the age property from the p1 object
del p1.age
print(p1.age)
#Delete object p1
del p1
print(p1) | true |
1f468a2055ef8548a517fb5333f574737a2da217 | bulsaraharshil/MyPyPractice_W3 | /lambda.py | 768 | 4.5 | 4 | #lambda arguments : expression
#A lambda function that adds 10 to the number passed in as an argument, and print the result
x = lambda x:x+5
print(x(5))
#A lambda function that multiplies argument a with argument b and print the result
x = lambda a,b:a*b
print(x(5,6))
#A lambda function that sums argument a, b, and c and print the result
x = lambda a,b,c:a+b+c
print(x(5,6,7))
#Use that function definition to make a function that always doubles the number you send in
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
#use the same function definition to make both functions, in the same program
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(12))
| true |
36b2d60352a9e55abb53d30f25e98319383dadc0 | dindamazeda/intro-to-python | /lesson3/exercise/7.element-non-grata.py | 542 | 4.28125 | 4 | # We have a list of sweets. Write a program that will ask the user which is his least favourite sweet and then remove that sweet from the list
### example ###
# sweets = ['jafa', 'bananica', 'rum-kasato', 'plazma', 'mars', 'bananica']
# program: Which one is your least favourite?
# korisnik: bananica
# program: ['jafa','rum-kasato', 'plazma', 'mars']
sweets = ['jafa', 'bananica', 'rum-kasato', 'plazma', 'mars', 'bananica']
print(sweets)
input_sweet = input('Which one is your least favpurite? ')
sweets.remove(input_sweet)
print(sweets) | true |
05cb1521168d0320f080cd8c25137ea9ef6e91b9 | dindamazeda/intro-to-python | /lesson2/exercises/3.number-guessing.py | 821 | 4.1875 | 4 | # Create list of numbers from 0 to 10 but with a random order (import random - see random module and usage)
# Go through the list and on every iteration as a user to guess a number between 0 and 10
# At end the program needs to print how many times the user had correct and incorrect guesses
# random_numbers = [5, 1, 3, 9, 7, 2, 4, 6, 8]
# program: Guess a number between 0 and 10.
# (If we look at the above list the current number is 5) user: 8
# program: That is not a correct number. Try to guess a new number between 0 and 10.
# (If we look at the above list the next number is 1) user: 1
# program: Bravo! That is the correct number. Try to guess a new one.
# The program continues until the end of the list...
# program: Congratulations. You've guessed the correct number 3 times and 7 times you were not correct. | true |
227d3c1780cca1ea0979d759c9a383fcdafb2314 | dindamazeda/intro-to-python | /lesson1/exercises/6.more-loops_dm.py | 612 | 4.3125 | 4 | # write a loop that will sum up all numbers from 1 to 100 and print out the result
### example ###
# expected result -> 5050
sum = 0
for numbers in range(1, 101):
sum = sum + numbers
print(sum)
# with the help of for loop triple each number from this list and print out the result
numbers = [5, 25, 66, 3, 100, 34]
for number in numbers:
triple = number * 3
print(triple)
# with the help of for loop and range() function print out all odd numbers from 1 to 100
### example ###
# program: 1, 3, 5, 7 etc.
for numbers in range(1, 101):
if numbers % 2 == 0:
continue
print(numbers)
| true |
bb941f4da9976abb554a43fe2d348ec956587cf1 | micalon1/small_tasks | /part5.py | 760 | 4.125 | 4 | shape = input("Enter a shape: ")
s = "square"
r = "rectangle"
c = "circle"
if shape == s:
l = int(input("What is the length of the square? "))
print("The area of the square is {}.". format(l**2))
elif shape == r:
h = int(input("What is the height of the rectangle? "))
w = int(input("What is the width of the rectangle? "))
print("The area of the rectangle is {}.". format(h*w))
elif shape == c:
r = int(input("What is the radius of the circle? "))
q = input("Enter 'c' for circumference or 'a' for area: ")
if q == "c":
print("The circumference is {}.". format(6*r))
elif q == "a":
print("The area is {}.". format(3*r**2))
else:
print("Invalid choice.")
else:
print("Invalid shape.") | true |
7bd385f1465918ac1c73311062647516a0d8ce74 | ritesh2k/python_basics | /fibonacci.py | 328 | 4.3125 | 4 | def fibonacci(num):
if num==0: return 0
elif num==1: return 1
else:
return fibonacci(num-1)+fibonacci(num-2) #using recursion to generate the fibonacci series
num=int(input('How many fibonacci numbers do you want? \n'))
print('Fibonacci numbers are :\n')
for i in range(num):
print(fibonacci(i) , end=' ')
print()
| true |
7c3e9c6db39509af1c38818f60a5b9c9697697c4 | ritesh2k/python_basics | /sentence_capitalization.py | 429 | 4.3125 | 4 | def capitalization(str):
str=str.strip()
cap=''
for i in range(len(str)):
if i==0 or str[i-1]==' ':cap=cap+str[i].upper() #checking for the space and the first char of the sentence
else: cap=cap+str[i] #capitalizing the character after space
#cap =[words[0].upper()+words[1:]]
print ('The result is:\n{}'.format(cap))
str=input('Enter the sentence and each word will be capitalized:\n')
capitalization(str) | true |
7a6c27963f8e1adcba4b636cd29fdf598acdde0b | YeasirArafatRatul/Python | /reverse_string_stack.py | 492 | 4.125 | 4 | def reverse_stack(string):
stack = [] #empty
#make the stack fulled by pushing the characters of the string
for char in string:
stack.append(char)
reverse = ''
while len(stack) > 0:
last = stack.pop()
#here the pop function take the last character first thats why
#we have to put it as the right operand
reverse = reverse + last
return reverse
string = input("Give Input:")
result = reverse_stack(string)
print(result)
| true |
817a383769b024049a81ad3e76be36231099462d | YeasirArafatRatul/Python | /reverse_string_functions.py | 340 | 4.625 | 5 | def reverse_string(string):
reverse = "" #empty
for character in string:
"""
when we concate two strings the right string
just join in the left string's end.
"""
reverse = character + reverse
return reverse
string = input("Enter a string:")
result = reverse_string(string)
print(result)
| true |
2c5b1e85b26ea93a1f6636758db8889b28b7798a | tnotstar/tnotbox | /Python/Learn/LPTHW/ex06_dr01.py | 822 | 4.5 | 4 | # assign 10 to types_of_people
types_of_people = 10
# make a string substituting the value of types_of_people
x = f"There are {types_of_people} types of people."
# assign some text to some variables
binary = "binary"
do_not = "don't"
# make a string substituting last variable's values
y = f"Those who know {binary} and those who {do_not}."
# printing string variables
print(x)
print(y)
# printing formatting string values
print(f"I said: {x}")
print(f"I also said: '{y}'")
# assigning some values to some variables
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
# printing a formatted string
print(joke_evaluation.format(hilarious))
# again, assigning some text to some vars
w = "This is the left side of..."
e = "a string with a right side."
# printing a concatenation expression
print(w + e) | true |
833d91dfe8f65ce41b7dfa9b4ae15632a03e6170 | undefinedmaniac/AlexProjects | /Basic Python Concepts/if statements and loops.py | 1,580 | 4.40625 | 4 | # If statements are used to make decisions based on a conditional statement
# for example, the value in a variable could be used
variable1 = True
variable2 = False
if variable1:
print("True")
# else if statements can be added to check for additional conditions
if variable1:
print("Variable 1 is True")
elif variable2:
print("Variable 2 is True")
# else statements can be added as a sort of "default" for when none of the other
# conditions are met
if variable1:
print("Variable 1 is True")
elif variable2:
print("Variable 2 is True")
else:
print("Variable 1 and Variable 2 are both False")
# Remember that only one of the available branches in an if statement is executed
# Also remember OR and AND operators
if variable1 or variable2:
print("Variable 1 or Variable 2 is True (or possibly both)")
if variable1 and variable2:
print("Variable 1 and Variable 2 are both True")
# Now fixed count loops
# Count to 10 and print 0 - 9
# i is the index for each loop
for i in range(10):
print(i)
# Python allows easy looping through lists as well
list1 = ["Hello", "There", "Alex"]
for i in list1:
print(i)
# While loops repeat steps until a condition is false
# Count to 10 and print 0 - 9
count = 0
while count != 10:
print(count)
count += 1
# This is commonly used as an infinite loop
while True:
# "break" leaves a loop early
break
# "continue" skips the rest of the code in a loop and moves to the next iteration
# Print 0 - 9 but skip 5
for i in range(10):
if i == 5:
continue
print(i)
| true |
971247c94cba717a85b4d900b0f93ae2bb6338a1 | radek-coder/simple_calculator | /run_it.py | 636 | 4.21875 | 4 | from addition import addition
from multiplication import multiplication
from division import division
from subtraction import subtraction
num_1 = int(input("Please insert your first number: "))
num_2 = int(input("Please insert your second number: "))
operation = input("Please insert your operation ")
if operation == "x" or operation == "X" or operation == "*":
print(multiplication(num_1, num_2))
elif operation == "+":
print(addition(num_1, num_2))
elif operation == "-":
print(subtraction(num_1, num_2))
elif operation == "/":
print(division(num_1, num_2))
else:
print("You are trying to break my calculator")
| true |
f88b699c69329d90c31d9b9d18ca19bb7f671090 | Arl-cloud/Python-basics | /basics5.py | 2,327 | 4.28125 | 4 | #For loops: How and Why
monday_temperatures = [9.1, 8.8, 7.6]
print(round(monday_temperatures[0])) #print rounded number with index 0
#in 1st iteration, variable temp = 9.1, in the 2nd iteration 8.8
for temp in monday_temperatures:
print(round(temp)) #executed command for all items in an array
print("Done")
for letter in "hello":
print(letter.title()) #array can also be a string
#For loop (with if condition) that prints out only numbers in colors over 50
colors = [11, 34, 98, 43, 45, 54, 54]
for foo in colors:
if foo > 50:
print(foo)
#prints out only if number in colors is type integer
for boo in colors:
if isinstance(boo, int): #use isinstance to check for type
print(boo)
#Loops for dictionaries
student_grades = {"Marry": 9.9, "Sim": 6.5, "John": 7.4}
for grades in student_grades.items(): #iterates over ITEMS (= key + value)
print(grades) #keys(names) and values are printed out in a tupel
for grades2 in student_grades.keys(): #iterates over keys
print(grades2)
for grades3 in student_grades.values(): #iterates over values
print(grades3)
#Combining dictionary loop and string formatting
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for key, value in phone_numbers.items():
print("{}: {}".format(key, value))
#replace "+" with "00" in phone numbers
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for value in phone_numbers.values():
print(value.replace("+", "00"))
#a for loop runs until a container is exhausted
for i in [1, 2, 3]:
print(i)
#a while loop runs as long as its condition is TRUE
a = 3
#while a > 0: will run endlessly, as this condition is always true
# print(1)
#execution of this loop ends when user types in "pypy" as username
username = "" #variable username is an empty string
while username != "pypy": #!= means is different than
#in the first iteration, variable username is an empty string-thus different than "pypy" and one gets the print
#in the second iteration, the variable username is what is entered by user
username = input("Enter username: ")
#while loops with break and continue
while True: #is always true
name = input("Enter name: ")
if name == "pypy": #if variable name is "pypy"
break #stops loop
else:
continue | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.