blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
d7de4f27b05171c1a29e6fd4f1b0fab5e872dbaf
|
AnshumanSinghh/DSA
|
/Sorting/selection_sort.py
| 864
| 4.28125
| 4
|
def selection_sort(arr, n):
for i in range(n):
min_id = i
for j in range(i + 1, n):
if arr[min_id] > arr[j]:
min_id = j
arr[min_id], arr[i] = arr[i], arr[min_id]
return arr
# Driver Code Starts
if __name__ == "__main__":
arr = list(map(int, input("Enter the array elements: ").split()))
print(selection_sort(arr, len(arr)))
"""
Time Complexity: O(n2) as there are two nested loops.
Auxiliary Space: O(1)
The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write
is a costly operation.
Exercise :
Sort an array of strings using Selection Sort
Stability : The default implementation is not stable. However it can be made stable. Please see stable selection
sort for details.
In Place : Yes, it does not require extra space.
"""
| true
|
d124e426fc4a6f6f42c2942a8ce753e31c07ba56
|
AnniePawl/Tweet-Gen
|
/class_files/Code/Stretch_Challenges/reverse.py
| 1,036
| 4.28125
| 4
|
import sys
def reverse_sentence(input_sentence):
"""Returns sentence in reverse order"""
reversed_sentence = input_sentence[::-1]
return reversed_sentence
def reverse_word(input_word):
"""Returns word in reverse order"""
reversed_word = input_word[::-1]
return reversed_word
def reverse_reverse(input):
"""Returns words AND sentence in reverse order"""
# Call reverse_sentence func, put words in new variable (type list)
reverse_input = reverse_sentence(input)
# Initialize new list to hold reversed newly words
reverse_list = []
# Iterate over each word in list, call reverse_word func
for word in reverse_input:
backwards_word = reverse_word(word)
reverse_list.append(backwards_word)
return " ".join(reverse_list)
if __name__ == '__main__':
# input_word = sys.argv[1:]
# print(reverse_word(input_word))
# input_sentence = sys.argv[1:]
# print(reverse_sentence(input_sentence))
input = sys.argv[1:]
print(reverse_reverse(input))
| true
|
5428b2f9dce1f91420c57963dcd1e80275e3c6cb
|
AnniePawl/Tweet-Gen
|
/class_files/Code/rearrange.py
| 864
| 4.125
| 4
|
import sys
import random
def rearrange_words(input_words):
"""Randomly rearranges a set of words provided as commandline arguments"""
# Initiate new list to hold rearranged words
rearranged_words = []
# Randomly place input words in rearranged_words list until all input words are used
while len(rearranged_words) < len(input_words):
rand_index = random.randint(0, len(input_words) - 1)
rand_word = input_words[rand_index]
# Skip words that have already been seen
if rand_word in rearranged_words:
continue
rearranged_words.append(rand_word)
# Turn list into a nicely formatted string
result = ' '.join(rearranged_words)
return result
if __name__ == '__main__':
# remember argument one is file name!
input_words = sys.argv[1:]
print(rearrange_words(input_words))
| true
|
f76a969859f8cdbfedb6a147d505ae1fc788dc19
|
Chris-Valenzuela/Notes_IntermediatePyLessons
|
/4_Filter.py
| 664
| 4.28125
| 4
|
# Filter Function #4
# Filter and map are usually used together. The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.
# filter(function, iterable) - takes in the same arguements as map
def add7(x):
return x+7
def isOdd(x):
return x % 2 != 0
a = [1,2,3,4,5,6,7,8,9,10]
# this is useful because we can do this instead of running a for loop with conditions
b = list(filter(isOdd, a))
print(b)
# here we are adding 7 to each filterd list
c = list(map(add7, filter(isOdd, a)))
print(c)
# Use Case: We can use filter to return things that have a certain digit or string etc..
| true
|
df1920f69ffd2cab63280aa8140c7cade46d6289
|
bhavyanshu/PythonCodeSnippets
|
/src/input.py
| 1,297
| 4.59375
| 5
|
# Now let us look at examples on how to ask the end user for inputs.
print "How many cats were there?",
numberofcats = int(raw_input())
print numberofcats
# Now basically what we have here is that we take user input as a string and not as a proper integer value as
# it is supposed to be. So this is a major problem because you won't be able to apply any kind of math operation on string type value.
# Now in the next example i will show you how to accept a string from user and let python convert it to an integer type value.
print "How many kittens were there?",
numberofkittens = int(raw_input())
print numberofkittens
# What's the difference between input() and raw_input()?
# The input() function will try to convert things you enter as if they were Python code, but it has security problems so you should avoid it.
#There is an easier way to write the above input prompter in single line. Let's take a look"
numberofDogs= int(raw_input("Total number of Dogs?")) #Easy, isn't it?
print numberofDogs
print "*********************Let us now print the input data******************"
print "*Number of cats are %d, number of kittens are %d & number of dogs are %d"%(numberofcats,numberofkittens,numberofDogs)+"*"
print "**********************************************************************"
| true
|
c0c986476ddb5849c3eb093487047acb2a8cadec
|
jlassi1/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/4-append_write.py
| 413
| 4.34375
| 4
|
#!/usr/bin/python3
"""module"""
def append_write(filename="", text=""):
"""function that appends a string at the end of a text file (UTF8)
and returns the number of characters added:"""
with open(filename, mode="a", encoding="UTF8") as myfile:
myfile.write(text)
num_char = 0
for word in text:
for char in word:
num_char += 1
return num_char
| true
|
8583fccda88b05dd25b0822e1e403de2ad64af11
|
Sisyphus235/tech_lab
|
/algorithm/tree/lc110_balanced_binary_tree.py
| 2,283
| 4.40625
| 4
|
# -*- coding: utf8 -*-
"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_balanced_recursive1(root: TreeNode) -> bool:
if root is None:
return True
left = get_depth(root.left)
right = get_depth(root.right)
if abs(left - right) > 1:
return False
return is_balanced_recursive1(root.left) and is_balanced_recursive1(root.right)
def get_depth(node: TreeNode) -> int:
if node is None:
return 0
return 1 + max(get_depth(node.left), get_depth(node.right))
def is_balanced_recursive2(root: TreeNode) -> bool:
if check_depth(root) == -1:
return False
return True
def check_depth(node: TreeNode) -> int:
if node is None:
return 0
left = check_depth(node.left)
if left == -1:
return -1
right = check_depth(node.right)
if right == -1:
return -1
if abs(left - right) > 1:
return -1
else:
return 1 + max(left, right)
def test_is_balanced():
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
assert is_balanced_recursive1(root) is True
assert is_balanced_recursive2(root) is True
root = TreeNode(1)
assert is_balanced_recursive1(root) is True
assert is_balanced_recursive2(root) is True
root = TreeNode(1)
root.right = TreeNode(2)
assert is_balanced_recursive1(root) is True
assert is_balanced_recursive2(root) is True
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
assert is_balanced_recursive1(root) is False
assert is_balanced_recursive2(root) is False
if __name__ == '__main__':
test_is_balanced()
| true
|
3c7c978a4d753e09e2b12245b559960347972b37
|
Sisyphus235/tech_lab
|
/algorithm/tree/lc572_subtree_of_another_tree.py
| 1,623
| 4.3125
| 4
|
# -*- coding: utf8 -*-
"""
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure
and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def subtree_of_another_tree(s: TreeNode, t: TreeNode) -> bool:
if not s:
return False
if is_same_tree(s, t):
return True
return subtree_of_another_tree(s.left, t) or subtree_of_another_tree(s.right, t)
def is_same_tree(s: TreeNode, t: TreeNode) -> bool:
if not s and not t:
return True
if not s or not t:
return False
if s.val != t.val:
return False
return is_same_tree(s.left, t.left) and is_same_tree(s.right, t.right)
def test_subtree_of_another_tree():
s_root = TreeNode(3)
s_root.left = TreeNode(4)
s_root.right = TreeNode(5)
s_root.left.left = TreeNode(1)
s_root.left.right = TreeNode(2)
t_root = TreeNode(4)
t_root.left = TreeNode(1)
t_root.right = TreeNode(2)
assert subtree_of_another_tree(s_root, t_root) is True
if __name__ == '__main__':
test_subtree_of_another_tree()
| true
|
1651e397c9fb56f6c6b56933babc60f97e830aac
|
Sisyphus235/tech_lab
|
/algorithm/array/find_number_occuring_odd_times.py
| 1,177
| 4.25
| 4
|
# -*- coding: utf8 -*-
"""
Given an array of positive integers.
All numbers occur even number of times except one number which occurs odd number of times.
Find the number in O(n) time & constant space.
Examples :
Input : arr = {1, 2, 3, 2, 3, 1, 3}
Output : 3
Input : arr = {5, 7, 2, 7, 5, 2, 5}
Output : 5
"""
def odd_times_n_space(array: list) -> int:
"""
space complexity: O(n)
:param array:
:return:
"""
hash_space = {}
for e in array:
if e in hash_space:
del hash_space[e]
else:
hash_space[e] = e
return list(hash_space.values())[0]
def odd_times_1_space(array: list) -> int:
"""
space complexity: O(1)
XOR method, comply with commutative property
:return:
"""
for i in range(len(array) - 1):
array[i + 1] = array[i] ^ array[i + 1]
return array[-1]
def test_odd_times():
array = [1, 2, 3, 2, 3, 1, 3]
assert odd_times_n_space(array) == 3
assert odd_times_1_space(array) == 3
array = [5, 7, 2, 7, 5, 2, 5]
assert odd_times_n_space(array) == 5
assert odd_times_1_space(array) == 5
if __name__ == '__main__':
test_odd_times()
| true
|
3cc965eda451b01a9c0f8eee2f80f64ea1d902a3
|
Sisyphus235/tech_lab
|
/algorithm/tree/lc145_post_order_traversal.py
| 1,363
| 4.15625
| 4
|
# -*- coding: utf8 -*-
"""
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
BUFFER = []
def post_order_traversal_recursive(root: TreeNode):
if root is not None:
post_order_traversal_recursive(root.left)
post_order_traversal_recursive(root.right)
BUFFER.append(root.val)
def post_order_traversal_iterative(root: TreeNode) -> List[int]:
ret = []
stack = [(root, False)]
while stack:
root, is_visited = stack.pop()
if root is None:
continue
if is_visited:
ret.append(root.val)
else:
stack.append((root, True))
stack.append((root.right, False))
stack.append((root.left, False))
return ret
def test_post_order_traversal():
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
post_order_traversal_recursive(root)
assert BUFFER == [3, 2, 1]
assert post_order_traversal_iterative(root) == [3, 2, 1]
if __name__ == '__main__':
test_post_order_traversal()
| true
|
d7eda822fb84cd5abd4e7a66fa76eec506b09599
|
omarfq/CSGDSA
|
/Chapter14/Exercise2.py
| 960
| 4.25
| 4
|
# Add a method to the DoublyLinkedList class that prints all the elements in reverse order
class Node:
def __init__(self, data):
self.data = data
self.next_element = None
self.previous_element = None
class DoublyLinkedList:
def __init__(self, head_node, last_node):
self.head_node = head_node
self.last_node = last_node
def print_in_reverse(self):
current_node = self.last_node
while current_node.previous_element:
print(current_node.data, end=' -> ')
current_node = current_node.previous_element
print(current_node.data, '-> None')
node_1 = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
node_1.next_element = node_2
node_2.previous_element = node_1
node_2.next_element = node_3
node_3.previous_element = node_2
node_4.previous_element = node_3
doubly_linked_list = DoublyLinkedList(node_1, node_4)
doubly_linked_list.print_in_reverse()
| true
|
3f13fa57a9d0e51fd4702c7c7814e0e277cb8f36
|
omarfq/CSGDSA
|
/Chapter13/Exercise2.py
| 277
| 4.125
| 4
|
# Write a function that returns the missing number from an array of integers.
def find_number(array):
array.sort()
for i in range(len(array)):
if i not in array:
return i
return None
arr = [7, 1, 3, 4, 5, 8, 6, 9, 0]
print(find_number(arr))
| true
|
63226638939260126c5d1ee013b0f76e9d5f5812
|
Temujin18/trader_code_test
|
/programming_test1/solution_to_C.py
| 506
| 4.3125
| 4
|
"""
C. Write a rotate(A, k) function which returns a rotated array A, k times; that is, each
element of A will be shifted to the right k times
○
rotate([3, 8, 9, 7, 6], 3) returns [9, 7, 6, 3, 8]
○
rotate([0, 0, 0], 1) returns [0, 0, 0]
○
rotate([1, 2, 3, 4], 4) returns [1, 2, 3, 4]
"""
from typing import List
def rotated_array(input_arr: List[int], key) -> List[int]:
return input_arr[-key:] + input_arr[:-key]
if __name__ == "__main__":
print(rotated_array([3, 8, 9, 7, 6], 3))
| true
|
ea13ba0ca0babd500a0b701db9693587830a4546
|
cryoMike90s/Daily_warm_up
|
/Basic_Part_I/ex_21_even_or_odd.py
| 380
| 4.28125
| 4
|
"""Write a Python program to find whether a given number (accept from the user) is even or odd,
print out an appropriate message to the user."""
def even_or_odd(number):
if (number % 2 == 0) and (number > 0):
print("The number is even")
elif number == 0:
print("This is zero")
else:
print("The number is odd")
number = 5
even_or_odd(number)
| true
|
4bb88de5f9de506d24fe0ff4acf2c43bb4bc7bca
|
momentum-team-3/examples
|
/python/oo-examples/color.py
| 1,888
| 4.3125
| 4
|
def avg(a, b):
""" This simple helper gets the average of two numbers.
It will be used when adding two Colors.
"""
return (a + b) // 2 # // will divide and round all in one.
def favg(a, b):
""" This simple helper gets the average of two numbers.
It will be used when adding two Colors. Unlike avg,
it does not round the result.
"""
return (a + b) / 2
def normalize_rgb(color_value: int) -> int:
if color_value < 0:
return 0
elif color_value > 255:
return 255
else:
return color_value
def normalize_alpha(alpha_value: float) -> float:
if alpha_value < 0.0:
return 0.0
elif alpha_value > 1.0:
return 1.0
else:
return alpha_value
class Color:
""" This class represents a color in RGBA format. Because colors can be mixed to
produce a new color, this class implements __add__. The __init__ method will ensure
that r, g, and b are between 0 and 255, and a is between 0 and 1.
"""
def __init__(self, r, g, b, a=1.0):
# Make sure r, g, and b are between 0 and 255 and
# make sure alpha is between 0.0 and 1.0
self.r = normalize_rgb(r)
self.g = normalize_rgb(g)
self.b = normalize_rgb(b)
self.a = normalize_alpha(a)
def liked_by_bob_ross(self):
return True
def __add__(self, other):
if not isinstance(other, Color):
raise TypeError("Cannot add Color and non-Color.")
else:
r = avg(self.r, other.r)
g = avg(self.g, other.g)
b = avg(self.b, other.b)
a = favg(self.a, other.a)
return Color(r,g,b,a)
def __repr__(self):
# Delegate to __str__
return self.__str__()
def __str__(self):
return f"<Color r={self.r} g={self.g} b={self.b} a={self.a}>"
| true
|
c20d16b102e1e408648cf055eb2b37a6d5198987
|
VSpasojevic/PA
|
/vezba05/stablo/stablo/stablo.py
| 2,136
| 4.21875
| 4
|
class Node:
"""
Tree node: left child, right child and data
"""
def __init__(self, p = None, l = None, r = None, d = None):
"""
Node constructor
@param A node data object
"""
self.parent = p
self.left = l
self.right = r
self.data = d
class Data:
"""
Tree data: Any object which is used as a tree node data
"""
def __init__(self, val1, val2):
"""
Data constructor
@param A list of values assigned to object's attributes
"""
self.key = val1
self.a2 = val2
class TBTS:
def __init__(self, r=None):
self.root=r
#self.len=l
def MakeNode(parent,n1,n2):
#prolazi i sa poredjenjem sa jednim if-om kao sto sam prvo i uradio
if parent.data.key <= n1.data.key:
n1.parent=parent
parent.right=n1
else:
n2.parent=parent
parent.left=n1
if parent.data.key <= n2.data.key:
n2.parent=parent
parent.right=n2
else:
n2.parent=parent
parent.left=n2
def PrintNode(node):
#print("parent:",node.parent.data.key)
print("levi:",node.left.data.key)
print("right:",node.right.data.key)
def ThreeInsert(T,z):
y=None
x=T.root
while x is not None:
y=x
if z.data.key < x.data.key:
x=x.left
else:
x=x.right
z.p=y
if y is None:
T.root=z
elif z.data.key < y.data.key:
y.left=z
else:
y.right=z
def InorderThreeWalk(x):
if x is not None:
InorderThreeWalk(x.left)
print("x->key",x.data.key)
InorderThreeWalk(x.right)
d1 = Data(1, 2)
d2 = Data(3, 4)
d3 = Data(5, 6)
d4 = Data(15, 16)
print(d1.key, d1.a2)
print(d2.key, d2.a2)
print(d3.key, d3.a2)
n1=Node(None,None,None,d2)
n2=Node(None,None,None,d1)
n3=Node(None,None,None,d3)
n4=Node(None,None,None,d4)
MakeNode(n1,n2,n3)
PrintNode(n1)
r= TBTS()
ThreeInsert(r,n1)
#print ("n2->key",n2.data.key)
ThreeInsert(r,n2)
ThreeInsert(r,n3)
#ThreeInsert(r,n4)
InorderThreeWalk(n2)
| false
|
26f77ff9d2e26fe9e711f5b72a4d09aed7f45b16
|
gaoshang1999/Python
|
/leetcod/dp/p121.py
| 1,421
| 4.125
| 4
|
# 121. Best Time to Buy and Sell Stock
# DescriptionHintsSubmissionsDiscussSolution
# Discuss Pick One
# Say you have an array for which the ith element is the price of a given stock on day i.
#
# If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
#
# Example 1:
# Input: [7, 1, 5, 3, 6, 4]
# Output: 5
#
# max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
# Example 2:
# Input: [7, 6, 4, 3, 1]
# Output: 0
#
# In this case, no transaction is done, i.e. max profit = 0.
import sys
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
lowest = sys.maxsize
highest = 0;
n = len(prices)
for i in range(n):
if prices[i] < lowest:
lowest = prices[i]
elif prices[i] - lowest > highest :
highest = prices[i] - lowest
return highest
s = Solution()
# p =[7, 1, 5, 3, 6, 4]
# print s.maxProfit(p)
# p =[7, 1, 5, 3, 6, 4, 7]
# print s.maxProfit(p)
p =[7, 1, 4, 7, 0, 2, 10]
print(s.maxProfit(p))
# p = [7, 6, 4, 3, 1]
# print s.maxProfit(p)
#
# p = [2,4,1]
# print s.maxProfit(p)
#
# p = [3,2,6,5,0,3]
# print s.maxProfit(p)
| true
|
fe82dce52d79df152dc57e93ae6e97e9efa722e5
|
keerthiballa/PyPart4
|
/fibonacci_linear.py
| 856
| 4.3125
| 4
|
"""
Exercise 3
Create a program called fibonacci_linear.py
Requirements
Given a term (n), determine the value of x(n).
In the fibonacci_linear.py program, create a function called fibonnaci. The function should take in an integer and return the value of x(n).
This problem must be solved WITHOUT the use of recursion.
Constraints
n >= 0
Answer below:
"""
n = int(input("Provide a number greater than or equal to 0: "))
def fibonacci(n):
first_num=0
second_num=1
if n>=0:
for i in range(1,n,1):
third_num = first_num + second_num
first_num = second_num
second_num = third_num
print(third_num)
else:
print("You need to provide a valid input to run the function")
if n>=0 and n<=30:
fibonacci(n)
else:
print("You need to provide a valid input to run the function")
| true
|
38367ab9a4c7cc52c393e9c22b1752dd27e0f0f4
|
eugenejazz/python2
|
/task02-2.py
| 625
| 4.25
| 4
|
# coding: utf-8
# 2. Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560, то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
def checkeven(x):
if (int(x) % 2) == 0:
return 1
else:
return 0
def checkodd(x):
if (int(x) % 2) == 0:
return 0
else:
return 1
a = str(input("Введите число: "))
even=0
odd=0
for i in a:
even = even + checkeven(i)
odd = odd + checkodd(i)
print(f'Четные: {even}')
print(f'Нечетные: {odd}')
| false
|
4e480a91ec51f5a2b8bf4802c3bd40d134cac839
|
eugenejazz/python2
|
/task02-3.py
| 412
| 4.4375
| 4
|
# coding: utf-8
# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
# Например, если введено число 3486, то надо вывести число 6843.
def reversestring(x):
return(print(x[::-1]))
a = str(input("Введите число: "))
reversestring(a)
| false
|
fcfcbf9381003708979b90a0ca204fe54fe747cc
|
amit-shahani/Distance-Unit-Conversion
|
/main.py
| 1,193
| 4.25
| 4
|
def add_unit(list_of_units, arr):
unit = str(input('Enter the new unit: ').lower())
conversion_ratio = float(
input('Enter the conversion ration from metres: '))
list_of_units.update({unit: conversion_ratio})
# arr.append(unit)
return list_of_units, arr
def conversion(list_of_units, arr):
length = float(input("Length: "))
unit = input('Unit: ').lower()
if unit not in list_of_units.keys():
print("Invalid Unit.")
return
print([x for x in arr][:len(arr)])
targeted_unit = str(input('Targeted Unit: '))
if targeted_unit not in list_of_units.keys():
print("Invalid Unit")
return
else:
print(float(length)*list_of_units[targeted_unit])
if __name__ == '__main__':
n = int(input(
'Press 1 : For Conversion.\nPress 2 : For For adding a unit.\nPress 3 : To Exit.\n'))
list_of_units = {'metres': 1, 'yard': 1.094,
'inches': 2.54, 'feet': 2.80840, 'kilometre': 0.001}
arr = ['metres', 'yard', 'inches', 'feet', 'kilometre']
if(n == 1):
conversion(list_of_units, arr)
elif (n == 2):
add_unit(list_of_units, arr)
else:
exit
| true
|
a5f7e54bd93e3445690ab874805e4e57005cecde
|
galhyt/python_excercises
|
/roads.py
| 2,852
| 4.125
| 4
|
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'numberOfWays' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY roads as parameter.
#
# returns the number of ways to put 3 hotels in three different cities while the distance between the hotels is equal
def numberOfWays(roads):
# Write your code here
print(roads)
dist_dict = {}
def set_dist_dict(new_key, key):
dist_dict[new_key] = dist_dict[key] + 1 if new_key not in dist_dict.keys() else min(dist_dict[new_key],
dist_dict[key] + 1)
def check_key(r):
keys = [(min(key), max(key)) for key in dist_dict.keys()]
new_keys = []
for key in keys:
if r[0] not in key and r[1] not in key: continue
if r[0] == key[1]:
if key[0] != r[1]:
new_key = (min(key[0], r[1]), max(key[0], r[1]))
set_dist_dict(new_key, key)
new_keys.append(new_key)
if r[0] == key[0]:
if key[1] != r[1]:
new_key = (min([key[1], r[1]]), max([key[1], r[1]]))
set_dist_dict(new_key, key)
new_keys.append(new_key)
if r[1] == key[0]:
if r[0] != key[1]:
new_key = (min([r[0], key[1]]), max([r[0], key[1]]))
set_dist_dict(new_key, key)
new_keys.append(new_key)
if r[1] == key[1]:
if r[0] != key[0]:
new_key = (min([r[0], key[0]]), max([r[0], key[0]]))
set_dist_dict(new_key, key)
new_keys.append(new_key)
return new_keys
for _ in range(len(roads)):
for r in map(lambda x: (min(x), max(x)), roads):
dist_dict[r] = 1
check_key(r)
print(dist_dict)
def distance(a, b):
return dist_dict[(a,b)]
ret = 0
n = len(roads)+1
for i in range(1,n-1):
for j in range(i+1,n):
for k in range(j+1, n+1):
dist_ij = distance(i, j)
if dist_ij == distance(i, k) and dist_ij == distance(j, k):
ret += 1
return ret
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
with open("input1_roads.txt") as file:
lines = file.readlines()
roads_rows = int(lines[0].strip())
roads_columns = int(lines[1].strip())
roads = []
for i in range(2, len(lines)):
roads.append(list(map(int, lines[i].rstrip().split())))
result = numberOfWays(roads)
print(result)
# fptr.write(str(result) + '\n')
#
# fptr.close()
| true
|
1bd458f150f97dd84780f65da401e59ec7fbfd5a
|
pkiop/Timechecker_web
|
/TimeChecker_web/backend/server/templates/python_class_example.py
| 260
| 4.25
| 4
|
#python_class_example.py
class MyClass:
"""A simple example class이건 독 스트링"""
i = 12345
def f(self):
return 'hello world'
def __init__(self, a):
self.i = a
# def __init__(self):
# self.i = 22222
x = MyClass(3)
print(x.i)
print(x.f())
| false
|
5c23070568b655b41f55e81f65a2d5840bd9b9c8
|
WesRoach/coursera
|
/specialization-data-structures-algorithms/algorithmic-toolbox/week3/solutions/7_maximum_salary/python/largest_number.py
| 979
| 4.3125
| 4
|
from typing import List
from functools import cmp_to_key
def compare(s1: str, s2: str) -> int:
"""Returns orientation of strings producing a smaller integer.
Args:
s1 (str): first string
s2 (str): second string
Returns:
int: one of: (-1, 0, 1)
-1: s1 first produces smaller int
0: No difference
1: s2 first produces smaller int
"""
s1_first = int(s1 + s2)
s2_first = int(s2 + s1)
if s1_first > s2_first:
return 1
elif s2_first > s1_first:
return -1
else:
return 0
def largest_number(a: List[str]) -> str:
"""Compose the largest number out of a set of integers.
Args:
a (List[str]): list of integers
Returns:
str: largest number that can be composed of `a`
"""
return "".join(sorted(a, reverse=True, key=cmp_to_key(compare)))
if __name__ == "__main__":
_ = input()
print(largest_number(input().split()))
| true
|
9901dd9ebb20c27db8e1519bcd71db450b7a7b2e
|
baxter-t/Practice
|
/codingProblems/productFib.py
| 399
| 4.25
| 4
|
'''
Find the product of nth fibonacci numbers
'''
def nthFib(n):
if n == 0 or n == 1:
return n
return nthFib(n-1) + nthFib(n-2)
def prodFib(prod):
n = 2
product = nthFib(n) * nthFib(n - 1)
while product <= prod:
if product == prod:
return True
n += 1
product = nthFib(n) * nthFib(n - 1)
return False
print(prodFib(5895))
| false
|
0b52e4ad1eef997e3a8346eb6f7ea30c4a591bb9
|
JankaGramofonomanka/alien_invasion
|
/menu.py
| 1,794
| 4.21875
| 4
|
from button import Button
class Menu():
"""A class to represent a menu."""
def __init__(self, screen, space=10):
"""Initialize a list of buttons."""
self.buttons = []
self.space = space
self.height = 0
self.screen = screen
self.screen_rect = screen.get_rect()
#Number of selected button.
self.selected = -1
def add(self, button, n = 'default'):
"""Add a button to menu."""
if n == 'default':
n = len(self.buttons)
if self.buttons:
if self.selected >= n:
self.selected += 1
else:
self.selected = 0
self.buttons.insert(n, button)
self.height = self.get_height()
def remove(self, n):
"""Remove a button from the menu."""
self.buttons[self.selected].selected = False
del self.buttons[n]
self.height = self.get_height()
self.selected = self.selected % len(self.buttons)
self.select(self.selected)
def select(self, n=0):
"""Select a button."""
if self.buttons:
self.buttons[self.selected].selected = False
self.selected = n
self.buttons[n].selected = True
else:
self.selected = -1
def get_height(self):
"""Return height of all buttons."""
height = 0
if self.buttons:
for button in self.buttons:
height += button.height + self.space
height -= self.space
return height
def get_top(self):
"""Return top of first button ."""
return self.screen_rect.centery - (self.height / 2)
def prep_buttons(self):
"""Place buttons in a right position."""
prev_button_bot = self.get_top() - self.space
for button in self.buttons:
button.rect.y = prev_button_bot + self.space
button.prep_msg()
prev_button_bot = button.rect.bottom
def draw_buttons(self):
"""Draw all buttons from 'self.buttons'."""
self.prep_buttons()
for button in self.buttons:
button.draw_button()
| true
|
ee19f685bf59a801596b6f4635944680ada27bc9
|
MateuszSacha/Iteration
|
/development exercise 1.py
| 317
| 4.3125
| 4
|
# Mateusz Sacha
# 05-11-2014
# Iteration Development exercise 1
number = 0
largest = 0
while not number == -1:
number = int(input("Enter a number:"))
if number > largest:
largest = number
if number == -1:
print("The largest number you've entered is {0}".format(largest))
| true
|
8995e16a70f94eddc5e26b98d51b1e03799ef774
|
MateuszSacha/Iteration
|
/half term homework RE3.py
| 302
| 4.1875
| 4
|
# Mateusz Sacha
# Revision exercise 3
total = 0
nofnumbers = int(input("How many number do you want to calculate the average from?:"))
for count in range (0,nofnumbers):
total = total + int(input("Enter a number:"))
average = total / nofnumbers
print("The average is {0}".format(average))
| true
|
5cbed6cdc2549ec225e478fb061deeff30cf5666
|
lleonova/jobeasy-algorithms-course
|
/4 lesson/Longest_word.py
| 305
| 4.34375
| 4
|
# Enter a string of words separated by spaces.
# Find the longest word.
def longest_word(string):
array = string.split(' ')
result = array[0]
for item in array:
if len(item) > len(result):
result = item
return result
print(longest_word('vb mama nvbghn bnb hjnuiytrc'))
| true
|
8a69feedb8da68729ee69fd193a3db2d8c59dc88
|
lleonova/jobeasy-algorithms-course
|
/2 lesson/Fibonacci.py
| 1,251
| 4.28125
| 4
|
# The equation for the Fibonacci sequence:
# φ0 = 0, φ1 = 1, φn = φn−1 + φn−2.
#
# The task is to display all the numbers from start to n of the Fibonacci sequence φn
# Equation:
# F0 = 0
# F1 = 1
# F2 = 1
# Fn = Fn-1 + Fn-2
def fibonacci(n):
fibonacci_1 = 1
fibonacci_2 = 1
if n == 0:
print(0)
if n > 0:
print(fibonacci_1)
if n > 1:
print(fibonacci_2)
index = 0
while index < n - 2:
fibonacci_1, fibonacci_2 = fibonacci_2, fibonacci_1 + fibonacci_2
index += 1
print(fibonacci_2)
print(fibonacci(5))
# TODO: HW: Rewrite code, which will return only needed element of Fib sequence
def fibonacci_1(n):
fibonacci_1 = 1
fibonacci_2 = 1
if n == 0:
return(0)
elif n == 1:
return(1)
else:
fibr_number = 1
index = 0
while index < n - 2:
fibonacci_1, fibonacci_2 = fibonacci_2, fibonacci_1 + fibonacci_2
fibr_number = fibonacci_2
index += 1
return(fibr_number)
print(fibonacci_1(5))
# Use of recursion
def fibonacci_2(n):
if n == 0:
return(0)
if n == 1:
return(1)
return(fibonacci_2(n-1) + fibonacci_2(n-2))
print(fibonacci_2(5))
| false
|
04e373740e134f7b71f655c44b76bba0c51bd6a1
|
lleonova/jobeasy-algorithms-course
|
/3 lesson/Count_substring_in_the_string.py
| 720
| 4.28125
| 4
|
# Write a Python function, which will count how many times a character (substring)
# is included in a string. DON’T USE METHOD COUNT
def substring_in_the_string(string, substring):
index = 0
count = 0
if len(substring) > len(string):
return 0
elif len(substring) == 0 or len(string) == 0:
return 0
while index <= len(string) - len(substring):
if substring == string[index:len(substring)+ index]:
count +=1
index += len(substring)
index += 1
return count
# s1 = input("please enter a string of characters:")
# s2 = input("please enter a substring of characters:")
s1 = "aabbaaabba"
s2 = "aa"
print(substring_in_the_string(s1, s2))
| true
|
66db39164628280219e3849c8cddeed370915ccb
|
pragatirahul123/practice_folder
|
/codeshef1.py
| 206
| 4.1875
| 4
|
# Write a program to print the numbers from 1 to 20 in reverse order.
# Output: 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
var=20
while var>=1:
print(var," ",end="")
var=var-1
| true
|
3f69d6abcca9971f266402b6eda42e62a399aab2
|
OdayaGU/TestProject
|
/TestProject/src/homework_1.py
| 373
| 4.15625
| 4
|
import pandas as pd
print ("welcome to your first HW: FILTER BY. So yallaa...")
df = pd.DataFrame({"ID":[703,783,788,780,790],"NAME":["John","James","Marry","Gil","Roy"], "LEVEL":[5,5,4,5,4],"GRADE":[87,88,90,65,100]})
print (df)
print ("--------------")
print ("Your task: given the dataframe above print on screen all those that their grade is grater than 80")
| false
|
3491a2c56d9e5761996237f2be8060de2a8a6e4b
|
BDDM98/Evaluador-Posfijo
|
/compilador.py
| 2,100
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
class Pila:
""" Representa una pila con operaciones de apilar, desapilar y
verificar si está vacía. """
def __init__(self):
""" Crea una pila vacía. """
# La pila vacía se representa con una lista vacía
self.items=[]
def apilar(self, x):
""" Agrega el elemento x a la pila. """
# Apilar es agregar al final de la lista.
self.items.append(x)
def desapilar(self):
""" Devuelve el elemento tope y lo elimina de la pila.
Si la pila está vacía levanta una excepción. """
try:
return self.items.pop()
except IndexError:
raise ValueError("La pila está vacía")
def es_vacia(self):
""" Devuelve True si la lista está vacía, False si no. """
return self.items == []
def verificar(caracteres):
datos=caracteres.split(" ")
print(datos)
while len(datos)+1!=0:
if len(datos)!=0:
try:
print(int(datos[0]),)
datos.pop(0)
except ValueError:
if datos[0]=="+" or datos[0]=="-" or datos[0]=="*" or datos[0]=="/" or datos[0]=="\n":
print("Error en los operadores")
return 0
else:
for i in len(datos):
if datos[i]=="+" or datos[i]=="-" or datos[i]=="*" or datos[i]=="/" or datos[i]=="\n":
print("ok")
datos.pop(i)
# except ValueError:
# return 0
#except ValueError:
# return 0
else:
print("ok")
return 1
def leer(nombre):
operaciones = Pila()
archivo = open(nombre,"r")
for linea in archivo.readlines():
print linea
verificar(linea)
operaciones.apilar(linea)
archivo.close()
leer("pruebita.txt")
| false
|
a1acd77a9c1adbe44056a532909bc9378681122a
|
OnoKishio/Applied-Computational-Thinking-with-Python
|
/Chapter15/ch15_storyTime.py
| 781
| 4.1875
| 4
|
print('Help me write a story by answering some questions. ')
name = input('What name would you like to be known by? ')
location = input('What is your favorite city, real or imaginary? ')
time = input('Is this happening in the morning or afternoon? ')
color = input('What is your favorite color? ')
town_spot = input('Are you going to the market, the library, or the park? ')
pet = input('What kind of pet would you like as your companion? ')
pet_name = input('What is your pet\'s name? ')
print('There once was a citizen in the town of %s, whose name was %s. %s loved to hang \
with their trusty %s, %s.' % (location, name, name, pet, pet_name))
print('You could always see them strolling through the %s \
in the %s, wearing their favorite %s attire.' % (town_spot, time, color))
| true
|
3cca295b200f107f100923509c3a31077be52995
|
akashbaran/PyTest
|
/github/q6.py
| 635
| 4.25
| 4
|
"""Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24 """
import math
C = 50
H = 30
D = raw_input("enter the values for D: ")
lst = D.split(',')
val = []
#print(lst)
for d in lst:
val.append(str(int(round(math.sqrt(2*C*float(d)/H)))))
print(','.join(val))
| true
|
b0b2d09c383a9d1354caf54eedc9d0df4a0e9d6a
|
akashbaran/PyTest
|
/github/q21.py
| 1,077
| 4.40625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 30 15:34:34 2018
@author: eakabar
A robot moves in a plane starting from the original point (0,0).
The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.
The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps.
Please write a program to compute the distance from current position
after a sequence of movement and original point.
If the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
"""
import math
l,r=0,0
while True:
s = input("enter direction ")
if not s:
break
lst = s.split(" ")
dir=lst[0]
pos=int(lst[1])
if dir == 'UP':
r = r + pos
elif dir == 'DOWN':
r = r - pos
elif dir == 'LEFT':
l = l - pos
elif dir == 'RIGHT':
l = l + pos
else:
pass
res = int(math.sqrt((l**2) + (r**2)))
print(res)
| true
|
c6e7af5146e9bcacd925ea9579dd15a8f571bfed
|
akashbaran/PyTest
|
/github/re_username1.py
| 405
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 12:25:27 2018
@author: eakabar
Assuming that we have some email addresses in the "username@companyname.com" format,
please write program to print the user name of a given email address.
Both user names and company names are composed of letters only.
"""
import re
emailAddress = input()
pat2 = "(\w+)@((\w+\.)+(com))"
r2 = re.match(pat2,emailAddress)
print(r2.group(1))
| true
|
b761d29007cc6ccf91f4c838e7fb2f4ebc972e8f
|
JimNastic316/TestRepository
|
/DictAndSet/challenge_simple_deep_copy.py
| 1,020
| 4.375
| 4
|
# write a function that takes a dictionary as an argument
# and returns a deep copy of the dictionary without using
# the 'copy' module
from contents import recipes
def my_deepcopy(dictionary: dict) -> dict:
"""
Copy a dictionary, creating copies of the 'list' or 'dict' values
:param dictionary: The dictionary to copy
:return: a copy of dictionary, with values being copies of the original values
"""
#
dictionary_copy = {}
for key, value in dictionary.items():
new_value = value.copy()
dictionary_copy[key] = new_value
return dictionary_copy
# create a new, empty dictionary
# iterate over the keys and values of the dictionary
# for each key, copy the value,
# then add a copy of the value to the dictionary
# test data
recipes_copy = my_deepcopy(recipes)
recipes_copy["Butter chicken"]["ginger"] = 300 #value is '3' in recipes
print(recipes_copy["Butter chicken"]["ginger"])
print(recipes["Butter chicken"]["ginger"])
| true
|
42455a07e117cf79b631630e7fe65f6cceaf5911
|
micmoyles/hackerrank
|
/alternatingCharacters.py
| 880
| 4.15625
| 4
|
#!/usr/bin/python
'''
https://www.hackerrank.com/challenges/alternating-characters/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings
You are given a string containing characters and only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.
Your task is to find the minimum number of required deletions.
For example, given the string , remove an at positions and to make in deletions
'''
s = 'AABBABAB'
s = 'AAAA'
s = 'AAABBB'
def alternatingCharacters(s):
count = i = 0
while i < len(s) - 1:
j = i+1
print('Comparing element %d - %s and %d - %s' % (i,s[i],j,s[j]))
while s[i] == s[j]:
print('remove')
count+=1
j+=1
if j >= len(s): break
i = j
return count
print alternatingCharacters(s)
| true
|
3a53c4f41bf1a8604ea073a17762e2dcfc39c8d8
|
jbsec/pythonmessagebox
|
/Message_box.py
| 598
| 4.21875
| 4
|
#messagebox with tkinter in python
from tkinter import *
from tkinter import messagebox
win = Tk()
result1 = messagebox.askokcancel("Title1 ", "Do you really?")
print(result1) # yes = true no = false
result2 = messagebox.askyesno("Title2", "Do you really?")
print(result2) # yes = true no = false
result3 = messagebox.askyesnocancel("Title3", "Do you really?")
print(result3) # yes = true, no = false, cancel = none
messagebox.showinfo("Title", "a Tk MessageBox")
messagebox.showwarning("warning", "a Tk warning")
messagebox.showerror("error", "a Tk error")
win.mainloop()
| true
|
a993b0b69e113eefbf033a5a6c4bbebd432ad5e9
|
cs-fullstack-2019-fall/codeassessment2-insideoutzombie
|
/q3.py
| 1,017
| 4.40625
| 4
|
# ### Problem 3
# Given 2 lists of claim numbers, write the code to merge the 2
# lists provided to produce a new list by alternating values between the 2 lists.
# Once the merge has been completed, print the new list of claim numbers
# (DO NOT just print the array variable!)
# ```
# # Start with these lists
# list_of_claim_nums_1 = [2, 4, 6, 8, 10]
# list_of_claim_nums_2 = [1, 3, 5, 7, 9]
# ```
# Example Output:
# ```
# The newly created list contains: 2 1 4 3 6 5 8 7 10 9
# ```
# empty array to pass the data into
merge_array = []
list_of_claim_nums_1 = [2, 4, 6, 8, 10]
list_of_claim_nums_2 = [1, 3, 5, 7, 9]
# declare a function
def someFun():
# loop to cycle through the list1 array
for x in list_of_claim_nums_1:
# adds the array to the empty array
merge_array.append(x)
# loop to cycle through the list2 array
for y in list_of_claim_nums_2:
# adds the array to the empty array
merge_array.append(y)
return merge_array
print(someFun())
| true
|
dfccab9f95be2b883dddb721f22ddf50bf5b2166
|
roconthebeatz/python_201907
|
/day_02/dictionary_02.py
| 1,141
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
# 딕셔너리 내부에 저장된 데이터 추출 방법
# - 키 값을 활용
numbers = { "ONE" : 1, "TWO" : 2, "THREE" : 3 }
# [] 를 사용하여 값을 추출
print(f"ONE -> {numbers['ONE']}")
print(f"TWO -> {numbers['TWO']}")
print(f"THREE -> {numbers['THREE']}")
# [] 를 사용하여 값을 추출하는 경우
# 존재하지 않는 키값을 사용하면 에러가 발생됩니다.
print(f"FIVE -> {numbers['FIVE']}")
# 딕셔너리 변수의 get 메소드를 활용하여 값을 추출하는 경우
# 해당 키 값이 존재하면 저장된 Value 값이 반환되고
# 해당 키 값이 존재하지 않으면 None 값이 반환됩니다.
# None : 다른 프로그래밍 언어의 NULL 값과 같은 의미
# 아직 결정되지 않은 값을 의미
# (존재하지 않는 값)
print(f"ONE -> {numbers.get('ONE')}")
print(f"TWO -> {numbers.get('TWO')}")
print(f"THREE -> {numbers.get('THREE')}")
# 아래는 FIVE 키 값이 존재하지 않기때문에
# None 값이 반환됩니다.
print(f"FIVE -> {numbers.get('FIVE')}")
| false
|
ec2279635d73dfabdce13ef10a7922ad697939a2
|
roconthebeatz/python_201907
|
/day_02/list_03.py
| 484
| 4.25
| 4
|
# -*- coding: utf-8 -*-
# 리스트 내부 요소의 값 수정
# 문자열 데이터와 같은 경우 배열(리스트)의 형태로 저장되며
# 값의 수정이 허용되지 않는 데이터 타입입니다.
msg = "Hello Python~!"
msg[0] = 'h'
# 반면, 일반적인 리스트 변수는 내부 요소의 값을
# 수정할 수 있습니다.
numbers = [1,2,3,4,5]
print(f"before : {numbers}")
numbers[2] = 3.3
print(f"after : {numbers}")
| false
|
4d820a5480f429613b8f09ca50cacae0d2d5d377
|
roconthebeatz/python_201907
|
/day_03/while_02.py
| 603
| 4.28125
| 4
|
# -*- coding: utf-8 -*-
# 제어문의 중첩된 사용
# 제어문들은 서로 다른 제어문에 포함될 수 있음
# 1 ~ 100 까지의 정수를 출력하세요.
# (홀수만 출력하세요...)
step = 1
while step < 101 :
if step % 2 == 1 :
# 제어문 내부에 위한 또다른 제어문의
# 실행 코드는 해당 제어문의 영역에
# 포함되기 위해서
# 추가적으로 들여쓰기를 작성해야 합니다.
print(f"step => {step:3}")
step += 1
print("프로그램 종료")
| false
|
f8cee34470276d3eb0f8e127d6698c39990a68c2
|
yuto-te/my-python-library
|
/src/factrize_divisionize.py
| 730
| 4.21875
| 4
|
"""
素因数分解
約数列挙
"""
"""
e.g. 2**2 * 3**2 * 5**2 = [(2, 2), (3, 2), (5, 2)]
"""
def factorize(n):
fct = [] # prime factor
b, e = 2, 0 # base, exponent
while b * b <= n:
while n % b == 0:
n = n // b
e = e + 1
if e > 0:
fct.append((b, e))
b, e = b + 1, 0
if n > 1:
fct.append((n, 1))
return fct
"""
e.g. 900 = [1, 2, 3, ..., 450, 900]
"""
def divisionize(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
# divisors = sorted(divisors) # ソートが必要であれば
return divisors
| false
|
67eda0475ddaca871d0c092032a458f994e94a0d
|
dvbckle/RoboGarden-Bootcamp
|
/Create edit and Delete files.py
| 1,515
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 14:48:35 2019
@author: dvbckle
"""
# code snips to create, edit and delete files
def main():
_file = 'my_create_and_delete_file.txt'
_CreateFile(_file)
_WriteToFile(_file)
_ReadandPrintFromFile(_file)
_AppendToFile(_file)
_ReadandPrintFromFile(_file)
_DeleteFile(_file)
print('\nEnd of Main')
# Create a file
def _CreateFile(_file):
print('\nCreating file: ',_file)
f = open(_file, 'w')
# Write to a file
def _WriteToFile(_file):
print('\nWriting to file: ',_file)
l = ['hi', 'there', 'I', 'am', 'writing', 'in', 'a', 'file']
with open(_file, 'w') as f:
for s in l:
f.write(s + '\n')
#Read from a file
def _ReadandPrintFromFile(_file):
print('\nReading and Printing from file: ',_file)
with open(_file, 'r') as f:
for line in f:
print(line, end='')
#Append to a file
def _AppendToFile(_file):
print('\nAppending to file: ',_file)
with open(_file, 'a') as f:
f.write('Bye\n')
#Delete a file
def _DeleteFile(_file):
print('\nDeleting file: ',_file)
permission = input('\nAre you sure you want to delete '+_file + ' ,To Proceed, enter Yes')
if permission == 'Yes':
import os
os.remove(_file)
print('\nFile: ' + _file + ' has been deleted')
else:
print ('\nOK, ' +_file + 'will not be deleted')
return
main()
| false
|
af3dd2583562a8fa5f2a45dacb6eea900f1409f5
|
JiungChoi/PythonTutorial
|
/Boolean.py
| 402
| 4.125
| 4
|
print(2 > 1) #1
print(2 < 1) #0
print(2 >= 1) #1
print(2 <= 2) #1
print(2 == 1) #0
print(2 != 1) #1
print( 2 > 1 and "Hello" == "Hello") # 1 & 1
print(not True) #0
print(not not True) #1
#True == 1
print(f"True is {int(True)}")
x = 3
print(x > 4 or not (x < 2 or x == 3))
print(type(3))
print(type(True))
print(type("True"))
def hello():
print("Hello!")
print(type(hello))
print(type(print))
| true
|
7a93dfe5082ef046d45f4526081c317063641b66
|
rafal1996/CodeWars
|
/Remove exclamation marks.py
| 434
| 4.3125
| 4
|
#Write function RemoveExclamationMarks which removes all exclamation marks from a given string.
def remove_exclamation_marks(s):
count=s.count("!")
s = s.replace('!','',count)
return s
print(remove_exclamation_marks("Hello World!"))
print(remove_exclamation_marks("Hello World!!!"))
print(remove_exclamation_marks("Hi! Hello!"))
print(remove_exclamation_marks(""))
print(remove_exclamation_marks("Oh, no!!!"))
| true
|
4d32c35fbc001223bf7def3087a5e0f02aef8f09
|
rafal1996/CodeWars
|
/Merge two sorted arrays into one.py
| 597
| 4.3125
| 4
|
# You are given two sorted arrays that both only contain integers.
# Your task is to find a way to merge them into a single one, sorted in asc order.
# Complete the function mergeArrays(arr1, arr2), where arr1 and arr2 are the original sorted arrays.
#
# You don't need to worry about validation, since arr1 and arr2 must be arrays' \
# ' with 0 or more Integers. If both arr1 and arr2 are empty, then just return an empty array.
def merge_arrays(arr1, arr2):
return sorted(set(arr1 + arr2))
print(merge_arrays([1,2,3,4], [5,6,7,8]))
print(merge_arrays([1,3,5,7,9], [10,8,6,4,2]))
| true
|
9998009659bc70720c63ab399c45fb8adafe5e2b
|
sam-calvert/mit600
|
/problem_set_1/ps1b.py
| 1,827
| 4.5
| 4
|
#!/bin/python3
"""
Paying Debt Off In a Year
Problem 2
Now write a program that calculates the minimum fixed monthly payment needed in order pay
off a credit card balance within 12 months. We will not be dealing with a minimum monthly
payment rate.
Take as raw_input() the following floating point numbers:
1. the outstanding balance on the credit card
2. annual interest rate as a decimal
Print out the fixed minimum monthly payment, number of months (at most 12 and possibly less
than 12) it takes to pay off the debt, and the balance (likely to be a negative number).
Assume that the interest is compounded monthly according to the balance at the start of the
month (before the payment for that month is made). The monthly payment must be a multiple of
$10 and is the same for all months. Notice that it is possible for the balance to become negative
using this payment scheme. In short:
Monthly interest rate = Annual interest rate / 12.0
Updated balance each month = Previous balance * (1 + Monthly interest rate) – Minimum
monthly payment
"""
# Gather user input
balance = float(input("Enter the outstanding balance on your credit card: "))
interest_rate = float(input("Enter the anual credit card interest rate as a decimal: "))
# Set payment to $10 and test whether this will pay off the balance
# Increase payment by $10 until the correct answer is found
set_balance = balance
payment = 10
while True:
balance = set_balance
for month in range(1,13):
balance *= interest_rate/12 + 1
balance -= payment
if balance <= 0:
break
if balance <= 0:
break
payment += 10
print("RESULT \nMonthly payment to pay off debt in 1 year: %d \
\nNumber of months needed: %d \nBalance: %.2f" \
% (payment, month, balance))
| true
|
c806a5d9275a6026fb58cc261b8bfd95c1d66b90
|
keshavkummari/python-nit-7am
|
/Operators/bitwise.py
| 1,535
| 4.71875
| 5
|
'''--------------------------------------------------------------'''
# 5. Bitwise Operators :
'''--------------------------------------------------------------'''
"""
Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a = 60; and b = 13;
Now in binary format they will be as follows :
a = 0011 1100
b = 0000 1101
# Note: Python's built-in function bin() can be used to obtain binary
representation of an integer number.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
# Bitwise operators in Python :
Operator Meaning Example
1. & Bitwise AND x & y = 0 (0000 0000)
2. | Bitwise OR x | y = 14 (0000 1110)
3. ~ Bitwise NOT ~x = -11 (1111 0101)
4. ^ Bitwise XOR x ^ y = 14 (0000 1110)
5. >> Bitwise right shift x>> 2 = 2 (0000 0010)
6. << Bitwise left shift x<< 2 = 40 (0010 1000)
"""
#!/usr/bin/python3
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0
c = a & b # 12 = 0000 1100
print ("result of AND is ", c,':',bin(c))
c = a | b # 61 = 0011 1101
print ("result of OR is ", c,':',bin(c))
c = a ^ b # 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))
c = ~a # -61 = 1100 0011
print ("result of COMPLEMENT is ", c,':',bin(c))
c = a << 2 # 240 = 1111 0000
print ("result of LEFT SHIFT is ", c,':',bin(c))
c = a >> 2 # 15 = 0000 1111
print ("result of RIGHT SHIFT is ", c,':',bin(c))
| true
|
910fe52e3d7eafcec15c6d5e31cc8d33bd087942
|
keshavkummari/python-nit-7am
|
/DataTypes/Strings/unicodes.py
| 2,461
| 4.1875
| 4
|
Converting to Bytes. The opposite method of bytes.decode() is str.encode(),
which returns a bytes representation of the Unicode string,
encoded in the requested encoding.
The errors parameter is the same as the parameter of the
decode() method but supports a few more possible handlers.
UTF-8 is one such encoding.
The low codepoints are encoded using a single byte,
and higher codepoints are encoded as sequences of bytes.
Python's unicode type is a collection of codepoints.
The line ustring = u'A unicode \u018e string \xf1' creates a
Unicode string with 20 characters.
Python's str type is a collection of 8-bit characters. The English alphabet can be represented using these 8-bit characters, but symbols such as ±, ♠, Ω and ℑ cannot.
Unicode is a standard for working with a wide range of characters. Each symbol has a codepoint (a number), and these codepoints can be encoded (converted to a sequence of bytes) using a variety of encodings.
UTF-8 is one such encoding. The low codepoints are encoded using a single byte, and higher codepoints are encoded as sequences of bytes.
Python's unicode type is a collection of codepoints. The line ustring = u'A unicode \u018e string \xf1' creates a Unicode string with 20 characters.
When the Python interpreter displays the value of ustring, it escapes two of the characters (Ǝ and ñ) because they are not in the standard printable range.
The line s = unistring.encode('utf-8') encodes the Unicode string using UTF-8. This converts each codepoint to the appropriate byte or sequence of bytes. The result is a collection of bytes, which is returned as a str. The size of s is 22 bytes, because two of the characters have high codepoints and are encoded as a sequence of two bytes rather than a single byte.
When the Python interpreter displays the value of s, it escapes four bytes that are not in the printable range (\xc6, \x8e, \xc3, and \xb1). The two pairs of bytes are not treated as single characters like before because s is of type str, not unicode.
The line t = unicode(s, 'utf-8') does the opposite of encode(). It reconstructs the original codepoints by looking at the bytes of s and parsing byte sequences. The result is a Unicode string.
The call to codecs.open() specifies utf-8 as the encoding, which tells Python to interpret the contents of the file (a collection of bytes) as a Unicode string that has been encoded using UTF-8.
| true
|
f5c67e47e4140b3d92226fe3df69055c3a0c3d85
|
keshavkummari/python-nit-7am
|
/Operators/arithmetic.py
| 709
| 4.53125
| 5
|
'''--------------------------------------------------------------'''
# 1. Arithmetic Operators:
'''--------------------------------------------------------------'''
"""
1. + = Addition
2. - = Subtraction
3. * = Multiplication
4. / = Division
5. % = Modulus
6. ** = Exponent
7. // = Floor Division
"""
# Example #1: Arithmetic operators in Python
x = 15
y = 4
# Output: x + y = 19
print(x,id(x),type(x))
print("")
print(y,id(y),type(y))
print("")
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
| false
|
c81ca7b213c5b8f442f5a1169be00a72874ecd7a
|
mirajbasit/dice
|
/dice project.py
| 1,152
| 4.125
| 4
|
import random
# do this cuz u have to
def main():
# .lower makes everything inputted lowercase
roll_dice = input("Would you like to roll a dice, yes or no? ").lower()
# add the name of what is being defined each time
if roll_dice == "no" or roll_dice == "n":
print("Ok, see you later ")
elif roll_dice == "yes" or roll_dice == "y":
yeppers = True
#you do not have to put the == true, still put the colon cuz loop
while yeppers == True:
outcome = random.randint(1,6)
print(f"The result is {outcome}")
re_roll = input("Will you roll again? ").lower()
if re_roll == "no" or re_roll == "n":
print("Ok, thanks for playing ")
yeppers = False
elif re_roll == "yes" or re_roll == "y":
yeppers = True
else:
print("Please enter yes or no! ")
#place for each condition
yeppers = False
else:
print("Please try again ")
# do this cuz u have to
if __name__ == "__main__":
main()
| true
|
53d5d64be2ba5861b854bd279f366e54f681235e
|
OscaRoa/intro-python
|
/mi_primer_script.py
| 749
| 4.125
| 4
|
# Primera sección de la clase
# Intro a scripts
"""
Primera sección de la clase
Intro a scripts
"""
# Segunda sección
# Estructuras de control
if 3 > 5 and 3 > 2:
print("Tres es mayor que cinco y que dos")
# edad = 18
# if edad > 18:
# print("Loteria!")
# elif edad == 18:
# print("Apenitas loteria!")
# else:
# print("No loteria :(")
# Tercera seccion
# Funciones
def saludo(nombre):
print("Hola", nombre)
def gana_loteria(edad):
"""
Funcion que checa si la edad de la persona
es valida para ganar la loteria
"""
if edad > 18:
print("Loteria!")
elif edad == 18:
print("Apenitas loteria")
else:
print("No loteria :(")
gana_loteria(18)
gana_loteria(29)
gana_loteria(3)
| false
|
f58b89d169650839c43e0b716b877f6661245f48
|
vnBB/python_basic_par1_exersises
|
/exercise_5.py
| 283
| 4.375
| 4
|
# Write a Python program which accepts the user's first and last name and print them in
# reverse order with a space between them.
firstname = str(input("Enter your first name: "))
lastname = str(input("Enter your last name: "))
print("Your name is: " + lastname + " " + firstname)
| true
|
4f1db5440a48a15f126f4f97439ef197c0c380ab
|
mynameischokan/python
|
/Strings and Text/1_4.py
| 1,915
| 4.375
| 4
|
"""
************************************************************
**** 1.4. Matching and Searching for Text Patterns
************************************************************
#########
# Problem
#########
# We want to match or search text for a specific pattern.
#########
# Solution
#########
# If the text you’re trying to match is a simple literal,
# we can often just use the basic string methods,
# such as `str.find()`, `str.endswith()`, `str.startswith()`.
# For more complicated matching, use regular expressions and the `re` module.
"""
import re
text = 'yeah, but no, but yeah, but no, but yeah'
# TODO
# Search for the location of the first occurrence of word `no` in `text` above
# INFO
# \d+ means match one or more digits
text1 = '11/27/2012'
text2 = 'Nov 27, 2012'
# TODO
# Write an `if/else` clause that determines `true/false` of `text1`
# and `text2` match using `re`
# TODO
# Precompile the regular expression pattern into a pattern object first
# DO the previous `TODO` with compiled version
text3 = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
# TODO
# `match` searches only starts with occurrence in the string
# but you need to FIND ALL matches in text, find them
# INFO
# When defining regular expressions, it is common to introduce `capture groups`
# by enclosing parts of the pattern in parentheses.
# TODO
# Compile `\d+/\d+/\d+` pattern with capture groups
# Print out `groups`(from 0, 3)
# Extract them to `month, day, year`
# Find all matches from `text3` using pattern with compiled groups
# Loop over them and print items in format: `month-day-year`
# TODO
# Loop over matches found using `findall`,
# but this time iteratively using `finditer()`
# INFO
# If you want an exact match,
# make sure the pattern includes the end-marker `$`
text4 = '12/23/2020awdaw'
# TODO
# Try to find exact match of date in `text4`
if __name__ == '__main__':
pass
| true
|
2005dfcd3969edb4c38aba4b66cbb9a5eaa2e0f2
|
mynameischokan/python
|
/Data Structures and Algorithms/1_3.py
| 1,459
| 4.15625
| 4
|
'''
*************************************************
**** Keeping the Last N Items
*************************************************
#########
# Problem
#########
# You want to keep a limited history of the last few items seen during iteration
# or during some other kind of processing.
#########
# Solution
#########
# Keeping a limited history is a perfect use for a `collections.deque`
'''
# For example, the following code performs a simple text match on a sequence of lines # noqa
# and yields the matching line along with the previous N lines of context when found: # noqa
from collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
# TODO
# Open a file `file_1_3.txt`.
# Loop over each line
# print current line and prev lines
# When writing code to search for items,
# it is common to use a generator function involving `yield`.
# This decouples the process of searching from the code that uses the results
q = deque()
# TODO
# Add item to `q`
# Add item to the begginning of `q`
# Remove item to `q`
# Remove item to the begginning of `q`
# Adding or popping items from either end of a queue has O(1) complexity.
# This is unlike a list where inserting or removing items from the front of the list is O(N). # noqa
if __name__ == '__main__':
pass
| true
|
383dbeb58575c030f659e21cfe9db4de0f3b4043
|
mynameischokan/python
|
/Files and I:O/1_3.py
| 917
| 4.34375
| 4
|
"""
*************************************************************
**** 5.3. Printing with a Different Separator or Line Ending
*************************************************************
#########
# Problem
#########
- You want to output data using print(),
but you also want to change the separator character or line ending.
#########
# Solution
#########
- Use the `sep` and `end` keyword arguments to print(),
to change the output as you wish.
# TODO:
- Print it by separating comma: 'ACME', 50, 91.5
- " " and by adding `!!\n` at the end.
- Print nums in range(5) one by one and in one line.
- Try to print `join` of `row` below and face an error.
- Try to print `row` below by using `join` and separator comma(,)
- Now print `row` using `sep` key of `print`.
"""
row = ('ACME', 50, 91.5)
if __name__ == '__main__':
pass
| true
|
6dfbf466e6a2697a3c650dd7963e8b446c3ebbdd
|
paulprigoda/blackjackpython
|
/button.py
| 2,305
| 4.25
| 4
|
# button.py
# for lab 8 on writing classes
from graphics import *
from random import randrange
class Button:
"""A button is a labeled rectangle in a window.
It is enabled or disabled with the activate()
and deactivate() methods. The clicked(pt) method
returns True if and only if the button is enabled and pt is inside it."""
def __init__(self, win, center, width, height, label):
""" Creates a rectangular button, eg:
qb = Button(myWin, centerPoint, width, height, 'Quit') """
w,h = width/2.0, height/2.0 #w and h are the width and the height
x,y = center.getX(), center.getY() #x and y are the coordinates
self.xmax, self.xmin = x+w, x-w #creates top left point of rect
self.ymax, self.ymin = y+h, y-h #creates top right point of rect
p1 = Point(self.xmin, self.ymin)#stores first point
p2 = Point(self.xmax, self.ymax) #stores second point
self.rect = Rectangle(p1,p2) #creates rect
self.rect.setFill('lightgray') #color of rect
self.rect.draw(win) #draws rect
self.label = Text(center, label) #puts text in button center
self.label.draw(win) #draws text
self.activate() #this line was not there in class today
def getLabel(self):
"""Returns the label string of this button."""
return self.label.getText()
def activate(self):
"""Sets this button to 'active'."""
self.label.setFill('black') #color the text "black"
self.rect.setWidth(2) #set the outline to look bolder
self.active = True #set the boolean variable that tracks "active"-ness to True
def deactivate(self):
"""Sets this button to 'inactive'."""
##color the text "darkgray"
self.label.setFill("darkgray")
##set the outline to look finer/thinner
self.rect.setWidth(1)
##set the boolean variable that tracks "active"-ness to False
self.active = False
def isClicked(self,p):
"""Returns true if button active and Point p is inside"""
x,y = p.getX(),p.getY()
if self.xmin < x and x < self.xmax and self.ymin < y and y < self.ymax and self.active == True:
return True
return False
if __name__ == "__main__":
main()
| true
|
bf694c58e1e2f543f3c84c41e32faa3301654c6e
|
akshat-52/FallSem2
|
/act1.19/1e.py
| 266
| 4.34375
| 4
|
country_list=["India","Austria","Canada","Italy","Japan","France","Germany","Switerland","Sweden","Denmark"]
print(country_list)
if "India" in country_list:
print("Yes, India is present in the list.")
else:
print("No, India is not present in the list.")
| true
|
f04933dd4fa2167d54d9be84cf03fa7f9916664c
|
akshat-52/FallSem2
|
/act1.25/3.py
| 730
| 4.125
| 4
|
def addition(a,b):
n=a+b
print("Sum : ",n)
def subtraction(a,b):
n=a-b
print("Diffrence : ",n)
def multiplication(a,b):
n=a*b
print("Product : ",n)
def division(a,b):
n=a/b
print("Quotient : ",n)
num1=int(input("Enter the first number : "))
num2=int(input("Enter the second number : "))
print("""
Choice 1 - SUM
Choice 2 - DIFFERENCE
Choice 3 - PRODUCT
Choice 4 - QUOTIENT
""")
choice=int(input("Enter the number of your choice : "))
if choice==1:
addition(num1,num2)
elif choice==2:
subtraction(num1,num2)
elif choice==3:
multiplication(num1,num2)
elif choice==4:
division(num1,num2)
else:
print("Invalid Choice !!! Please choose 1/2/3/4 only .")
| true
|
bda09e5ff5b572b11fb889b929daddb9f4e53bb9
|
rhps/py-learn
|
/Tut1-Intro-HelloWorld-BasicIO/py-greeting.py
| 318
| 4.25
| 4
|
#Let's import the sys module which will provide us with a way to read lines from STDIN
import sys
print "Hi, what's your name?" #Ask the user what's his/her name
#name = sys.stdin.readline() #Read a line from STDIN
name = raw_input()
print "Hello " + name.rstrip() #Strip the new line off from the end of the string
| true
|
795d075e858e3f3913f9fc1fd0cb424dcaafe504
|
rhps/py-learn
|
/Tut4-DataStructStrListTuples/py-lists.py
| 1,813
| 4.625
| 5
|
# Demonstrating Lists in Python
# Lists are dynamically sized arrays. They are fairly general and can contain any linear sequence of Python objects: functions, strings, integers, floats, objects and also, other lists. It is not necessary that all objects in the list need to be of the same type. You can have a list with strings, numbers , objects; all mixed up.
# Constructing a basic list
# This list purely has integers
test_list = [1,2,3,4,5,6,7,8,9]
print test_list
# Constructing a mixed list
# This list has integers as well as strings
test_mixed_list = [1,2,3,"test list"]
print "Displaying test_list"
print test_list
print "Displaying test_mixed_list"
print test_mixed_list
# Appending to a list
test_list.append(10)
# Now the test_list = [1,2,3,4,5,6,7,8,9,10]
print "After appending 10 to the test_list"
print test_list
test_list = test_list + [13,12,11]
# Now the test_list = [1,2,3,4,5,6,7,8,9,10,13,12,11]
print "After adding [13,12,11] to the test list"
print test_list
# Delete from the test_list
del test_list[2]
print "Deleted element at index 2 in the test_list"
# new test list is [1,2,4,5,6,7,8,9,10,13,12,11]
print test_list
# Sorting a list
print "Sorting the test list"
test_list.sort()
print test_list
# This will display [1,2,4,5,6,7,8,9,10,11,12,13]
# Reverse a list
print "Reversting the test_list"
test_list.reverse()
print test_list
# This will display [13,12,11,10,9,8,7,6,5,4,2,1]
# Now we will demonstrate "Multiplying" a list with a constant. I.e, the
# list will be repeatedly concatenated to itself
list_to_multiply = ['a','b','c']
print "list to multiply"
print list_to_multiply
print "After multiplying this list by 3, i.e. repeating it 3 times:"
product_list = 3 * list_to_multiply
print product_list
# This will display ['a','b','c','a','b','c','a','b','c']
| true
|
dbd856336c8f7e2e724e9b50c81494b3ca3a7771
|
tmjnow/Go-Python-data-structures-and-sorting
|
/Datastructures/queue/queue.py
| 1,054
| 4.28125
| 4
|
'''
Implementation of queue using list in python.
Operations are O(1)
`python queue.py`
'''
class Queue():
def __init__(self):
self.items = []
def is_empty(self):
return self._is_empty()
def enqueue(self, item):
self._enqueue(item)
def dequeue(self):
return self._dequeue()
def size(self):
return self._size()
def print_queue(self):
print self.items
# private methods.
def _is_empty(self):
return self.items == []
def _enqueue(self, item):
self.items.insert(0, item)
def _dequeue(self):
if not self.is_empty():
self.items = self.items[1:]
return self.items
raise Exception('queue is already empty')
def _size(self):
return len(self.items)
if __name__ == "__main__":
queue = Queue()
queue.enqueue(2)
print(queue.size())
queue.enqueue(4)
queue.enqueue(5)
queue.enqueue(9)
queue.print_queue()
queue.dequeue()
queue.dequeue()
queue.print_queue()
| false
|
ec823610ba821cd62f067b8540e733f46946de34
|
thaycacac/kids-dev
|
/PYTHON/lv2/lesson1/exercise2.py
| 463
| 4.15625
| 4
|
import random
number_random = random.randrange(1, 100)
numer_guess = 0
count = 0
print('Input you guess: ')
while number_random != numer_guess:
numer_guess = (int)(input())
if number_random > numer_guess:
print('The number you guess is smaller')
count += 1
elif number_random < numer_guess:
print('The number you guess is bigger')
count += 1
else:
print('Congratulations you\'ve guessed correctly')
print('You guessed wrong:', count)
| true
|
011d9ac704c3705fd7b6025c3e38d440a30bf59a
|
Saskia-vB/Eng_57_2
|
/Python/exercises/108_bizzuuu_exercise.py
| 1,540
| 4.15625
| 4
|
# Write a bizz and zzuu game ##project
user_number= (int(input("please enter a number")))
for i in range(1, user_number + 1):
print(i)
while True:
user_number
play = input('Do you want to play BIZZZUUUU?\n')
if play == 'yes':
user_input = int(input('what number would you like to play to?\n'))
for num in range(1, user_input + 1):
if num % 15 == 0:
print('bizzzuu')
elif num % 3 ==0:
print('bizzz')
elif num % 5 ==0:
print("zzuuu")
else:
print(num)
break
# as a user I should be able prompted for a number, as the program will print all the number up to and inclusing said number while following the constraints / specs. (bizz and buzz for multiples or 3 and 5)
number= int(input("Choose a number:"))
if (number % 5) == 0:
print("buzz")
elif (number % 3)== 0:
print("bizz")
else:
print("You lost")
# As a user I should be able to keep giving the program different numbers and it will calculate appropriately until you use the key word: 'penpinapplespen'
# write a program that take a number
# prints back each individual number, but
# if it is a multiple of 3 it returns bizz
# if a multiple of 5 it return zzuu
# if a multiple of 3 and 5 it return bizzzzuu
# EXTRA:
# Make it functional
# make it so I can it so it can work with 4 and 9 insted of 3 and 5.
# make it so it can work with any number!
# print ("I'm going to print the numbers!")
# i = int(input("Enter the number: "))
# func(i)
| true
|
b572d0bda55a6a4b9a3bbf26b609a0edc026c0a3
|
Saskia-vB/Eng_57_2
|
/Python/dictionaries.py
| 1,648
| 4.65625
| 5
|
# Dictionaries
# Definition and syntax
# a dictionary is a data structure, like a list, but organized with keys and not index.
# They are organized with 'key' : 'value' pairs
# for example 'zebra' : 'an African wild animal that looks like a horse but has black and white or brown and white lines on its body'
# This means you can search data using keys, rather than index.
#syntax
# {}
# my_dictionary={'key':'value'}
# print(type(my_dictionary))
# i.e.: {'zebra': 'A horse with stripes'}
# Defining a dictionary
# allows you to store more data, the value can be anything, it can be another data structure.
# i.e. for stingy landlords list, we need more info regarding the houses they have and contact details.
stingy_landlord1 = {
'name':'Alfredo',
'phone_number':'0783271192',
'property':'Birmingham, near Star City'
}
# printing dictionary
print(stingy_landlord1)
print(type(stingy_landlord1))
# getting one value out
print(stingy_landlord1['name'])
print(stingy_landlord1['phone_number'])
# re-assigning one value
stingy_landlord1['name'] = "Alfredo de Medo"
print(stingy_landlord1)
# new key value pair
stingy_landlord1['address']="house 2, Unit 29 Watson Rd"
print(stingy_landlord1)
stingy_landlord1['number_of_victimes']=0
print(stingy_landlord1)
stingy_landlord1['number_of_victimes']+=1
print(stingy_landlord1)
stingy_landlord1['number_of_victimes']+=1
print(stingy_landlord1)
# get all the values out
# special dictionary methods
# (methods are functions that belong to a specific data type)
# .keys()
print(stingy_landlord1.keys())
# .values()
print(stingy_landlord1.values())
# .items()
print(stingy_landlord1.items())
| true
|
793e45264df9239562ea359d2b1f704643e7c9e2
|
alveraboquet/Class_Runtime_Terrors
|
/Students/andrew/lab1/lab1_converter.py
| 1,903
| 4.4375
| 4
|
def feet_to_meters():
measurment = { 'ft':0.03048}
distance = input("Enter a distance in feet: ")
meters = float(distance) * measurment['ft']
print(f'{distance} ft is {meters}m ')
def unit_to_meters():
measurment = {'ft':0.03048, 'km':1000, 'mi':1609.34}
distance = input("Enter a distance in meters: ")
unit = input("Select a distance unit: ft-feet, km-kilometer or mi-mile.: \n ")
meters = float(distance) * measurment[unit]
print(f'{distance} {unit} is {meters}m ')
def unit_to_metersV3():
measurment = {'ft':0.03048, 'km':1000, 'mi':1609.34}
measurment['yd'] = 0.9144
measurment['in'] = 0.0254
distance = input("Enter a distance in meters: ")
unit = input("Select a distance unit: ft-feet, km-kilometer yd-yard, in-inch or mi-mile.: \n ")
meters = float(distance) * measurment[unit]
print(f'{distance} {unit} is {meters}m ')
def advanced_unit_conversion():
measurment = {'ft':0.3048, 'km':1000, 'mi':1609.34, 'm':1}
distance = input("Enter a distance: ")
input_unit = input("Choose an imput unit; ft-feet, km-kilometer m-meter or mi-mile.: \n ")
output_unit = input("Choose an output unit; ft-feet, km-kilometer m-meter or mi-mile.: \n ")
meters = float(distance) * measurment[input_unit]
conversion = meters / measurment[output_unit]
print(f"{distance} {input_unit} is {conversion} {output_unit}")
def unit_conversion_selector():
sel = input("Please select a conversion tool, type v1 v2 v3 or v4: \n v1-version 1: \n v2-version 2: \n v3-version 3: \n v4-advanved \n")
while sel != "n":
converters = {'v1':feet_to_meters, 'v2':unit_to_meters, 'v3':unit_to_metersV3, 'v4':advanced_unit_conversion}
converters[sel]()
sel = input("Please select a conversion tool: \n v1-version 1: \n v2-version 2: \n v3-version 3: \n v4-advanved \n or n to quit ")
if sel == "n":
print("goodbye!")
break
unit_conversion_selector()
| false
|
d0625cb91921c28816cd5ab06a100cb3ae9e4bbb
|
alveraboquet/Class_Runtime_Terrors
|
/Students/cleon/Lab_6_password_generator_v2/password_generator_v2.py
| 1,206
| 4.1875
| 4
|
# Cleon
import string
import random
speChar = string.hexdigits + string.punctuation # special characters
print(" Welcome to my first password generator \n") # Welcome message
lower_case_length = int(input("Please use the number pad to enter how many lowercase letters : "))
upper_case_length = int(input("How many uppercase letters : "))
number_length = int(input("How many numbers : "))
special_length = int(input("How many special characters : "))
gP = ""
while True:
while lower_case_length > 0:
gP += random.choice(string.ascii_lowercase)
lower_case_length = lower_case_length - 1
while upper_case_length > 0:
gP += random.choice(string.ascii_uppercase)
upper_case_length = upper_case_length - 1
while number_length > 0:
gP += random.choice(string.digits)
number_length = number_length - 1
while special_length > 0:
gP += random.choice(speChar)
special_length = special_length - 1
break
gP = (random.sample(gP, len(gP))) # Can't randomly sort string elements.Use this function it returns as a list
gP= ''.join(gP) # Then you must use join function to convert back to string
print(gP)
| true
|
5a89444d7b72175ba533b87139a5a611a11a89a7
|
alveraboquet/Class_Runtime_Terrors
|
/Students/Jordyn/Python/Fundamentals1/problem1.py
| 224
| 4.3125
| 4
|
def is_even(value):
value = abs(value % 2)
if value > 0:
return 'Is odd'
elif value == 0:
return 'Is even'
value = int(input('Input a whole number: '))
response = is_even(value)
print(response)
| true
|
59bc2af7aeef6ce948184bb1291f18f81026ed9c
|
alveraboquet/Class_Runtime_Terrors
|
/Students/Jordyn/Python/Fundamentals2/problem3.py
| 296
| 4.1875
| 4
|
def latest_letter(word):
length = len(word)
length -= 1
word_list = []
for char in word:
word_list += [char.lower()]
return word_list[length]
word = input("Please input a sentence: ")
letter = latest_letter(word)
print(f"The last letter in the sentence is: {letter}")
| true
|
627275ef1f88b1c633f0114347570dc62a16f175
|
alveraboquet/Class_Runtime_Terrors
|
/Students/cadillacjack/Python/lab15/lab15.py
| 1,306
| 4.1875
| 4
|
from string import punctuation as punct
# Import ascii punctuation as "punct".
# "punct" is a list of strings
with open ('monte_cristo.txt', 'r') as document:
document_content = document.read(500)
doc_cont = document_content.replace('\n',' ')
# Open designated file as "file". "file" is a string
for punc in punct:
doc_cont = doc_cont.replace(punc, "")
# Remove all punctuation from string
doc_cont = doc_cont.lower()
# Lowercase all words
doc_cont = doc_cont.split(' ')
# Convert string to list of strings
word_count = {} # Create empty dictionary
for word in doc_cont: # Scan "doc_cont", check every word.
if word not in word_count: # If scanned word not in "word_count"...
word_count[word] = 1 # Add word to "word_count" as a key with the value 1
elif word in word_count: # If scanned word is in "word_count"...
word_count[word] +=1 # Increase value of key "word" by 1
words = list(word_count.items())
# Convert dict "word_count" to a list of tuples.
# Save list as "words"
# Tuples are key, value pairs
words.sort(key = lambda tup: tup[1],reverse = True)
# Sort list "words" using the value of each tuple
# Reverse the order of list fro highest value to lowest
print(f"The top ten words are ; {words[:10]})")
# print the first 10 words of list "words"
| true
|
0c31b359da41c800121e7560fceac30836e2daec
|
alveraboquet/Class_Runtime_Terrors
|
/Students/tom/Lab 11/Lab 11, make change, ver 1.py
| 1,903
| 4.15625
| 4
|
# program to make change
# 10/16/2020
# Tom Schroeder
play_again = True
while play_again:
money_amount = input ('Enter the amount amount of money to convert to change: \n')
float_convert = False
while float_convert == False:
try:
money_amount = float(money_amount)
float_convert = True
except ValueError:
money_amount = input ('Your entry is not a valid entry. Enter the amount amount of money to convert to change: \n')
quarters = money_amount // .25
# print (f'{quarters} quartes')
money_amount_less_quarters = round(money_amount % .25, 2)
# print (f'{money_amount_less_quarters} money_amount_less_quarters')
dimes = money_amount_less_quarters // .1
# print (f'{dimes} dimes')
money_amount_less_dimes = round(money_amount_less_quarters % .1, 2)
# print (f'{money_amount_less_dimes} money_amount_less_dimes')
nickles = money_amount_less_dimes // .05
# print (f'{nickles} nickles')
money_amount_less_nickles = round(money_amount_less_dimes % .05, 2)
# print (f'{money_amount_less_nickles} money_amount_less_nickles')
pennies = money_amount_less_nickles / .01
quarters = int(quarters)
dimes = int(dimes)
nickles = int(nickles)
pennies = int(pennies)
print(f'${money_amount} is made up of {quarters} quarters, {dimes} dimes, {nickles} nickles, {pennies} pennies.')
play_again_input = input ('Would you like to do another one? "Y" or "N"').capitalize()
while play_again_input != 'Y' and play_again_input != 'N':
play_again_input = input ('You made an incorrect entry. Would you like to do another one? "Y" or "N"').capitalize()
if play_again_input == 'Y':
play_again = True
elif play_again_input == 'N':
play_again = False
| true
|
8a8ce83b77498d38089aea25b1edd589330d8f0b
|
alveraboquet/Class_Runtime_Terrors
|
/Students/cadillacjack/Python/oop/volume.py
| 1,152
| 4.25
| 4
|
class Volume:
def __init__(self, length, width, height):
self.length = int(length)
self.width = int(width)
self.height = int(height)
def perimeter(self):
per = 2 * (self.length * self.width)
return per
def area(self):
area = self.length * self.width
return area
def vol(self):
volu = self.length * self.width * self.height
return volu
class All_measurements(Volume):
def __init__(self, length, width, height):
super().__init__(length, width, height)
self.area = self.area()
self.per = self.perimeter()
self.volu = self.vol()
def print_all(self):
print(f'''
The Area is : {self.area}
The Perimeter is : {self.per}
The Volume is : {self.volu}''')
length = input("What is the length : ")
width = input("What is the width : ")
height = input("What is the height : ")
what_should_never = All_measurements(length, width, height)
what_is = Volume(length, width, height)
print(Volume.area(what_is))
print(Volume.perimeter(what_is))
print(Volume.vol(what_is))
print(All_measurements.print_all(what_should_never))
| false
|
bd89d612e7e9d15153ad804f85dfe64245c365a6
|
DanielY1783/accre_python_class
|
/bin/06/line_counter.py
| 1,440
| 4.71875
| 5
|
# Author: Daniel Yan
# Email: daniel.yan@vanderbilt.edu
# Date: 2018-07-25
#
# Description: My solution to the below exercise posed by Eric Appelt
#
# Exercise: Write a command line utility in python that counts the number
# of lines in a file and prints them. to standard output.
#
# The utility should take the name of a file as an argument. To do this use
# import sys and then sys.argv[1] will be the first argument given.
#
# By trial and error, determine the type of exception raised when the user
# fails to run the program with an argument, the file specified does not
# exist, or the user does not have permission to read the file specified.
#
# Using try/except blocks, handle each of these exception types separately
# and send an appropriate message to the user in each case.
import sys
if __name__ == '__main__':
try:
file_name = sys.argv[1]
count = 0
with open(file_name, "r") as read_file:
for _ in read_file:
count += 1
print("{} has {} line(s)".format(file_name, count))
except IndexError:
print("No file specified. Specify file in first command line argument")
except FileNotFoundError:
print("File does not exist. Make sure that directory and extension of "
"file are included.")
except PermissionError:
print("You do not have permission to read the file. Please obtain "
"read permission to file and try again.")
| true
|
b4d3854aea11e1cac0cece0b4dbd708b6d95d184
|
DanielY1783/accre_python_class
|
/bin/01/fib.py
| 1,338
| 4.53125
| 5
|
# Author: Daniel Yan
# Email: daniel.yan@vanderbilt.edu
# Date: 2018-06-07
#
# Description: My solution to the below exercise posed by Eric Appelt
#
# Exercise: Write a program to take an integer that the user inputs and print
# the corresponding Fibonacci Number. The Fibonacci sequence begins 1, 1, 2, 3,
# 5, 8, 13, so if the user inputs 7, the user should see the 7th Fibonacci
# number printed, which is 13. If the user inputs a negative number the
# program should print an error message.
if __name__ == '__main__':
# Get user input
user_input = input(
"Enter in a positive integer 'n' such that the 'nth' Fibonacci Number "
"will be printed: ")
fib_num = int(user_input)
# Print error if number is not positive
if fib_num < 0:
print("Value is not positive. Exiting.")
exit(-1)
elif fib_num == 0:
print("The Fibonacci Number in the 0 position is: 0")
else:
# Set the two previous Fibonacci Numbers.
f1 = 0
f2 = 0
# Set the current Fibonacci Number to print.
cur = 1
# Get the user choice.
while fib_num > 1:
f1 = f2
f2 = cur
cur = f1 + f2
fib_num = fib_num - 1
print(
"The Fibonacci Number in the '" + user_input + "' position is: "
+ str(cur))
| true
|
1db59dcb55f8b898d4d57ad244edc677b590941b
|
rshin808/quickPython
|
/Classes/EXoverriding.py
| 1,387
| 4.34375
| 4
|
class Animal:
def __init__(self, name):
self._name = str(name)
def __str__(self):
return "I am an Animal with name " + self._name
def get_name(self):
return self._name
def make_sound(self):
raise NotImplementedError("Subclass must implement abstract method")
def do_action(self):
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def __init__(self, name = "", sound = "Meow~", action = "Scratch"):
Animal.__init__(self, name)
self._sound = str(sound)
self._action = str(action)
def __str__(self):
return self._sound + " I am a Cat with name " + self._name + ", and I like to " + self._action
def make_sound(self):
return self._sound
def do_action(self):
return self._action
class Dog(Animal):
def __init__(self, name = "", sound = "Woof!", action = "Fetch"):
Animal.__init__(self, name)
self._sound = str(sound)
self._action = str(action)
def __str__(self):
return self._sound + " I am a Dog with name " + self._name+ ", and I like to " + self._action
def make_sound(self):
return self._sound
def do_action(self):
return self._action
cat = Cat("Kitty")
dog = Dog("Doggy")
animals = [cat, dog]
for animal in animals:
print str(animal)
| false
|
64739565dd86b5b36fdbe203c3f6beeb2c78b847
|
anthony-marino/ramapo
|
/source/courses/cmps130/exercises/pe01/pe1.py
| 651
| 4.5625
| 5
|
#############################################
# Programming Excercise 1
#
# Write a program that asks the user
# for 3 integers and prints the
# largest odd number. If none of the
# three numbers were odd, print a message
# indicating so.
#############################################
x = int(input("Enter x: "))
y = int(input("Enter y: "))
z = int(input("Enter z: "))
max_odd = float("-inf")
if x % 2 != 0 and x > max_odd:
max_odd = x
if y % 2 != 0 and y > max_odd:
max_odd = y
if z % 2 != 0 and z > max_odd:
max_odd = z
if max_odd != float("-inf") :
print("The largest odd number was", max_odd)
else:
print("There were no odd numbers!")
| true
|
9dbffbb4195dfe02d90e4f2bd2813cc2a7d993a6
|
anthony-marino/ramapo
|
/source/courses/cmps130/exercises/pe10/pe10-enumeration.py
| 1,047
| 4.40625
| 4
|
##############################################################################
# Programming Excercise 10
#
# Find the square root of X using exhaustive enumeration
#############################################################################
# epsilon represents our error tolerance. We'll
# accept any answer Y where Y squared is within epsilon
# of X
epsilon = 0.001
# step is based on epsilon for convenience, but doesn't
# have to be. Its just the increment that we'll check in.
# It should be rather small relative to epsilon
step = epsilon ** 2
# we'll also keep track of how many turns around the loop
# this takes, so we can compare against other techniques.
num_iterations = 0
x = float(input("Please enter a real number: "))
ans = 0.0
while abs(ans**2 - x) > epsilon:
ans += step
num_iterations += 1
print ("Completed in", num_iterations, " iterations")
if abs(ans**2 - x ) > epsilon:
print("Exhaustive enumeration could not determine the square root of", x)
else:
print("The square root of", x, "is", ans, "!")
| true
|
f279a594a986076b96993995f5072bcc383244d6
|
singh-vijay/PythonPrograms
|
/PyLevel3/Py19_Sets.py
| 288
| 4.15625
| 4
|
'''
Sets is collection of items with no duplicates
'''
groceries = {'serial', 'milk', 'beans', 'butter', 'bananas', 'milk'}
''' Ignore items which are given twice'''
print(groceries)
if 'pizza' in groceries:
print("you already have pizza!")
else:
print("You need to add pizza!")
| true
|
96ee1777becc904a39b140c901522881b2942cee
|
WavingColor/LeetCode
|
/LeetCode:judge_route.py
| 1,034
| 4.125
| 4
|
# Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
# The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
# Example 1:
# Input: "UD"
# Output: true
# Example 2:
# Input: "LL"
# Output: false
class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
rs, ls, us, ds = [], [], [], []
for string in moves:
if string == 'D':
ds.append(string)
elif string == 'R':
rs.append(string)
elif string == 'U':
us.append(string)
elif string == 'L':
ls.append(string)
return not bool((len(rs)+len(us) - len(ls) - len(ds)))
| true
|
f084aa9b24edc8fe1b0d87cd20beee21288946ad
|
mattandersoninf/AlgorithmDesignStructures
|
/Points/Python/Point.py
| 1,083
| 4.15625
| 4
|
# python impolementation of a point
# a point in 2-D Euclidean space which should contain the following
# - x-coordinate
# - y-coordinate
# - moveTo(new_x,new_y): changes the coordinates to be equal to the new coordinates
# - distanceTo(x_val,y_val): this function returns the distance from the current point to some other point as a float
class Point:
def __init__(self,x,y):
self._x = x
self._y = y
@property
def x(self):
print("get x-coordinate")
return self._x
@x.setter
def x(self,val):
print("set x-coordinate")
self._x = val
@property
def y(self):
print("get y-coordinate")
return self._x
@y.setter
def y(self,val):
print("set y-coordinate")
self._x = val
@property
def coordinates(self):
print("get coordinates")
return (self._x,self._y)
def moveTo(self,new_x,new_y):
self._x = new_x
self._y = new_y
def distanceTo(self,x_val,y_val):
return ((self._x-x_val)**2+(self._y-y_val)**2)**.5
| true
|
91eb26b11d3a5839b3906211e3e10a636ac0277b
|
Exia01/Python
|
/Self-Learning/testing_and_TDD/basics/assertions.py
| 649
| 4.28125
| 4
|
# Example1
def add_positive_numbers(x, y):
# first assert, then expression, message is optional
assert x > 0 and y > 0, "Both numbers must be positive! -> {}, {}".format(
x, y)
return x + y
# test cases
print(add_positive_numbers(1, 1)) # 2
add_positive_numbers(1, -1) # AssertionError: Both numbers must be positive!
# Example 2
def eat_junk(food):
assert food in [ # truth or false
"pizza",
"ice cream",
"candy",
"fried butter"
], "food must be a junk food!"
return f"NOM NOM NOM I am eating {food}"
#test case
food = input("ENTER A FOOD PLEASE: ")
print(eat_junk(food))
| true
|
dbdf00041078931bec33a443fbd330194cf60ec0
|
Exia01/Python
|
/Self-Learning/lists/slices.py
| 361
| 4.28125
| 4
|
items = [1, 2, 3, 4, 5, 6, ['Hello', 'Testing']]
print(items[1:])
print(items[-1:])
print(items[::-1])# reverses the list
print(items[-3:])
stuff = items[:] # will copy the array
print(stuff is items) # share the same memory space?
print(stuff[0:7:2])
print(stuff[7:0:-2])
stuff[:3] = ["A", "B", "C"]
print(stuff)
x =[ "Hello World!", "Testing HEre"]
| true
|
64878d4e5e228f2c45c578ea44614fcb5dc67e1b
|
Exia01/Python
|
/Self-Learning/built-in_functions/abs_sum_round.py
| 712
| 4.125
| 4
|
#abs --> Returns the absolute value of a number. The argument may be an integer or a floating point number
#Example
print(abs(5)) #5
print(abs(3.5555555))
print(abs(-1324934820.39248))
import math
print(math.fabs(-3923)) #treats everything as a float
#Sum
#takes an iterable and an optional start
# returns the sum of start and the items of an iterable from left to right and returns the total.
# starts default to 0
print(sum([1,2,3]))
print(sum([1, 2, 3,], 10)) # will start at 10 and add
#round
#Return number rounded to ndigits precision after the decimal point.
#If ndigits is omitted or is None, it returns the nearest integer to input
print(round(10.2)) #10
print(round(1.24323492834, 2))#1.24
| true
|
278dd78ed805a27e0a702bdd8c9064d3976a2f78
|
Exia01/Python
|
/Python OOP/Vehicles.py
| 2,884
| 4.21875
| 4
|
# file vehicles.py
class Vehicle:
def __init__(self, wheels, capacity, make, model):
self.wheels = wheels
self.capacity = capacity
self.make = make
self.model = model
self.mileage = 0
def drive(self, miles):
self.mileage += miles
return self
def reverse(self, miles):
self.mileage -= miles
return self
# file vehicles.py
class Vehicle:
def __init__(self, wheels, capacity, make, model):
self.wheels = wheels
self.capacity = capacity
self.make = make
self.model = model
self.mileage = 0
def drive(self, miles):
self.mileage += miles
return self
def reverse(self, miles):
self.mileage -= miles
return self
class Bike(Vehicle):
def vehicle_type(self):
return "Bike"
class Car(Vehicle):
def set_wheels(self):
self.wheels = 4
return self
class Airplane(Vehicle):
def fly(self, miles):
self.mileage += miles
return self
v = Vehicle(4, 8, "dodge", "minivan")
print(v.make)
b = Bike(2, 1, "Schwinn", "Paramount")
print(b.vehicle_type())
c = Car(8, 5, "Toyota", "Matrix")
c.set_wheels()
print(c.wheels)
a = Airplane(22, 853, "Airbus", "A380")
a.fly(580)
print(a.mileage)
class Parent:
# parent methods and attributes here
class Child(Parent): # inherits from Parent class so we define Parent as the first parameter
# parent methods and attributes are implicitly inherited
# child methods and attributes
def varargs(arg1, *args):
print("Got " + arg1 + " and " + ", ".join(args))
varargs("one") # output: "Got one and "
varargs("one", "two") # output: "Got one and two"
varargs("one", "two", "three") # output: "Got one and two, three"
class Wizard(Human):
def __init__(self):
super().__init__() # use super to call the Human __init__() method
# every wizard starts off with 10 intelligence, overwriting the 3 from Human
self.intelligence = 10
def heal(self):
self.health += 10 # all wizards also get a heal() method
class Ninja(Human):
def __init__(self):
super().__init__() # use super to call the Human __init__() method
# every Ninja starts off with 10 stealth, overwriting the stealth of 1 from Human
self.stealth = 10
def steal(self):
self.stealth += 5 # all ninjas also get a steal() method
class Samurai(Human):
def __init__(self):
super().__init__() # use super to call the Human __init__() method
# every Samurai starts off with 10 strength, overwriting the 2 from Human
self.strength = 10
def sacrifice(self):
self.health -= 5 # all samurais also get a sacrifice() method
| true
|
65a6a75a451031ae2ea619b3b8b2210a44859ca3
|
Exia01/Python
|
/Self-Learning/Algorithm_challenges/three_odd_numbers.py
| 1,607
| 4.1875
| 4
|
# three_odd_numbers
# Write a function called three_odd_numbers, which accepts a list of numbers and returns True if any three consecutive numbers sum to an odd number.
def three_odd_numbers(nums_list, window_size=3):
n = window_size
results = []
temp_sum = 0
#test this check
if window_size > len(nums_list):
return False
# first sum
for i in range(window_size):
temp_sum += nums_list[i]
#can implement quick short circuit here
results.append(temp_sum % 2 != 0)
for i in range(window_size, len(nums_list)):
temp_sum = temp_sum - nums_list[i - n] + nums_list[i]
results.append(temp_sum % 2 != 0)
return any(results)
##Test Cases
print(three_odd_numbers([1,2])) # True
print(three_odd_numbers([1,2,3,4,5])) # True
print(three_odd_numbers([0,-2,4,1,9,12,4,1,0])) # True
print(three_odd_numbers([5,2,1])) # False
print(three_odd_numbers([1,2,3,3,2])) # False
#Here be dragons
# https://scipher.wordpress.com/2010/12/02/simple-sliding-window-iterator-in-python/
# def maxSubArraySum(arr, n):
# tempSum = 0
# maxSum = 0
# dic = {}
# try:
# n > len(arr)
# except:
# return None
# for num in range(n):
# maxSum += arr[num]
# # print(maxSum)
# tempSum = maxSum
# for i in range(n, len(arr)):
# # print(arr[i-n], arr[i], tempSum)
# tempSum = tempSum - arr[i - n] + arr[i]
# maxSum = max(maxSum, tempSum)
# # if (tempSum > maxSum):
# # maxSum = tempSum
# return maxSum
# print(maxSubArraySum(arr, n))
| true
|
66ebbe4465ff1a433f5918e7b20f019c60b496ae
|
Exia01/Python
|
/Self-Learning/lambdas/basics/basics.py
| 725
| 4.25
| 4
|
# A regular named function
def square(num): return num * num
# An equivalent lambda, saved to a variable but has no name
square2 = lambda num: num * num
# Another lambda --> anonymous function
add = lambda a,b: a + b #automatically returns
#Executing the function
print(square(7))
# Executing the lambdas
print(square2(7))
print(add(3,10))
# Notice that the square function has a name, but the two lambdas do not
print(square.__name__)
print(square2.__name__)
print(add.__name__)
#Adding
add_values = lambda x, y: x + y
#Multiplying
multiply_values = lambda x, y: x * y
#dividing
divide_values = lambda x, y: x / y
#subtract
subtract_values = lambda x, y: x - y
# Cube
cube = lambda a: a ** 3
print(cube(8))
| true
|
40be281781c92fc5417724157b0eebb2aefb8160
|
Exia01/Python
|
/Self-Learning/functions/operations.py
| 1,279
| 4.21875
| 4
|
# addd
def add(a, b):
return a+b
print(add(5, 6))
# divide
def divide(num1, num2): # num1 and num2 are parameters
return num1/num2
print(divide(2, 5)) # 2 and 5 are the arguments
print(divide(5, 2))
# square
def square(num): # takes in an argument
return num * num
print(square(4))
print(square(8))
#return examples
def sum_odd_numbers(numbers):
total = 0
for num in numbers:
if num % 2 != 0:
total += num
return total # Returning too early :(
# OLD-VERSION----OLD-VERSION----OLD-VERSION-----
# NEW AND IMPROVED VERSION :)
def sum_odd_numbers_2(numbers):
total = 0
for num in numbers:
if num % 2 != 0:
total += num
return total
print(sum_odd_numbers_2([1, 2, 3, 4, 5, 6, 7]))
# cleaner code example
def is_odd_number(num):
if num % 2 != 0:
return True
else: # This else is unnecessary
return False
def is_odd_number_2(num):
if num % 2 != 0:
return True
return False # We can just return without the else
print(is_odd_number_2(4))
print(is_odd_number_2(9))
def count_dollar_signs(word):
count = 0
for char in word:
if char == '$':
count += 1
return count
print(count_dollar_signs("$uper $size"))
| true
|
44697f20d48ba5522c2b77358ad1816d6af2bb96
|
Exia01/Python
|
/Self-Learning/built-in_functions/exercises/sum_floats.py
| 611
| 4.3125
| 4
|
#write a function called sum_floats
#This function should accept a variable number of arguments.
#Should return the sum of all the parameters that are floats.
# if the are no floats return 0
def sum_floats(*args):
if (any(type(val) == float for val in args)):
return sum((val for val in args if type(val)==float))
return 0
#Test Cases
print(sum_floats(1.5, 2.4, 'awesome', [], 1))# 3.9
print(sum_floats(1, 2, 3, 4, 5)) # 0
#Explanation:
# First check to see if there are "any" float pass in the args through a loop.
#if there float we loop to find them and only add those, then returning it
| true
|
f8b7cd07614991a3ae5580fd2bd0458c730952ee
|
Exia01/Python
|
/Self-Learning/functions/exercises/multiple_letter_count.py
| 428
| 4.3125
| 4
|
#Function called "multiple_letter_count"
# return dictionary with count of each letter
def multiple_letter_count(word = None):
if not word:
return None
if word:
return {letter: word.count(letter) for letter in word if letter != " "}
#Variables
test_1 = "Hello World!"
test_2 = "Gotta keep Pushing!"
#Test cases
print(multiple_letter_count(test_1))
print(multiple_letter_count(test_2))
| true
|
7ad9a8f7530f0636495f8b65372cccd4fe050c24
|
Exia01/Python
|
/Self-Learning/OOP/part2/exercises/multiple_inheritance.py
| 784
| 4.15625
| 4
|
class Aquatic:
def __init__(self, name):
self.name = name
def swim(self):
return f'{self.name} is swimming'
def greet(self):
return f'I am {self.name} of the sea!'
class Ambulatory:
def __init__(self, name):
self.name = name
def walk(self):
return f'{self.name} is walking'
def greet(self):
return f'I am {self.name} of the land!'
class Penguin(Ambulatory, Aquatic):
def __init__(self, name):
super().__init__(name=name)
jaws = Aquatic("Jaws")
lassie = Ambulatory("Lassie")
Captain_cook = Penguin("Captain Cook")
print(jaws.swim())
print(lassie.walk())
Captain_cook.swim()
Captain_cook.walk()
print(Captain_cook.greet()) # uses greet from land
# we could do both is instance to test
| false
|
bea429f7de9a604e1d92b4506038dd17fef4c7eb
|
shvnks/comp354_calculator
|
/src/InterpreterModule/Tokens.py
| 936
| 4.28125
| 4
|
"""Classes of all possible types that can appear in a mathematical expression."""
from dataclasses import dataclass
from enum import Enum
class TokenType(Enum):
"""Enumeration of all possible Token Types."""
"Since they are constant, and this is an easy way to allow us to know which ones we are manipulating."
NUMBER = 0
PLUS = 1
MINUS = 2
MULTIPLICATION = 3
DIVISION = 4
POWER = 5
FACTORIAL = 6
TRIG = 7
LOGARITHMIC = 8
STANDARDDEVIATION = 9
GAMMA = 10
MAD = 11
PI = 12
E = 13
SQUAREROOT = 14
LEFTP = 15
RIGHTP = 16
LEFTB = 17
RIGHTB = 18
COMMA = 19
@dataclass
class Token:
"""Stores the Type of Token and it value if any."""
type: TokenType
value: any = None
def __repr__(self):
"""Output the Token (Debugging Purposes)."""
return self.type.name + str({f'{self.value}' if self.value is not None else ''})
| true
|
aa7556b840c4efa4983cd344c69008a0f342f528
|
shvnks/comp354_calculator
|
/src/functionsExponentOldAndrei.py
| 2,603
| 4.21875
| 4
|
# make your functions here
def exponent_function(constant, base, power):
total = base
if power % 1 == 0:
if power == 0 or power == -0:
return constant * 1
if power > 0:
counter = power - 1
while counter > 0:
total *= base
counter -= 1
return constant * total
else:
power *= -1
counter = power - 1
while counter > 0:
total *= base
counter -= 1
total = 1 / total
return constant * total
elif power % 1 != 0:
if power == 0 or power == -0:
return constant * 1
if power > 0:
sqrt = base ** power
return constant * sqrt
else:
power *= -1
sqrt = 1 / (base ** power)
return constant * sqrt
# print("\nPOSITIVE WHOLE NUMBERS")
# print("2^0= " + str(exponent_function(1, 2, 0)))
# print("2^1= " + str(exponent_function(1, 2, 1)))
# print("2^2= " + str(exponent_function(1, 2, 2)))
# print("2^3= " + str(exponent_function(1, 2, 3)))
# print("1^4= " + str(exponent_function(1, 1, 4)))
#
# print("\nNEGATIVE WHOLE NUMBERS")
# print("2^-0= " + str(exponent_function(1, 2, -0)))
# print("2^-1= " + str(exponent_function(1, 2, -1)))
# print("2^-2= " + str(exponent_function(1, 2, -2)))
# print("2^-3= " + str(exponent_function(1, 2, -3)))
# print("1^-4= " + str(exponent_function(1, 1, -4)))
#
# print("\nPOSITIVE FLOAT NUMBERS")
# print("2^0.0= " + str(exponent_function(1, 2, 0.0)))
# print("2^0.5= " + str(exponent_function(1, 2, 0.5)))
# print("2^1.5= " + str(exponent_function(1, 2, 1.5)))
# print("2^2.5= " + str(exponent_function(1, 2, 2.5)))
# print("2^3.5= " + str(exponent_function(1, 2, 3.5)))
# print("1^4.5= " + str(exponent_function(1, 1, 4.5)))
# print("4^1.5= " + str(exponent_function(1, 4, 1.5)))
# print("8^0.3= " + str(exponent_function(1, 8, 0.3)))
# print("2^arcos(0.98)= " + str(exponent_function(1, 2, math.acos(0.98))))
# print("2^log2(10)= " + str(exponent_function(1, 2, math.log(10, 2))))
# print("\nNEGATIVE FLOAT NUMBERS")
# print("2^-0.0= " + str(exponent_function(1, 2, -0.0)))
# print("2^-0.5= " + str(exponent_function(1, 4, -0.5)))
# print("2^-1.5= " + str(exponent_function(1, 2, -1.5)))
# print("2^-2.5= " + str(exponent_function(1, 2, -2.5)))
# print("2^-3.5= " + str(exponent_function(1, 2, -3.5)))
# print("1^-4.5= " + str(exponent_function(1, 1, -4.5)))
# print("4^-1.5= " + str(exponent_function(1, 4, -1.5)))
# print("8^-0.3= " + str(exponent_function(1, 8, -0.3)))
| true
|
8face047d25661db2f4a5ed4faccf7036977c899
|
y0m0/MIT.6.00.1x
|
/Lecture5/L5_P8_isIn.py
| 854
| 4.28125
| 4
|
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Base case: If aStr is empty, we did not find the char.
if aStr == '':
return False
# Base case: if aStr is of length 1, just see if the chars are equal
if len(aStr) == 1:
return char == aStr
middle = aStr[len(aStr)/2]
if char == middle:
return True
# Recursive case: If the test character is bigger than the middle
# character, recursively search on the first half of aStr
if char > middle:
return isIn(char,aStr[len(aStr)/2:])
# Otherwise the test character is smaller than the middle
# character, recursively search on the first half of aStr
else:
return isIn(char,aStr[:len(aStr)/2])
| true
|
4a442570e403106067cd7df096500e2d34099819
|
ge01/StartingOutWithPython
|
/Chapter_02/program_0212.py
| 236
| 4.1875
| 4
|
# Get the user's first name.
first_name = raw_input('Enter your first name: ')
# Get the user's last name.
last_name = raw_input('Enter your last name: ')
# Print a greeting to the user.
print('Hello ' + first_name + " " + last_name)
| true
|
d38fbf3290696cc8ca9ae950fd4fe81c0253bbfd
|
jiresimon/csc_lab
|
/csc_ass_1/geometric_arithmetic/geo_arithmetic_mean.py
| 1,066
| 4.25
| 4
|
from math import *
print("Program to calculate the geometric/arithmetic mean of a set of positive values")
print()
print("N -- Total number of positive values given")
print()
total_num = int(input("Enter the value for 'N' in the question:\n>>> "))
print()
print("Press the ENTER KEY to save each value you enter...")
i = 1
num_list = []
while (i <= total_num):
numbers = int(input("Enter the numbers:\n>>> "))
if numbers > 0 :
num_list.append(numbers)
elif numbers < 0:
break
i+=1
print(num_list)
#To calculate the geometric mean
try:
geo_mean_1 = prod(num_list)
geo_mean_2= pow(geo_mean_1, 1/total_num)
#To calculate the arithmetic mean
ar_mean_1 = sum(num_list)
ar_mean_2 = (ar_mean_1/len(num_list))
print('Here are your answers...')
print()
print(f"The geometric mean of the given set of positive values is {geo_mean_2}")
print(f"The arithmetic mean of the given set of positive values is {ar_mean_2}")
except ZeroDivisionError:
print("Not divisible by zero")
| true
|
bcb4dd22aab6768e2540ccd3394a8078b8b38490
|
RazvanCimpean/Python
|
/BMI calculator.py
| 337
| 4.25
| 4
|
# Load pandas
import pandas as pd
# Read CSV file into DataFrame df
df = pd.read_csv('sample 2.csv', index_col=0)
# Show dataframe
print(df)
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.