blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
90597944fa6a087ee66dc343ed3f846b332390da | jaliagag/21_python | /pirple/08/second.py | 2,601 | 4.21875 | 4 | # Project #1: A Simple Game
#Details:
#Have you ever played "Connect 4"? It's a popular kid's game by the Hasbro company. In this project, your task is create a Connect 4 game in Python. Before you get started, please watch this video on the rules of Connect 4:
#https://youtu.be/utXzIFEVPjA
# Rules
# 2 players 6 rows, 7 columns
# goal is to get 4 pieces in a row, diagonal, vertical, horizontal
#Once you've got the rules down, your assignment should be fairly straightforward. You'll want to draw the board, and allow two players to take turns placing their pieces on the board (but as you learned above, they can only do so by choosing a column, not a row). The first player to get 4 across or diagonal should win!
#Normally the pieces would be red and black, but you can use X and O instead.
#Extra Credit:
#Want to try colorful pieces instead of X and O? First you'll need to figure out how to import a package like termcolor into your project. We're going to cover importing later in the course, but try and see if you can figure it out on your own. Or you might be able to find unicode characters to use instead, depending on what your system supports. Here's a hint: print(u'\u2B24')
import os
def board (rows, columns):
Trows, Tcolumns = os.popen('stty size', 'r').read().split()
if rows > int(Trows) or columns > int(Tcolumns):
return False
else:
dash = '-'
rows *= 2
columns *= 2
dashes = dash*(columns+1)
menosUno = columns-1
for row in range(rows):
if row % 2 == 0:
for column in range(1,columns):
if column % 2 == 1:
if column == menosUno:
print(" |")
else:
print(" ", end="")
else:
print("|", end="")
else:
print(dashes)
return True
board(6, 7)
campo = []
turn = 0
score = 0
counter = 0
def changeTurn():
global turn
if turn == 1:
turn = 0
elif turn == 0:
turn = 1
def wrong(param):
if param <= 0 or param > 7:
print('wrong column number - please, input a valid column number, 1 through 7')
changeTurn()
while counter < 10:
counter += 1
if turn == 0:
play = int(input('player 1: select a column 1 - 7 to make your move: '))
wrong(play)
if turn == 1:
play = int(input('player 2: select a column 1 - 7 to make your move: '))
wrong(play)
changeTurn()
print(counter)
| true |
8a2a8f8023225a98482a7c70274dc7ba892f24b1 | ElianMelo/python | /Aulas/Mundo 02 Estruturas de Controle/Aula 14 - Desafio 59.py | 1,224 | 4.15625 | 4 | num1 = float(input("Digite o 1° Valor: "))
num2 = float(input("Digite o 2° Valor: "))
maior = 0
menor = 0
opcao = 0
while opcao != 5:
print('''[ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Novos Números
[ 5 ] Sair do Programa''')
opcao = int(input("Qual opção? "))
# Realiza a soma dos valores
if opcao == 1:
soma = num1 + num2
print(" ")
print("A soma de {} + {} = {}".format(num1, num2, soma))
print(" ")
# Realiza a multiplicação dos valores
if opcao == 2:
mult = num1 * num2
print(" ")
print("A multiplicação de {} * {} = {}".format(num1, num2, mult))
print(" ")
# Realiza a captura de novos valores
if opcao == 3:
if num1 >= num2:
maior = num1
menor = num2
else:
maior = num2
menor = num1
print(" ")
print("O maior valor é {} e o menor valor é {}".format(maior, menor))
print(" ")
# Realiza a captura de novos valores
if opcao == 4:
num1 = float(input("Digite o 1° Valor: "))
num2 = float(input("Digite o 2° Valor: "))
print("Fim do Programa")
| false |
46c442fc739b7e287d01a43d467013b5d92138c3 | All3yp/Daily-Coding-Problem-Solutions | /Solutions/206.py | 752 | 4.46875 | 4 | """
Problem:
A permutation can be specified by an array P, where P[i] represents the location of the
element at i in the permutation. For example, [2, 1, 0] represents the permutation
where elements at the index 0 and 2 are swapped.
Given an array and a permutation, apply the permutation to the array. For example,
given the array ["a", "b", "c"] and the permutation [2, 1, 0], return ["c", "b", "a"].
"""
from typing import List
def permute(arr: List[str], p: List[int]) -> List[str]:
for i in range(len(p)):
p[i] = arr[p[i]]
return p
if __name__ == "__main__":
print(permute(["a", "b", "c"], [2, 1, 0]))
print(permute(["a", "b", "c", "d"], [3, 0, 1, 2]))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
"""
| true |
4e89662b7935b081c2812eab1e621b3a1eae69b1 | All3yp/Daily-Coding-Problem-Solutions | /Solutions/153.py | 1,502 | 4.21875 | 4 | """
Problem:
Find an efficient algorithm to find the smallest distance (measured in number of words)
between any two given words in a string.
For example, given words "hello", and "world" and a text content of "dog cat hello cat
dog dog hello cat world", return 1 because there's only one word "cat" in between the
two words.
"""
def calculate_distance(text: str, word1: str, word2: str) -> int:
word_list = text.split()
length = len(word_list)
distance, position, last_match = None, None, None
# searching for the smallest distance
for i in range(length):
if word_list[i] in (word1, word2):
if last_match in (word_list[i], None):
last_match = word_list[i]
position = i
continue
current_distance = i - position - 1
last_match = word_list[i]
position = i
if distance == None:
distance = current_distance
else:
distance = min(distance, current_distance)
return distance
if __name__ == "__main__":
print(
calculate_distance(
"dog cat hello cat dog dog hello cat world", "hello", "world"
)
)
print(
calculate_distance("dog cat hello cat dog dog hello cat world", "world", "dog")
)
print(calculate_distance("hello world", "hello", "world"))
print(calculate_distance("hello", "hello", "world"))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
"""
| true |
936693bb7143edab3a6cd7e8768839cddf955f8b | All3yp/Daily-Coding-Problem-Solutions | /Solutions/103.py | 1,969 | 4.125 | 4 | """
Problem:
Given a string and a set of characters, return the shortest substring containing all
the characters in the set.
For example, given the string "figehaeci" and the set of characters {a, e, i}, you
should return "aeci".
If there is no substring containing all the characters in the set, return null.
"""
from typing import Set
def shortest_substring_with_all_characters(string: str, characters: Set[str]) -> str:
curr_char_queue, index_queue = [], []
curr_seen = set()
num_char = len(characters)
result = None
# generating the shortest substring
for i in range(len(string)):
if string[i] in characters:
curr_char_queue.append(string[i])
index_queue.append(i)
curr_seen.add(string[i])
# shortening the substring
shift = 0
for k in range(len(curr_char_queue) // 2):
if curr_char_queue[k] == curr_char_queue[-k - 1]:
shift += 1
# truncating the queues
curr_char_queue = curr_char_queue[shift:]
index_queue = index_queue[shift:]
# all characters found
if len(curr_seen) == num_char:
if (not result) or (len(result) > (index_queue[-1] - index_queue[0] + 1)):
result = string[index_queue[0] : index_queue[-1] + 1]
return result
if __name__ == "__main__":
print(shortest_substring_with_all_characters("abcdedbc", {"g", "f"}))
print(shortest_substring_with_all_characters("abccbbbccbcb", {"a", "b", "c"}))
print(shortest_substring_with_all_characters("figehaeci", {"a", "e", "i"}))
print(shortest_substring_with_all_characters("abcdedbc", {"d", "b", "b"}))
print(shortest_substring_with_all_characters("abcdedbc", {"b", "c"}))
print(shortest_substring_with_all_characters("abcdecdb", {"b", "c"}))
print(shortest_substring_with_all_characters("abcdecdb", {"b", "c", "e"}))
"""
SPECS:
TIME COMPLEXITY: O(n ^ 2)
SPACE COMPLEXITY: O(n)
"""
| true |
a01b0ff284ec23054811211c269826e0d43221b4 | All3yp/Daily-Coding-Problem-Solutions | /Solutions/056.py | 1,066 | 4.125 | 4 | """
Problem:
Given an undirected graph represented as an adjacency matrix and an integer k, write a
function to determine whether each vertex in the graph can be colored such that no two
adjacent vertices share the same color using at most k colors.
"""
from typing import List
def can_color(adjacency_matrix: List[List[int]], k: int) -> bool:
minimum_colors_required = 0
vertices = len(adjacency_matrix)
# generating the minimum number of colors required to color the graph
for vertex in range(vertices):
colors_required_for_current_vertex = sum(adjacency_matrix[vertex]) + 1
minimum_colors_required = max(
minimum_colors_required, colors_required_for_current_vertex
)
return minimum_colors_required <= k
if __name__ == "__main__":
adjacency_matrix = [
[0, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0],
]
print(can_color(adjacency_matrix, 4))
print(can_color(adjacency_matrix, 3))
"""
SPECS:
TIME COMPLEXITY: O(n ^ 2)
SPACE COMPLEXITY: O(1)
"""
| true |
95f8ac695131eb49055717f7fa9704e45f9da577 | All3yp/Daily-Coding-Problem-Solutions | /Solutions/027.py | 1,289 | 4.21875 | 4 | """
Problem:
Given a string of round, curly, and square open and closing brackets, return whether
the brackets are balanced (well-formed).
For example, given the string "([])", you should return true.
Given the string "([)]" or "((()", you should return false.
"""
from typing import Dict
from DataStructures.Stack import Stack
def is_parenthesis_balanced(
string: str, parenthesis_map: Dict[str, str] = {"{": "}", "[": "]", "(": ")"}
) -> bool:
open_parenthesis_set = set(parenthesis_map.keys())
stack = Stack()
# iterating through the string and checking if its balanced
for char in string:
if char in open_parenthesis_set:
stack.push(char)
elif not stack.is_empty() and parenthesis_map[stack.peek()] == char:
stack.pop()
else:
return False
# the string is balanced only if the stack is empty (equal number of opening and
# closing parenthesis)
return stack.is_empty()
if __name__ == "__main__":
print(is_parenthesis_balanced("([])"))
print(is_parenthesis_balanced("((([{}])))"))
print(is_parenthesis_balanced("([])[]({})"))
print(is_parenthesis_balanced("([)]"))
print(is_parenthesis_balanced("((()"))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
"""
| true |
b98e12ef4e9cd729ddaaac08d491330a0c1fe87a | All3yp/Daily-Coding-Problem-Solutions | /Solutions/129.py | 785 | 4.1875 | 4 | """
Problem:
Given a real number n, find the square root of n. For example, given n = 9, return 3.
"""
TOLERENCE = 10 ** (-6)
def almost_equal(num1: float, num2: float) -> bool:
return num1 - TOLERENCE < num2 < num1 + TOLERENCE
def get_sqrt(num: int) -> float:
# using binary search to get the sqaure-root
high, low = num, 0
while True:
mid = (high + low) / 2
mid_square = mid * mid
if almost_equal(mid_square, num):
return round(mid, 6)
elif mid_square < num:
low = mid + 1
else:
high = mid - 1
if __name__ == "__main__":
print(get_sqrt(100))
print(get_sqrt(9))
print(get_sqrt(3))
print(get_sqrt(2))
"""
SPECS:
TIME COMPLEXITY: O(log(n))
SPACE COMPLEXITY: O(1)
"""
| true |
8c93d2ab457003f16a47c40ca1058cdb06a61d6e | All3yp/Daily-Coding-Problem-Solutions | /Solutions/083.py | 989 | 4.15625 | 4 | """
Problem:
Invert a binary tree.
For example, given the following tree:
a
/ \
b c
/ \ /
d e f
should become:
a
/ \
c b
\ / \
f e d
"""
from DataStructures.Tree import BinaryTree, Node
def invert_helper(node: Node) -> None:
node.right, node.left = node.left, node.right
# recursively inverting the children
if node.right is not None:
invert_helper(node.right)
if node.left is not None:
invert_helper(node.left)
def invert(tree: BinaryTree) -> None:
# inverts the tree in place
if not tree.root:
return
invert_helper(tree.root)
if __name__ == "__main__":
tree = BinaryTree()
tree.root = Node("a")
tree.root.left = Node("b")
tree.root.right = Node("c")
tree.root.left.left = Node("d")
tree.root.left.right = Node("e")
tree.root.right.left = Node("f")
print(tree)
invert(tree)
print(tree)
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(log(n))
"""
| true |
6c9b7bc41eb453dea54279f479e91d0415eb00cd | All3yp/Daily-Coding-Problem-Solutions | /Solutions/258.py | 1,837 | 4.375 | 4 | """
Problem:
In Ancient Greece, it was common to write text with the first line going left to right,
the second line going right to left, and continuing to go back and forth. This style
was called "boustrophedon".
Given a binary tree, write an algorithm to print the nodes in boustrophedon order.
For example, given the following tree:
1
/ \
2 3
/ \ / \
4 5 6 7
You should return [1, 3, 2, 4, 5, 6, 7].
"""
from typing import Dict, List
from DataStructures.Tree import Node, BinaryTree
def get_boustrophedon_helper(
node: Node, level: int, accumulator: Dict[int, List[int]]
) -> None:
# using dfs to store a list of values by level
if level not in accumulator:
accumulator[level] = []
accumulator[level].append(node.val)
if node.left:
get_boustrophedon_helper(node.left, level + 1, accumulator)
if node.right:
get_boustrophedon_helper(node.right, level + 1, accumulator)
def get_boustrophedon(tree: BinaryTree) -> List[int]:
if not tree.root:
return []
# generating the nodes by level
level_data = {}
get_boustrophedon_helper(tree.root, 1, level_data)
result = []
# adding the even levels in reverse order in the result
for level in sorted(list(level_data.keys())):
if level % 2 == 0:
result.extend(reversed(level_data[level]))
else:
result.extend(level_data[level])
return result
if __name__ == "__main__":
tree = BinaryTree()
tree.root = Node(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
print(get_boustrophedon(tree))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
"""
| true |
b680d98973d1ae1bbce673b95533fa98ea0cbfa6 | All3yp/Daily-Coding-Problem-Solutions | /Solutions/342.py | 1,187 | 4.15625 | 4 | """
Problem:
reduce (also known as fold) is a function that takes in an array, a combining function,
and an initial value and builds up a result by calling the combining function on each
element of the array, left to right. For example, we can write sum() in terms of
reduce:
def add(a, b):
return a + b
def sum(lst):
return reduce(lst, add, 0)
This should call add on the initial value with the first element of the array, and then
the result of that with the second element of the array, and so on until we reach the
end, when we return the sum of the array.
Implement your own version of reduce.
"""
from typing import Any, Callable, Iterable
def reduce(iterable: Iterable, func: Callable, initial_value: int) -> int:
value = initial_value
for item in iterable:
value = func(value, item)
return value
def add(a: int, b: int) -> int:
return a + b
def sum(lst: Iterable) -> int:
return reduce(lst, add, 0)
if __name__ == "__main__":
print(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
[for the reduce function only (considering the iterable doesn't contain a nested
iterable)]
"""
| true |
4ad27acf7b2b4ee7a28ccd5dd3f0dc77148dbb2b | All3yp/Daily-Coding-Problem-Solutions | /Solutions/191.py | 1,208 | 4.1875 | 4 | """
Problem:
Given a collection of intervals, find the minimum number of intervals you need to
remove to make the rest of the intervals non-overlapping.
Intervals can "touch", such as [0, 1] and [1, 2], but they won't be considered
overlapping.
For example, given the intervals (7, 9), (2, 4), (5, 8), return 1 as the last interval
can be removed and the first two won't overlap.
The intervals are not necessarily sorted in any order.
"""
from typing import List
def num_overlap(arr: List[int]) -> int:
time_slot_usage = [False for _ in range(max(arr, key=lambda x: x[1])[1] + 1)]
overlap_count = 0
for interval in arr:
start, end = interval
overlap_flag = True
for i in range(start, end):
if not time_slot_usage[i]:
time_slot_usage[i] = True
elif overlap_flag:
overlap_count += 1
overlap_flag = False
return overlap_count
if __name__ == "__main__":
print(num_overlap([[0, 1], [1, 2]]))
print(num_overlap([(7, 9), (2, 4), (5, 8)]))
print(num_overlap([(7, 9), (2, 4), (5, 8), (1, 3)]))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
[n = maximum ending time]
"""
| true |
9a3698e9e19924e0ef4781ec89d9f0228ef4394c | All3yp/Daily-Coding-Problem-Solutions | /Solutions/349.py | 2,032 | 4.21875 | 4 | """
Problem:
Soundex is an algorithm used to categorize phonetically, such that two names that sound
alike but are spelled differently have the same representation.
Soundex maps every name to a string consisting of one letter and three numbers, like
M460.
One version of the algorithm is as follows:
Remove consecutive consonants with the same sound (for example, change ck -> c).
Keep the first letter. The remaining steps only apply to the rest of the string.
Remove all vowels, including y, w, and h.
Replace all consonants with the following digits:
b, f, p, v -> 1
c, g, j, k, q, s, x, z -> 2
d, t -> 3
l -> 4
m, n -> 5
r -> 6
If you don't have three numbers yet, append zeros until you do. Keep the first three
numbers. Using this scheme, Jackson and Jaxen both map to J250.
"""
IRRELEVANT_CHAR = {"a", "e", "i", "o", "u", "y", "w", "h"}
SIMILAR_SOUND_MAP = {"c": {"k", "s"}, "k": {"c"}, "s": {"c"}}
CHAR_DIGIT_MAP = {
"b": "1",
"f": "1",
"p": "1",
"v": "1",
"c": "2",
"g": "2",
"j": "2",
"k": "2",
"q": "2",
"s": "2",
"x": "2",
"z": "2",
"d": "3",
"t": "3",
"l": "4",
"m": "5",
"n": "5",
"r": "6",
}
def soundex(word: str) -> str:
# removing irrelevant characters from the word
word = "".join([char for char in word.lower() if char not in IRRELEVANT_CHAR])
last_char = word[0]
transformed_word = last_char
soundex_map = ""
# eliminating similar sounding characters
for char in word[1:]:
if char in SIMILAR_SOUND_MAP:
if last_char in SIMILAR_SOUND_MAP[char]:
continue
transformed_word += char
last_char = char
# generating soundex
soundex_map = transformed_word[0].upper()
for char in transformed_word[1:]:
soundex_map += CHAR_DIGIT_MAP[char]
return soundex_map + "0" * (4 - len(soundex_map))
if __name__ == "__main__":
print(soundex("Jackson"))
print(soundex("Jaxen"))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
"""
| true |
5ecbeed93255cb3c8d57aa53d05f2834d0a00aea | All3yp/Daily-Coding-Problem-Solutions | /Solutions/182.py | 1,714 | 4.1875 | 4 | """
Problem:
A graph is minimally-connected if it is connected and there is no edge that can be
removed while still leaving the graph connected. For example, any binary tree is
minimally-connected.
Given an undirected graph, check if the graph is minimally-connected. You can choose to
represent the graph as either an adjacency matrix or adjacency list.
"""
from copy import deepcopy
from DataStructures.Graph import GraphUndirectedUnweighted
from DataStructures.Queue import Queue
def is_minimally_connected(graph: GraphUndirectedUnweighted) -> bool:
graph_copy = GraphUndirectedUnweighted()
graph_copy.connections, graph_copy.nodes = deepcopy(graph.connections), graph.nodes
# getting a random node for starting the traversal
for node in graph.connections:
start = node
break
# running bfs and checking if a node is visited more than once
# (redundant edges present => not a minimally connected graph)
visited = set([start])
queue = Queue()
queue.enqueue(start)
while not queue.is_empty():
node = queue.dequeue()
for neighbour in graph_copy.connections[node]:
graph_copy.connections[neighbour].remove(node)
queue.enqueue(neighbour)
if neighbour in visited:
return False
visited.add(neighbour)
return True
if __name__ == "__main__":
graph = GraphUndirectedUnweighted()
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(3, 4)
print(graph)
print(is_minimally_connected(graph))
graph.add_edge(1, 4)
print(graph)
print(is_minimally_connected(graph))
"""
SPECS:
TIME COMPLEXITY: O(n x e)
SPACE COMPLEXITY: O(n + e)
"""
| true |
f0800fbf4e22a4cff89344fe365e41e235a41b1d | All3yp/Daily-Coding-Problem-Solutions | /Solutions/123.py | 2,587 | 4.1875 | 4 | """
Problem:
Given a string, return whether it represents a number. Here are the different kinds of
numbers:
"10", a positive integer
"-10", a negative integer
"10.1", a positive real number
"-10.1", a negative real number
"1e5", a number in scientific notation
And here are examples of non-numbers:
"a"
"x 1"
"a -2"
"-"
"""
def check_valid_number_representation(string: str) -> bool:
is_valid = True
has_number = False
num_negatives, num_points, num_e = 0, 0, 0
for char in string:
if not (char.isdigit()):
if char == "-":
if num_negatives >= 1:
# if the string contains an 'e', 2 '-'s are allowed (for mantissa
# and exponent)
if num_negatives == 1 and num_e == 1:
num_negatives += 1
continue
is_valid = False
break
num_negatives += 1
elif char == ".":
if num_points >= 1:
# if the string contains an 'e', 2 '.'s are allowed (for mantissa
# and exponent)
if num_points == 1 and num_e == 1:
num_points += 1
continue
is_valid = False
break
num_points += 1
elif char == "e":
# a number can have only 1 'e'
if num_e >= 1:
is_valid = False
break
num_e += 1
elif char == " ":
# spaces are ignored
pass
else:
# any other character makes the number invalid
is_valid = False
break
else:
# current character is a number
has_number = True
return is_valid and has_number
if __name__ == "__main__":
print(check_valid_number_representation("10"))
print(check_valid_number_representation("-10"))
print(check_valid_number_representation("10.1"))
print(check_valid_number_representation("-10.1"))
print(check_valid_number_representation("1e5"))
print(check_valid_number_representation("1e-5"))
print(check_valid_number_representation("-1.6 e -5.2"))
print(check_valid_number_representation("a"))
print(check_valid_number_representation("x 1"))
print(check_valid_number_representation("a -2"))
print(check_valid_number_representation("-"))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
"""
| true |
b27d136b1b597c64f89e1487080cb866f2160b07 | All3yp/Daily-Coding-Problem-Solutions | /Solutions/177.py | 971 | 4.21875 | 4 | """
Problem:
Given a linked list and a positive integer k, rotate the list to the right by k places.
For example, given the linked list 7 -> 7 -> 3 -> 5 and k = 2, it should become
3 -> 5 -> 7 -> 7.
Given the linked list 1 -> 2 -> 3 -> 4 -> 5 and k = 3, it should become
3 -> 4 -> 5 -> 1 -> 2.
"""
from DataStructures.LinkedList import Node, LinkedList
def rotate_linked_list(ll: LinkedList, k: int = 0) -> None:
k = k % ll.length
for _ in range(k):
temp = ll.head
ll.head = ll.head.next
temp.next = None
ll.rear.next = temp
ll.rear = ll.rear.next
if __name__ == "__main__":
LL = LinkedList()
for num in [7, 7, 3, 5]:
LL.add(num)
print(LL)
rotate_linked_list(LL, 2)
print(LL)
print()
LL = LinkedList()
for num in [1, 2, 3, 4, 5]:
LL.add(num)
print(LL)
rotate_linked_list(LL, 3)
print(LL)
"""
SPECS:
TIME COMPLEXITY: O(k)
SPACE COMPLEXITY: O(1)
"""
| true |
7c37fd99f49eb5b8e3e037686b025c975c33792b | All3yp/Daily-Coding-Problem-Solutions | /Solutions/141.py | 2,422 | 4.1875 | 4 | """
Problem:
Implement 3 stacks using a single list:
class Stack:
def __init__(self):
self.list = []
def pop(self, stack_number):
pass
def push(self, item, stack_number):
pass
"""
class Stack:
def __init__(self) -> None:
self.list = []
self.stack1_last_index = 0
self.stack2_last_index = 0
self.stack3_last_index = 0
def __repr__(self) -> str:
return (
f"Stack1: {self.list[:self.stack1_last_index]}"
+ f"\nStack2: {self.list[self.stack1_last_index:self.stack2_last_index]}"
+ f"\nStack3: {self.list[self.stack2_last_index:]}"
)
def pop(self, stack_number: int) -> int:
if stack_number == 1:
if len(self.list[: self.stack1_last_index]) == 0:
raise ValueError("Stack Underflow")
self.list.pop(self.stack1_last_index - 1)
self.stack1_last_index -= 1
self.stack2_last_index -= 1
self.stack3_last_index -= 1
elif stack_number == 2:
if len(self.list[self.stack1_last_index : self.stack2_last_index]) == 0:
raise ValueError("Stack Underflow")
self.list.pop(self.stack2_last_index - 1)
self.stack2_last_index -= 1
self.stack3_last_index -= 1
elif stack_number == 3:
if len(self.list[self.stack2_last_index :]) == 0:
raise ValueError("Stack Underflow")
self.list.pop()
self.stack3_last_index -= 1
def push(self, item: int, stack_number: int) -> None:
if stack_number == 1:
self.list.insert(self.stack1_last_index, item)
self.stack1_last_index += 1
self.stack2_last_index += 1
self.stack3_last_index += 1
elif stack_number == 2:
self.list.insert(self.stack2_last_index, item)
self.stack2_last_index += 1
self.stack3_last_index += 1
elif stack_number == 3:
self.list.insert(self.stack3_last_index, item)
self.stack3_last_index += 1
if __name__ == "__main__":
stack = Stack()
stack.push(5, 3)
stack.push(10, 2)
stack.push(1, 1)
print(stack)
print()
stack.push(3, 3)
stack.push(1, 2)
stack.push(0, 2)
print(stack)
print()
stack.pop(2)
stack.pop(1)
stack.pop(3)
print(stack)
| false |
2eb04c62a087d65891257394bd67d25d7e7d50cb | All3yp/Daily-Coding-Problem-Solutions | /Solutions/234.py | 1,783 | 4.125 | 4 | """
Problem:
Recall that the minimum spanning tree is the subset of edges of a tree that connect all
its vertices with the smallest possible total edge weight. Given an undirected graph
with weighted edges, compute the maximum weight spanning tree.
"""
from typing import Set
from DataStructures.Graph import GraphUndirectedWeighted
def get_maximum_spanning_tree_helper(
graph: GraphUndirectedWeighted,
curr_node: int,
remaining_nodes: Set[int],
weight: int,
) -> int:
if not remaining_nodes:
return weight
scores = []
for destination in graph.connections[curr_node]:
if destination in remaining_nodes:
rem_cp = set(remaining_nodes)
rem_cp.remove(destination)
new_score = get_maximum_spanning_tree_helper(
graph,
destination,
rem_cp,
weight + graph.connections[curr_node][destination],
)
scores.append(new_score)
return max(scores)
def get_maximum_spanning_tree(graph: GraphUndirectedWeighted) -> int:
node_set = set(graph.connections.keys())
start_node = node_set.pop()
weight = get_maximum_spanning_tree_helper(graph, start_node, node_set, 0)
return weight
if __name__ == "__main__":
graph = GraphUndirectedWeighted()
graph.add_edge(1, 2, 5)
graph.add_edge(1, 3, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 3)
graph.add_edge(2, 4, 4)
print(graph)
print(get_maximum_spanning_tree(graph))
graph = GraphUndirectedWeighted()
graph.add_edge(1, 2, 1)
graph.add_edge(1, 3, 2)
graph.add_edge(3, 2, 3)
print(graph)
print(get_maximum_spanning_tree(graph))
"""
SPECS:
TIME COMPLEXITY: O(n x e)
SPACE COMPLEXITY: O(n x e)
"""
| true |
23777a53212dab0229f75bb35ddf2f64973c515a | All3yp/Daily-Coding-Problem-Solutions | /Solutions/096.py | 1,081 | 4.25 | 4 | """
Problem:
Given a number in the form of a list of digits, return all possible permutations.
For example, given [1,2,3], return [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]].
"""
from copy import deepcopy
from typing import List, Optional
def generate_all_permutations(
arr: List[int], l: int = 0, r: Optional[int] = None, res: List[List[int]] = []
) -> List[List[int]]:
if r is None:
r = len(arr) - 1
if l == r:
res.append(list(arr))
return res
# generating all permutation using backtracking
for i in range(l, r + 1):
arr[l], arr[i] = arr[i], arr[l]
generate_all_permutations(arr, l + 1, r, res)
arr[l], arr[i] = arr[i], arr[l]
return res
if __name__ == "__main__":
print(generate_all_permutations([1, 2, 3], res=[]))
print(generate_all_permutations([1, 2], res=[]))
print(generate_all_permutations([1], res=[]))
print(generate_all_permutations([], res=[]))
"""
SPECS:
TIME COMPLEXITY: O(n!)
SPACE COMPLEXITY: O(n!)
[there are n! permutions for an array with n elements]
"""
| true |
667cf6f76fd33d22a444047490d68124ae9a94cd | All3yp/Daily-Coding-Problem-Solutions | /Solutions/181.py | 1,568 | 4.28125 | 4 | """
Problem:
Given a string, split it into as few strings as possible such that each string is a
palindrome.
For example, given the input string "racecarannakayak", return
["racecar", "anna", "kayak"].
Given the input string "abc", return ["a", "b", "c"].
"""
from typing import List
def is_palindrome(string: str) -> bool:
return string and string == string[::-1]
def split_into_string_list_helper(
string: str, current: str, palindrome_list: List[str]
) -> List[str]:
if not string and not current:
return palindrome_list
elif not string:
return palindrome_list + list(current)
# generating the palindrome list
curr = current + string[0]
if is_palindrome(curr):
# adding curr to the list of palindromes
palindrome_list_1 = split_into_string_list_helper(
string[1:], "", palindrome_list + [curr]
)
# checking if a larger palindrome can be obtained
palindrome_list_2 = split_into_string_list_helper(
string[1:], curr, palindrome_list
)
return min(palindrome_list_1, palindrome_list_2, key=lambda List: len(List))
return split_into_string_list_helper(string[1:], curr, palindrome_list)
def split_into_string_list(string: str) -> List[str]:
return split_into_string_list_helper(string, "", [])
if __name__ == "__main__":
print(split_into_string_list("racecarannakayak"))
print(split_into_string_list("abc"))
print(split_into_string_list("abbbc"))
"""
SPECS:
TIME COMPLEXITY: O(2 ^ n)
SPACE COMPLEXITY: O(n)
"""
| true |
305b0b5717f0b2a43894e4d4f5b3af868947481f | All3yp/Daily-Coding-Problem-Solutions | /Solutions/108.py | 480 | 4.15625 | 4 | """
Problem:
Given two strings A and B, return whether or not A can be shifted some number of times
to get B.
For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb,
return false.
"""
def can_shift(A: str, B: str) -> bool:
return (A and B) and (len(A) == len(B)) and (B in A * 2)
if __name__ == "__main__":
print(can_shift("abcde", "cdeab"))
print(can_shift("abc", "acb"))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
"""
| true |
7d51b55c96bf2d21cbd38d7b6a9ef921afdfa61c | sridharkritha/programming | /python/calculation.py | 859 | 4.21875 | 4 | def divide(first,second):
while True:
try:
final = float(first)/float(second)
break
except ZeroDivisionError:
print("Can't Divide By Zero")
second = input("Enter Second Number: ")
secondNum = second
return final
while True:
firstNum = input("Enter a Number: ")
secondNum = input("Enter a Second Number: ")
operation = input("Add(+), Subtract(-), Multiply(*), or Divide(/)? ")
if operation == "+":
result = float(firstNum) + float(secondNum)
elif operation == "-":
result = float(firstNum) - float(secondNum)
elif operation == "*":
result = float(firstNum) * float(secondNum)
elif operation == "/":
result = divide(firstNum,secondNum)
print(firstNum + ' ' + operation + ' ' + secondNum + ' = ' + str(result))
break
| false |
ed1d2b7d94c117c94668a2e544640ed66c3bfe43 | xDhairyax/GuessingGame | /guessinggame.py | 414 | 4.1875 | 4 | import random
chances=0
number=random.randint(1,10)
while chances < 5:
guess=int(input("Guess a Number between 1 and 10:"))
if guess == number:
print("YOU WIN!!")
break
elif guess > number:
print("GUESS LOWER,TRY AGAIN")
else:
print("GUESS HIGHER,TRY AGAIN")
chances+=1
if not chances < 5:
print("YOU LOSE!! THE NUMBER IS ",number)
| true |
be3699af387e756b570c7ca0845471d5ddda01ac | prosales95/PythonInterm | /Comprehensions.py | 1,171 | 4.4375 | 4 | print('List comprehension Examples with multiples of 3 until 30')
multiples = [i for i in range(30) if i % 3 == 0]
print(multiples)
print('Awesome the same applies for divisors if we just remember that range is')
print('only considering from 1 until n-1, then we have to adjust limits')
n = int(input('Divisors of n = '))
def divisors(n):
divisors = [j for j in range(1, n + 1) if n % j == 0]
print(divisors)
print('divisors of n are')
print(divisors(n))
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
# normal option with 3 lines
squared = []
for x in range(10):
squared.append(x ** 2)
# better opt with compreh
squared = [x ** 2 for x in range(10)]
print(squared)
# 2. dict compr
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3, 'd': 32, 'D': 3}
mcase_frequency = {
k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0)
for k in mcase.keys()
}
print(mcase_frequency)
# mcase_frequency == {'a': 17, 'z': 3, 'b': 34}
# 3. set compr
squared = {x ** 2 for x in range(n + 1)}
print('the square numbers until then are :')
print(sorted(squared))
# Output: {1, 4}
# great! even better if we use sorted cause if not they are all over the place
| true |
214d51b996f0ea1c707881d7e470f8697e03a71a | bolivaralejandro/py4e | /ex102.py | 877 | 4.15625 | 4 | # Exercise 2: This program counts the distribution of the hour of the day for each
# of the messages. You can pull the hour from the “From” line by finding the time
# string and then splitting that string into parts using the colon character. Once
# you have accumulated the counts for each hour, print out the counts, one per line,
# sorted by hour as shown below.
# Sample Execution:
# python timeofday.py
# Enter a file name: mbox-short.txt
# 04 3
# 06 1
# 07 1
# 09 2
# 10 3
# 11 6
# 14 1
# 15 2
# 16 4
# 17 2
# 18 1
# 19 1
filename = input("Enter a file name: ")
fhand = open(filename, 'r')
hours_of_day = {}
for line in fhand:
if line.startswith("From "):
time = line.split()[5]
hour = time.split(":")[0]
hours_of_day[hour] = hours_of_day.get(hour, 0) + 1
lst = list(hours_of_day.items())
lst.sort()
for t in lst:
print(t[0], t[1]) | true |
97ff069eb351b6699ff8359fe2a6d0240ee53353 | ncapps/python-workout | /ch01_numeric_types/hexadecimal_output.py | 235 | 4.1875 | 4 | def hex_output():
decnum = 0
user_input = input("Enter a hex number to convert: ")
for power, digit in enumerate(reversed(user_input)):
decnum += int(digit, base=16) * (16 ** power)
print(decnum)
hex_output()
| true |
4d4c658822101d11c5d9c27839ab5aaa0c0a8d17 | AryamannNingombam/DSA | /sorting/bubbleSort/bubbleSort.py | 295 | 4.125 | 4 | def bubbleSort(array):
for i in range(len(array)):
for j in range(len(array)-i-1):
if array[j+1] < array[j]:
array[j+1],array[j] = array[j],array[j+1]
return array
print(bubbleSort(list(map(lambda x : int(x) , input("Enter the array").split())))) | false |
8bee369b096de5e0111d0ae398b5d7102e87b615 | AceHW/LearningPython3 | /guessing_game.py | 826 | 4.28125 | 4 | import random
number_of_guesses = 4
user_won = False
print("Welcome to the guessing game!")
# Computer guesses a random number between 1 and 10
correct_answer = random.randint(1, 10)
while number_of_guesses > 0:
# User guesses the number
user_guess = input("Guess my number: ")
user_guess = int(user_guess)
if user_guess == correct_answer:
print("Good guess")
print("You're correct")
user_won = True
break
# Computer tells user whether guess was too high or too low
elif user_guess > correct_answer:
print("Sorry, guessed too high")
elif user_guess < correct_answer:
print("Sorry, guessed too low")
# User has 3 guesses before losing the game
number_of_guesses -= 1
if user_won == True:
print("You won!")
else:
print("You lost")
| true |
be673d5726ab2addac1cf198fec4be9da96301f1 | oscos/codewars | /python/factorial.py | 1,071 | 4.34375 | 4 | # https://www.codewars.com/kata/54ff0d1f355cfd20e60001fc
def multiply(ls):
prod = 1
for x in ls:
prod *= x
return prod
def factorial(n):
if n > 12 or n < 0:
raise ValueError("Invalid Number")
# ls = list(range(n + 1))[1:]
ls = list(range(1, n + 1))
return multiply(ls)
# Other user submission
import math
def factorial(n):
if 0<=n<=12:
return math.factorial(n)
else:
raise ValueError("value out of range")
# Other user submission
# the int("x") will always raise a value error that the problem asks for
# __import__("math") is another way of importing python modules to get it all in one line
factorial=lambda n:__import__("math").factorial(n)if 0<=n<13 else int("x")
print(factorial(0), 1, "factorial for 0 is 1")
print(factorial(1), 1, "factorial for 1 is 1")
print(factorial(2), 2, "factorial for 2 is 2")
print(factorial(3), 6, "factorial for 3 is 6")
print(factorial(4), 9, "factorial for 2 is 2")
print(factorial(5), 13, "factorial for 2 is 2")
# print(factorial(-1), "Error", "factorial for 0 is 1") | true |
8d14fe3cfe0fe86dea93022c477f1ae0bb7e2536 | srihariprasad-r/workable-code | /Algorithms_Datastructures/sorting algorithms/insertionsort.py | 307 | 4.25 | 4 | def insertionsort(array):
for i in range(1, len(array)):
for j in range(i-1, -1 , -1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
else:
break
return array
array = [6,2,1,3,4]
print(insertionsort(array)) | false |
c356e338ff5db79ffa15aa157da311e9c504ec12 | srihariprasad-r/workable-code | /Practice problems/foundation/recursion/printzigzagsequence.py | 514 | 4.28125 | 4 | """
Pre sequence is peformed while going up recursive stack
In sequence is performed between left and right call
Post sequence is performed while coming down recursive stack
"""
def printzigzagsequence(n):
if n == 0:
return
print("pre sequence:", n) # pre-sequence
printzigzagsequence(n-1) # left call
print("in sequence:", n) # in sequence
printzigzagsequence(n-1) # right call
print("post sequence:", n) # post sequence
n = 3
printzigzagsequence(n) | true |
c95871a5975f3bdd05ff34cc4698252a8499d62e | srihariprasad-r/workable-code | /500_Practise Problems/arrange_get_largest_number.py | 613 | 4.125 | 4 | """
this function will arrange them in such way that the arrangement will form the largest value.
Input = {3, 1, 13, 34, 8}
Output = 8343131
"""
def arrangeNumber(array):
n = len(array)
for i in range(n):
for j in range(n):
if str(array[i]) + str(array[j]) > str(array[j]) + str(array[i]):
if i > j:
array[i], array[j] = array[j], array[i]
return ''.join(map(str,array)) #map function expects 2 arguments, function to be applied and sequence on which it should run
array = [3, 1, 13, 34, 8]
array_o = arrangeNumber(array)
print(array_o) | true |
a5341ff34dfd047fde4caa06f67612442ca47f43 | SparshGautam/Lists | /Lists2.py | 716 | 4.59375 | 5 |
digits = ("apple","microsoft","google","Tata") # assigning list to digits
print(digits[-1]) # as +ve is opposite of-ve here -1 represents to get output from backside of our list here "Tata" will be printed
print(digits[:3]) # here you can use colon so that the first 3 lis items will be printed
names = "hello my name is adarsh" # in the same way you can use colon to select in range
print(names[:5]) # here hello = 5 alphabets so i typed here 5
print(digits[0:3]) #this, function is known as strides here your 3rd digits will be printed leaving other 2
| true |
f972851601e69a837942a0b7645ddd6713aa870c | ALILIYES/Introduction-to-DataScience-and-Engineering | /All Code/4.8插入排序.py | 353 | 4.125 | 4 | def insertionSort(arr):
for i in range(1,len(arr)):
preindex = i-1
cur = arr[i]
while preindex>=0 and arr[preindex]>cur:
arr[preindex+1] = arr[preindex]
preindex-=1
arr[preindex+1] = cur
return arr
if __name__ == "__main__":
list = [5,3,4,2,1]
insertionSort(list)
print(list)
| false |
c3ddb968fab6d302986a4a373a54abfcfd153da1 | starizwan/projects-python | /[mini-project]-guess-the-number-computer/guess-number-user.py | 947 | 4.46875 | 4 | # Computer will generate some random number and user has to guess it in 3 attempts
# Computer should generate some hints on the range of number
import random
def guess(maximum):
secret_number = random.randint(1, maximum)
guessed_number = 0
max_guess_count = 3
guess_count = max_guess_count
print(f"Guess a number in {guess_count} attempts\n")
while(guess_count):
guessed_number = int(input(f"Guess a number between 1 to {maximum}: "))
if guessed_number > secret_number:
print("Sorry, Guessed number too high! \n")
elif guessed_number < secret_number:
print("Sorry, Guessed number is too low\n")
else:
print(f"\nGood! You have guessed the number {secret_number} correctly!!\n")
break
guess_count -= 1
else:
print(f"\nSorry you only get {max_guess_count} attempts.\n{secret_number} was the secret number")
guess(10) | true |
e0e1366da7b0d30a305d7b917dcbb92b438f8ba0 | WillDutcher/project-2-data-visualization | /exercises/cubes_colormap.py | 765 | 4.125 | 4 | """
A number raised to the third power is a cube.
Plot the first five cubic numbers and then plot the first 5000 cubic numbers.
"""
import matplotlib.pyplot as plt
# First 5000
x_values = range(1, 5001)
y_values = [x**3 for x in x_values]
plt.style.use('seaborn-deep')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Greens, s=1)
# Set chart title and label axes
ax.set_title('Cube Numbers', fontsize=24)
ax.set_xlabel('Value')
ax.set_ylabel('Cube of Value')
# Set range for each axis.
ax.axis([0, 5001, 0, 126000000000])
# Set the size of tick labels.
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('cubes_colormap_plot.png', bbox_inches='tight')
plt.show() # Show on-screen
| true |
b33dc48efd5c551bcd376554e99f6ca9bcbf96e7 | iamreebika/Python-Assignment2 | /Examples/4.py | 585 | 4.25 | 4 | """
4. Create a list. Append the names of your colleagues and friends to it.
Has the id of the list changed? Sort the list. What is the first item on
the list? What is the second item on the list?
"""
names = []
inital_id = id(names)
names.append('Tanu')
names.append('Aruna')
names.append('Kisa')
id_after_append = id(names)
if inital_id == id_after_append:
print('Id has not been changed and is {inital_id}')
else:
print('Id has been changed from {inital_id} to {id_after_append}')
names.sort()
print()
print('First item -> {names[0]}')
print('second item -> {names[1]}')
| true |
dc53865bed03df415d3b9a21ce47eb711d2f7461 | iamreebika/Python-Assignment2 | /Examples/7.py | 893 | 4.28125 | 4 | """
7. Create a list of tuples of first name, last name, and age for your
friends and colleagues. If you don't know the age, put in None.
Calculate the average age, skipping over any None values. Print out
each name, followed by old or young if they are above or below the
average age.
"""
from functools import reduce
people_data = ([('Reenika', 'Bhatta', 21), ('Bishal', 'Khanal', 22),
('Prakash', 'Aryal', None), ('Jaya', 'Kc', 23)])
ages = [x[2] for x in people_data]
sum_of_ages = 0
age_count = 0
for age in ages:
if age is not None:
age_count += 1
sum_of_ages += age
avg_age = sum_of_ages / age_count
for first_name, last_name, age in people_data:
print('{first_name} {last_name}', end=' ')
if age is not None:
if age < avg_age:
print('young')
else:
print('old')
else:
print('Unknown')
| true |
3033dfa221491e4794c5b458811abd9e84e4f98a | Minu94/PythonWorkBook1 | /python_oops/4.py | 561 | 4.25 | 4 | # Write a program to print the area of two rectangles having
# sides (4,5) and (5,8) respectively by creating a class named
# 'Rectangle' with a method named 'Area' which returns the area
# and length and breadth passed as parameters to its constructor.
class Rectangle:
def __init__(self,atr_tuple):
self.atr_tuple = atr_tuple
def area(self):
length =self.atr_tuple[0]
breadth = self.atr_tuple[1]
a = length*breadth
return print(a)
rec1 = Rectangle((4,5))
rec2 = Rectangle((5,8))
rec1.area()
rec2.area()
| true |
ef4700af074c40d83ad2c914ec8c04c3c6e13a56 | AragondaJyosna/chainladder-python | /docs/auto_examples/plot_triangle_from_pandas.py | 1,643 | 4.1875 | 4 | """
=======================
Basic Triangle Creation
=======================
This example demonstrates the typical way you'd ingest data into a Triangle.
Data in tabular form in a pandas DataFrame is required. At a minimum, columns
specifying origin and development, and a value must be present. Note, you can
include more than one column as a list as well as any number of indices for
creating triangle subgroups.
In this example, we create a triangle object with triangles for each company
in the CAS Loss Reserve Database for Workers' Compensation.
"""
import chainladder as cl
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Read in the data
lobs = 'wkcomp'
data = pd.read_csv(f'https://www.casact.org/research/reserve_data/wkcomp_pos.csv')
data = data[data['DevelopmentYear']<=1997]
# Create a triangle
triangle = cl.Triangle(data, origin='AccidentYear',
development='DevelopmentYear',
index=['GRNAME'],
columns=['IncurLoss_D','CumPaidLoss_D','EarnedPremDIR_D'])
# Output
print('Raw data:')
print(data.head())
print()
print('Triangle summary:')
print(triangle)
print()
print('Aggregate Paid Triangle:')
print(triangle['CumPaidLoss_D'].sum())
plot_data = triangle['CumPaidLoss_D'].sum().to_frame().unstack().reset_index()
plot_data.columns = ['Development Period', 'Accident Year', 'Cumulative Paid Loss']
sns.set_style('whitegrid')
plt.title('CAS Loss Reserve Database: Workers'' Compensation')
g = sns.pointplot(x='Development Period', y='Cumulative Paid Loss',
hue='Accident Year', data=plot_data, markers='.')
| true |
5c4adfede4c268ae5d631bb1c432925c660a83ce | maelfosso/dailycodingproblem | /dcp537.py | 1,255 | 4.15625 | 4 | """
This is your coding interview problem for today.
This problem was asked by Apple.
A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer:
if n is even, the next number in the sequence is n / 2
if n is odd, the next number in the sequence is 3n + 1
It is conjectured that every such sequence eventually reaches the number 1. Test this conjecture.
Bonus: What input n <= 1000000 gives the longest sequence?
We will be sending the solution tomorrow, along with tomorrow's question. As always, feel free to shoot us an email if there's anything we can help with.
Have a great day!
"""
def collatz(n):
s = n
seq = [s]
while s != 1:
if s % 2 == 0:
s = s / 2
else:
s = 3 * s + 1
seq.append(int(s))
return seq
def longest(max):
min = 0
value = 0
seq_len = dict()
for n in range(2, max + 1):
s = n
seq = [s]
while s != 1:
if s in seq_len:
seq_len[n] = len(seq) + seq_len[s]
break
else:
if s % 2 == 0:
s = s / 2
else:
s = 3 * s + 1
seq.append(int(s))
if s == 1:
seq_len[n] = len(seq)
if min < len(seq):
min = len(seq)
value = n
return n, min
| true |
78c9088884aaae4114378d8412fc178ff9d294ce | KaueGuimaraes/Python-Begin-Exercises | /ex016.py | 895 | 4.34375 | 4 | print('========= DESAFIO 016 =========\n')
n = float(input('Digite um número (não inteiro): '))
nn = int(n)
print('\nO valor digitado foi {} e a sua porção inteira é {} '.format(n, nn))
print('\nFIM!!')
'''
English Version
print('========= CHALLENGE 016 =========\n')
n = float(input('Type a number (not whole): '))
nn = int(n)
print('\nThe value entered is {} and its wholes portions is {} '.format(n, nn))
print('\nEND!!')
'''
'''
Desafio: Crie um programa que leia um número Real qualquer pelo teclado e
mostre na tela a sua porção inteira
Ex: Digite um número: 6.127
O número 6.127 tem a parte inteira 6.
Challenge: Write a program that reads a float number in the KeyBoard and
shows on the screen its whole portions.
EX: Type a number: 6.127
The number 6.127 have a whole potions 6.
''' | false |
f303e96e2d065c74181428416ff5119ededea062 | KaueGuimaraes/Python-Begin-Exercises | /ex014.py | 601 | 4.125 | 4 | print('========= DESAFIO 014 =========\n')
c = float(input('Informe a temperatura em °C'))
f = ((9 * c) / 5) + 32
print('\nA temperatura dee {}°C corresponde a {}°F'.format(c, f))
print('\nFIM!!')
'''
English Version
print('========= CHALLENGE 014 =========\n')
c = float(input('Enter the temperature in °C'))
f = ((9 * c) / 5) + 32
print('\nThe temperature of {}°C corresponds to {}°F'.format(c, f))
print('\nEND!!')
'''
'''
Desafio: Escreva um programa que converta uma temperatura digitada em °C para °F.
Challenge: Write a program that converts a temperature in °C to °F.
''' | false |
46a094f5de1dbc83dfa67094bd1bf8fc4af87fc4 | KaueGuimaraes/Python-Begin-Exercises | /ex004.py | 914 | 4.34375 | 4 | print('========= DESAFIO 004 =========\n')
letra = input('Digite algo: ')
print('\nÉ um número? ', letra.isnumeric())
print('É alfabético? ', letra.isalpha())
print('É alfanúmerico? ', letra.isalnum())
print('Está em maiúsculo? ', letra.isupper())
print('Está em minúsculo? ', letra.islower())
print('\nFIM!!')
'''
print('========= CHALLENGE 004 =========\n')
letra = input('Type Something: ')
print('\nIs numeric? ', letra.isnumeric())
print('Is alpha? ', letra.isalpha())
print('Is alpha numeric? ', letra.isalnum())
print('Is upper? ', letra.isupper())
print('Is lower? ', letra.islower())
print('\nEND!!')
'''
'''
Desafio: Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.
Challenge: Make a program that reads something on the KeyBoard and shows, its primitive type and all possible information about it.
'''
| false |
c13acce370eb3a31cd3fb1266ff72dcb8cd1616b | KaueGuimaraes/Python-Begin-Exercises | /ex001.py | 733 | 4.15625 | 4 | print('========= DESAFIO 001 =========')
print()
nome = input('Qual é o seu nome? ')
print('Seja bem vindo' + nome + ' este é o meu primeiro Script Python!')
print()
print('FIM!!')
'''
English Version
print('========= CHALLENGE 001 =========')
print()
name = input('What is your name? ')
print('Wellcome' + name + ' this is my firt Python Script!')
print()
print('END!!')
'''
'''
Desafio : Crie um programa que escreva "Olá mundo" na tela
Era somente para eu dizer "Olá mundo", mas eu fiz mais do que o professor pediu(eu nem lembro o porque disso).
Challenge : Do a python cript that can write "Hello World"
I was just supposed to say "Hello world", but I did more than the teacher asked (I don't even remember why).
'''
| false |
4204ef382bd3144b4a49e266f25dd26859922887 | CaptainSundae/UOA-Compsci-101 | /Lab 08/Lecture21ExampleCode/changecase.py | 2,293 | 4.46875 | 4 |
def change_case(sentence,my_type):
"""Returns the sentence in uppercase or lowercase depending on the type requested
Arguments:
sentence - sentence to be transformed
mytype - either "upper" or "lower"
Returns:
sentence transformed to upper or lower case
>>> change_case("rock","upper")
'ROCK'
>>> change_case("PAPER","lower")
'paper'
>>> change_case("pApEr","upper")
'PAPER'
>>> change_case("rock","lower")
'rock'
>>> change_case("PapeR","lower")
'paper'
>>> change_case("","upper")
''
>>> change_case("","fred")
''
>>> change_case("Can we dO a WHole Sentence","upper")
'CAN WE DO A WHOLE SENTENCE'
"""
uppercase = ["A","B","C","D","E","F","G","H",
"I","J","K","L","M","N","O","P",
"Q","R","S","T","U","V","W","X","Y","Z"]
lowercase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
new_sentence = ""
for i in range(0,len(sentence)):
if ((my_type == "upper" and
sentence[i] in lowercase) or
(my_type == "lower" and
sentence[i] in uppercase)):
new_sentence += get_new_letter(sentence[i],my_type)
else:
new_sentence += sentence[i]
return new_sentence
def get_new_letter(letter, my_type):
"""Returns letter in uppercase or lowercase depending on my_type
Arguments:
sentence - letter to be transformed
my_type - either "upper" or "lower"
Returns:
letter transformed to upper or lower case
>>> get_new_letter("r","upper")
'R'
>>> get_new_letter("P","lower")
'p'
"""
uppercase = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lowercase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
if my_type == "upper":
for i in range(0,len(lowercase)):
if lowercase[i] == letter:
return uppercase[i]
else:
for i in range(0,len(uppercase)):
if uppercase[i] == letter:
return lowercase[i]
import doctest
doctest.testmod()
| false |
61578097f5b156761faf5af4f7e284ea808ab4b9 | davicosta12/python_work | /Part_01/Cap_03/Lista_remoção.py | 1,362 | 4.21875 | 4 | #USANDO O MÉTODO DEL --> Exclui o elemento da lista, sem se preocupar com a reutilização dele na lógica seguinte. Nos precisamos saber a posição do elemento, quando usasmos del
#motorcycles = ['honda', 'yamaha', 'suzuki']
#print('\n' + str(motorcycles))
#del motorcycles[0]
#print(motorcycles)
#del motorcycles[1]
#print(motorcycles)
#USANDO O MÉTODO POP --> Exclui o elemento da lista, se preocupando com a reutilização dele na lógica seguinte. Não precisamos saber necessariamente a posição do elemento na lista.
#motorcycles = ['honda', 'yamaha', 'suzuki']
#print(motorcycles)
#popped_motorcycle = motorcycles.pop()
#print(motorcycles)
#print(popped_motorcycle)
#Utilidade do método pop -- podemos definirar com o índice que queremos trabalhar
#motorcycles = ['honda', 'yamaha', 'suzuki']
#last_owned = motorcycles.pop()
#print("The last motorcycle I owned was a " + last_owned.title() + ".")
# USANDO O MÉTODO REMOVE --> Exclui o elemento da lista, se preocupando com a reutilização dele na lógica seguinte. Precisamos saber somente o conteúdo e não o indice.
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.")
| false |
047897d1046a53fa92955cdc850b0cc767f95af9 | inotives/python-learnings | /common-data-structures/_2_array_data_structures.py | 1,947 | 4.53125 | 5 | #!/usr/bin/python
'''
list - mutable dynamic arrays (can be added or removed
'''
print('LIST EXAMPLE::')
arr = ['one', 'two', 'three']
print(arr[0])
print(arr)
print('list are mutable:')
arr[1] = 'Changed'
print(arr)
del arr[1]
print(arr)
print("list can hold arbitrary data types:")
arr.append(23)
print(arr)
'''
tuple - immutable containers (cant be removed or added, only can be defined at creation time)
'''
tuplearr = 'one', 'two', 'three'
print(tuplearr[0])
print(tuplearr)
'''
array.array - Typed Arrays, more space efficient compare to lists and tuples. Array stored are tightly packed.
useful when storing same type elements.
'''
from array import array
arr_arr = array('f', (1.0, 1.5, 2.0, 2.5))
print(arr_arr[1])
print(arr_arr)
print('array are mutable:')
arr_arr[1] = 23.0
print(arr_arr)
del arr_arr[1]
print(arr_arr)
arr_arr.append(44)
# arr_arr[1] = 'hello' # array are typed - TypeError: a float is required
'''
str - immutable arrays of unicode characters (in python 3.x)
str object are space-efficient bcause they are tightly packed and specialize in a single data-type. if you are storing unicode text,
you should use them. because str are immutable in python, modifying them requires creating a modified copy.
'''
arr_str = 'abcd'
print(arr_str[1])
print(arr_str)
print("String are immutable: ")
# arr_str[1] = 'e' # 'str' object doesnot support item deletion
print("String can be unpack into a list to get a mutable representation")
print(list(arr_str))
print(''.join(list(arr_str)))
print("String are recursive data structures: ")
print(type('abc'))
print(type('abc'[0]))
'''
bytes - immutable arrays of single bytes
similar to str objects. they are space-efficient, immutable, but unlike str, they are dedicated "mutable by array" data type called bytearray
that can be unpacked into.
'''
arr_byte = bytes((0, 1, 2, 3))
print(arr_byte[1])
# bytes literals have their own syntax:
print(arr_byte)
print(type(arr_byte))
| true |
78347f1d003d3ef66daacebdef2e74c452c24539 | inotives/python-learnings | /classes-and-oop/_4_cloning_objects.py | 1,186 | 4.34375 | 4 | #!/usr/bin/python
'''
Shallow Copy
-------
Constructing new collection of objects and then populating it with references to the child objects found in the original.
This mean it is only 1-level deep which the copying process does not recurse and child objects copies wont be created.
'''
xs = [[1,2,3], [4,5,6], [7,8,9]]
ys = list(xs) # make a shallow copies
print "XS:", (xs)
print "YS:", (ys)
print "adding sublist to XS"
xs.append(["New Item"])
print "XS:", (xs)
print "YS:", (ys)
print "but because the child reference of YS is the same as XS, if changes was made to XS child object, YS will get affected."
xs[1][0] = 'X'
print "XS:", (xs)
print "YS:", (ys)
'''
Deep Copy
-------
Deep copy makes the copying process recursive. First construct a new collection object then recursively populate it with
the copies of the child object found in the original. The result copied object will be a complete independent copies.
'''
print "\n\nDEEP COPY Example"
import copy
xa = [[1,2,3], [4,5,6], [7,8,9]]
za = copy.deepcopy(xa)
print "XA:", xa
print "ZA:", za
print "with deepcopy, if changes was made to XA, ZA wont get affected."
xa[1][0] = "XX"
print "XA:", xa
print "ZA:", za
| true |
6daa5d960fbe319b3faefd6159aa177dc2cfc34e | justin-crabtree/uni_mich_getting-started-python | /romeo_text_sort.py | 591 | 4.1875 | 4 | # Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.
fileHandle = open('romeo.txt')
lst = list()
for line in fileHandle:
words = line.rstrip().split()
lst.append(words)
lst = lst[0] + lst[1] + lst[2] + lst[3]
lst.sort()
new_list = list(dict.fromkeys(lst))
print(new_list)
| true |
4b6cc71ac5978188c2d9c90227d9ef2da3586435 | alecodigo/Python | /validateakey.py | 1,447 | 4.15625 | 4 | # -*- coding: utf-8 -*-
import sys
PASSWORD = ''
def create_password():
global PASSWORD
pwd = input("Enter your new password: ")
confir_pwd = input("Confirm you password: ")
if pwd == confir_pwd:
print("Success")
PASSWORD = confir_pwd
else:
print("Error in password try again.")
def change_password():
global PASSWORD
if PASSWORD:
current_pwd = input("Enter current password: ")
if PASSWORD == current_pwd:
new_passwd = input("Enter a new password: ")
PASSWORD = new_passwd
print(PASSWORD)
else:
print("Current password is not valid.")
else:
print("You don't have any password set.")
def menu():
password = input(""" Configuration Menu
Press [1] to create a new password
Press [2] to change password
Press [Q] to exit
""")
return password
if __name__ == '__main__':
# Menu
while True:
password = menu()
if password.isdecimal():
if password == '1':
create_password()
elif password == '2':
change_password()
elif password == 'Q':
break
else:
print("Enter only numbers")
#sys.exit()
#break
print("\n")
print("Thanks for use our services.")
| true |
3bfe8c3e58412724d29d594d153bc8240163f2be | mgalactico/substring | /substring.py | 1,177 | 4.15625 | 4 | # Prints longest substring in which letters appear in alphabetical order
s = 'azcbobobegghakl'
n = len(s)
i = 1
currentString = ''
largestString = s[i - 1] # initializes string to first char in string
currentLetter = ''
nextLetter = ''
# Loop over length of s
while i < n:
currentLetter = s[i - 1]
nextLetter = s[i]
# Loop to build substring
while nextLetter >= currentLetter:
if len(currentString) == 0: # Begin of currentString
currentString = currentLetter + nextLetter
elif len(currentString) != 0: # Grow currentString
currentString = currentString + nextLetter
if (i + 1) < n: # counter is only increased if within boundaries of s's length
i += 1
currentLetter = s[i - 1]
nextLetter = s[i]
else:
break
# Compares two strings and replaces one with other
if len(currentString) > len(largestString):
largestString = currentString
# resets current string and increases counter to move to next character
currentString = ''
i += 1
# print largest string
print('Longest substring in alphabetical order is:', largestString)
| true |
3b7039d8350ee851d294cb4b07e02df5db75a72d | MmeKelain/interview-solver | /overused-coding-questions/linked_list_cycle.py | 1,582 | 4.21875 | 4 | def overused_linked_list_cycle(linked_list):
""
Returns true if a cycle exists, false otherwise.
Arguments:
linked_list -- a data structure that should never contain a cycle. Assume a linked_list is an object comprised of node objects, each containing a pointer to the next node called 'next'.
""
nodes = [] # create list[Node]
current_node = linked_list.head # start with head node
while(current_node.next != None): # until the linked_list ends
if current_node not in nodes:
nodes.append(current_node) # put the node in the list
else:
return True
current_node = current_node.next
return False
# alternately, use the built-in Linked_List class to cheat
return linked_list.is_broken
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class Linked_List:
def __init__(self):
self.current_node = None
self.head = None
self.is_broken = False
def add_node(self, data):
if self.head == None:
self.head = Node(data, None)
self.current_node = self.head
else:
new_node = Node(data, self.current_node)
self.current_node = new_node
def add_cycle(self, cycle_node):
last_node = self.head
while last_node.next != None:
last_node = last_node.next
last_node.next = cycle_node
self.is_broken = True
| true |
1c2b0e507fb4e431235ed56484b47743a26310e4 | hdmcspadden/CS5010 | /Module05/primes_fail1.py | 1,154 | 4.5 | 4 | # File: primes_fail1.py
# CS 5010
# Learning Python (Python version: 3)
# Topics:
# - Unit testing / debugging code
# - Using primes example
# - **inserting errors to show how primes_test can fail**
def is_prime(number):
# Return True if *number* is prime
#if number < 0: # Negative numbers are not prime
# return False
#if number in (0, 1): # The numbers 0 and 1 are not prime
# return False
# Above two if-statements could be replaced by following single if-statement
# However, above two if-statements are kept for clarity for this example
#if number <= 1:
# return False
for element in range(number): # starts at 0 ...!
if number % element == 0: # ... therefore modulo zero is an error!
return False
return True # Otherwise... return True, the number IS a prime
# ======================================================
def print_next_prime(number):
# Print the closest prime number larger than *number*
# Returns a single numerical value
index = number
while True:
index += 1
if is_prime(index):
return index
| true |
8317695c37f954c11bb04810a427b47d0bd518e5 | Arup-Paul8509/Python_Tutorials | /Tkinter/Tutorial/03_2_Grid_method.py | 1,680 | 4.5 | 4 | '''
***Python Tkinter grid() method***
The grid() geometry manager organizes the widgets in the tabular form. We can specify the
rows and columns as the options in the method call. We can also specify the column span (
width) or rowspan(height) of a widget.
This is a more organized way to place the widgets to the python application. The syntax to
use the grid() is given below.
Syntax:widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
1.Column
The column number in which the widget is to be placed. The leftmost column is represented by 0.
2.Columnspan
The width of the widget. It represents the number of columns up to which, the column is expanded.
3.ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's border.
4.padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
5.row
The row number in which the widget is to be placed. The topmost row is represented by 0.
6.rowspan
The height of the widget, i.e. the number of the row up to which the widget is expanded.
7.Sticky
If the cell is larger than a widget, then sticky is used to specify the position of the
widget inside the cell. It may be the concatenation of the sticky letters representing
the position of the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
'''
from tkinter import *
root=Tk()
id=Label(root,text="User Id : ")
id.grid(row=0,column=0)
e1=Entry(root)
e1.grid(row=0,column=1)
password=Label(root,text="Password : ")
password.grid(row=1,column=0)
e2=Entry(root)
e2.grid(row=1,column=1)
btn=Button(root,text="Log in")
btn.grid(row=4,column=0)
root.mainloop() | true |
90574be944f57d47ea1fdf12b31825eebc77659b | Arup-Paul8509/Python_Tutorials | /NumPy/1_NumPy Array/02_NumPy_Array_function_Creation.py | 360 | 4.125 | 4 | '''
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
'''
import numpy as np
arr1=np.array([1,2,3,4,5])#array created with list
arr2=np.array((1,3,5,7,9))#array created with tuple
print(arr2)
print(type(arr2))#type() returns type of object passes to it | true |
9a031cf6a2566bc4742ec04abbd2ed9748f4140a | Arup-Paul8509/Python_Tutorials | /NumPy/1_NumPy Array/17_Sorting _arrays.py | 234 | 4.125 | 4 | '''
The NumPy ndarray object has a function called sort()
that will sort a specified array.
'''
import numpy as np
arr1=np.array([3,2,0,1]);
print(np.sort(arr1))
#sorting 2D array
arr2=np.array([[3,2,4],[5,0,1]])
print(np.sort(arr2)) | true |
302df82f6aeed33ff02b005d78ad44a4fd479b61 | kedar-naik/markets | /sorting/selection.py | 2,024 | 4.375 | 4 | """
this script implements selection sort
"""
import numpy as np
# -----------------------------------------------------------------------------#
def selection_sort(numbers):
"""
given a list or array of numbers, this function will sort the numbers in
ascending order using selection sort. this algorithm is good if the cost of
doing a swap is high, since there is only one swap per run-through
space: O(1) extra
time: O(n^2)
"""
# count up the number of elements in the list
n = len(numbers)
# run through the list
for i in range(n):
# in the portion of the list spanning indices i through n-1, find the
# location of the minimum value. (this is just an argmin operation.)
# start by initializing the location of the minimum to be i itself
min_index = i
# now, run through the numbers in front of i and see if any are smaller
for j in range(i+1, n):
# if there's a smaller number than the smallest one already seen,
# then it's index is the new minimum location
if numbers[j] < numbers[min_index]:
min_index = j
# once the location of the minimum has been found, pull out that value
# for a second
min_value = numbers[min_index]
# put the i-th value where the min value was
numbers[min_index] = numbers[i]
# and put the minimum value at index i
numbers[i] = min_value
# n.b. you don't need to return the array here, since the array itself is
# being altered by having been run through this function
# --------------------------------------------------------------------------- #
# make a list of 9 random values between 0 and 100
values = 100 * np.random.randn(9)
# print out the values before sorting
print('\n selection sort:')
print('\n\t- original list:\n\t ', values)
# sort the values using selection sort
selection_sort(values)
# print out the sorted values
print('\n\t- sorted list:\n\t ', values)
| true |
b992b3ced67c24fa5ad76f59c954377d07e1a23b | rocketpunch-dev/euler | /python/problems_112.py | 762 | 4.15625 | 4 | def is_bouncy(number):
is_increasing = False
is_decreasing = False
str_number = str(number)
check_num = str_number[0]
for s in str_number[1:]:
if int(check_num) < int(s):
is_increasing = True
elif int(check_num) > int(s):
is_decreasing = True
check_num = s
if is_increasing and is_decreasing:
return True
return False
def bouncy_rate(rate):
bouncy_count = 0
total_count = 1
number = 1
while rate > (bouncy_count / total_count) * 100:
number += 1
# print(bouncy_count / total_count)
if is_bouncy(number):
bouncy_count += 1
total_count += 1
print(number)
if __name__ == "__main__":
bouncy_rate(99)
| false |
169df8953d7cd778e2a02ecaf36e66ce944ec4a1 | Chinon93/python-programming | /Unit1/variables.py | 1,428 | 4.1875 | 4 | def main():
first_name = "Chinonso"
last_name = "Ibekwe"
full_name = first_name + " " + last_name
print(full_name)
#boolean variable
neha_has_a_big_head = True
#null/none variable (no value; value is missing completely)
cars = None
#modulus operator (mostly used with integers; tests if number is odd or even)
def conditionals():
#given a range of grades 0 - 100
#if grade is between 80 and 100 - print "A"
#if grade is between 60 and 79 - print "B"
# grade is between 50-59 - print "C"
# if grade is 0-49 - print "You're a dummy lol"
grade = 49
if grade >= 80:
print("A")
elif grade >= 60:
print("B")
elif grade >=50:
print("C")
else:
print("You're a dummy lol")
def fizzbuzz():
'''
for the number 1 to 50
print 'fizz' if the number is a multiple of 3
print 'buzz' if the number is a multiple of 5
print 'fizzbuzz' if the number is a multiple of 15
otherwise print number
'''
# use range for this
# range()
#for num in range()
#print num
# used % to find if number is a multiple of 3 or 5
for num in range(1, 51):
if num%3 == 0 and num%5 == 0:
print("fizzbuzz")
elif num%3 == 0:
print("fizz")
elif num%5 == 0:
print("buzz")
else:
print(num)
if __name__ == "__main__":
fizzbuzz()
| true |
0a3757112f2c24c0ee9348e864632b21db7772aa | samuelheg/AlgorithmieAvancee | /s1/semaine_1/semaine_1/exercice_1.py | 1,997 | 4.4375 | 4 | """
1. Coder un algorithme pour calculer la moyenne d'un tableau en utilisant une boucle while
2. Modifier l'algorithme pour qu'il n'incrémente pas i
2.1 Est-ce qu'il finit ?
3. Modifier l'algorithme initial pour qu'il divise la valeur par n dans la boucle au contraire de faire à la fin
3.1 Est-il correct ?
"""
def moy_tableau_1(A: list):
"""
calcule la moyenne d'un tableau en utilisant une boucle while
:param A: tableau de réel
:return: moy:float la moyenne
"""
moy: float = 0 # resultat
n: int = len(A) # taille du tableau
somme: float = 0 # somme des valeurs du tableau
i: int = 0
##### à coder #####
if n > 0:
while i < n:
somme += A[i]
i += 1
##### fin code #####
moy = somme/n
return moy
def moy_tableau_2(A: list):
"""
calcule la moyenne d'un tableau en utilisant une boucle while
:param A: tableau de réel
:return: moy:float la moyenne
"""
moy: float # resultat
n: int = len(A) # taille du tableau
somme: float = 0 # somme des valeurs du tableau
i: int = 0
##### à coder #####
if n > 0:
while i < n:
somme += A[i]
moy = somme/n
##### fin code #####
return moy
def moy_tableau_3(A: list):
"""
calcule la moyenne d'un tableau en utilisant une boucle while
:param A: tableau de réel
:return: moy:float la moyenne
"""
moy: float # resultat
n: int = len(A) # taille du tableau
somme: float = 0 # somme des valeurs du tableau
i: int = 0
##### à coder #####
if n > 0:
while i < n:
somme += A[i]
i+=1
moy = somme/n
##### fin code ####
return moy
if __name__ == "__main__":
A: list = [3.5, 4.5, 2.0, 6.0]
#moy = moy_tableau_1(A) # question 1.
#moy = moy_tableau_2(A) # question 2.
moy = moy_tableau_3(A) # quesiton 3.
print("moyenne =", moy)
| false |
da0715ca6d97b1121682ebd9b316712e13e6bb8c | firasbk/python_samples | /numbers_exercise.py | 282 | 4.5 | 4 | radius = float ( input ( "Please enter the radius of the circle: ") )
import math
area = math.pi * ( radius ** 2 )
circumference = 2 * math.pi * radius
print("The area of the circle is: ", round(area,2) )
print("The circumference of the circle is: ", round(circumference,2) )
| true |
8d2424953443ae31cc9765c1622e74545ba2a254 | KyleADeGuzman/UHSComputerScience1 | /Assignment1/KyleD.Assignment1.py | 2,417 | 4.34375 | 4 | # 1
lastName= raw_input("what is your lastname? ")
firstname= raw_input("what is your first name? ")
print("Hello there! " + lastName + ", " + firstname)
# 2
# Write a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them
# the year that they will turn 100 years old.
age=int(raw_input("What is your current age?"))
currentyear=int(raw_input("What is the current year?"))
yearsto100=int(100-age)
futureyear=currentyear+yearsto100
year=str(futureyear)
print("You will turn 100 in the year " + year)
print(currentyear+yearsto100)
# 3
# Write a program that asks the user to enter 2 numbers to divide.
# Print out a message telling them what the remainder is.
divide1= input("What is the number you want to divide? ")
divide2= input("What is the number you want to divide by? ")
divide3= divide1%divide2
print(str(divide1) + " divided by " + str(divide2) + " will have a reminder of " + str(divide3))
# 4
# Write a program that asks the user to enter a word
# and how many times they want the word to be repeated.
# Print that word to the screen as many times as they requested.
word= raw_input("Give me a word: ")
amount= input("How many times do you want me to print it? ")
print(str(word+" ")*amount)
# 5
# Write a program that asks the user to enter
# the length and width of a rectangle.
# Print out a message telling them what the area and perimeter are.
length= input("What is the length of the rectangle ")
width= input("What is the width of the rectangle ")
perimeter= (length+length+width+width)
area= (length*width)
print("The perimeter of your rectangle is " + str(perimeter) + " units. The area is " + str(area) + " units squared.")
# 6
# Write a program that asks the user to enter the diameter
# of a circle. Print out the circumference and area of the circle.
diameter= input("What is the diameter of the circle? ")
radius = (diameter/2)
circumference = (2*3.14*radius)
area= (3.14*radius**2)
print("The circumference is " + str(circumference) + " units and the area is " + str(area) + " units squared")
# 7
# Write a program that asks the user to enter
# the year in which they were born. Print out a message telling them how old they are
birthYear= input("What year were you born? ")
age=(2019-birthYear)
print("Since you were born in " + str(birthYear) + " you are probably " + str(age))
'''
7/7 Nice work.
'''
| true |
3a5870bc34171034bbea4b5d93d6c1bd626fa8ad | MohamadHaziq/100-days-of-python | /day_1-10/day_7/hangman.py | 745 | 4.125 | 4 | import random
import hangman_art
from word_list import word_list
stages = hangman_art.stages
## List of possible words
chosen_word = random.choice(word_list)
display = ['_'] * len(chosen_word)
lives = 6
print(lives)
while "_" in display and lives > 0:
letter = input('Guess a letter !').lower()
for position in range(len(chosen_word)):
if letter == chosen_word[position]:
display[position] = letter
if letter in display:
print (f"You already chose {letter}")
if letter not in chosen_word:
lives -= 1
print(stages[lives])
print(display)
if "_" not in display:
print ("You win")
else:
print ("Loser")
print ("Game over !")
print (f"The word was {chosen_word}") | true |
c6f8149d9eb4d3d70c10625c13d9f451031c33f1 | Neminem1203/Puzzles | /DailyCodingProblem/29-runLengthEncode.py | 1,279 | 4.34375 | 4 | '''
Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
'''
testEncode = "AAAABBBCCDAA"
testDecode = "4A3B2C1D2A"
def rLEncode(code, type):
output = ""
copyOfcode = code
if(type == "Encode"):
char = ""
charCount = 0
while(copyOfcode):
if char == '':
char = copyOfcode[0]
charCount += 1
elif char != copyOfcode[0]:
output += str(charCount) + char
char = copyOfcode[0]
charCount = 1
else:
charCount += 1
copyOfcode = copyOfcode[1:]
output += str(charCount) + char
if(type == "Decode"):
while(copyOfcode):
output += copyOfcode[1] * int(copyOfcode[0])
copyOfcode = copyOfcode[2:]
return output
print(rLEncode(testEncode, "Encode"))
print(rLEncode(testDecode, "Decode"))
| true |
3573f19ab381bb02ff542b2647463d905bfea570 | Neminem1203/Puzzles | /DailyCodingProblem/49-maxContiguousSum.py | 710 | 4.1875 | 4 | '''
Given an array of numbers, find the maximum sum of any contiguous subarray of the array.
For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86.
Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any elements.
Do this in O(N) time.
'''
def maxContiguousSum(array):
maxSum = 0
sumSoFar = 0
for num in array:
sumSoFar += num
if(sumSoFar < 0):
sumSoFar = 0
continue
if(maxSum < sumSoFar):
maxSum = sumSoFar
return maxSum
print(maxContiguousSum([34, -50, 42, 14, -5, 86]))
print(maxContiguousSum([-5, -1, -8, -9])) | true |
a7458f83f76e499b5189c46e751c160218e1cf87 | Neminem1203/Puzzles | /DailyCodingProblem/32-currencyConversion.py | 1,817 | 4.1875 | 4 | '''
Suppose you are given a table of currency exchange rates, represented as a 2D array. Determine whether there is a possible arbitrage: that is, whether there is some sequence of trades you can make, starting with some amount A of any currency, so that you can end up with some amount greater than A of that currency.
There are no transaction costs and you can trade fractional quantities.
'''
currencyNames = ['USD', 'CAD', 'YEN', 'RUB', 'EUR']
currencyArray = [
[1, 1.31, 108.31, 63.00, 0.89], # USD
[0.76, 1, 82.74, 48.13, 0.68], # CAD
[0.0092, 0.012, 1, 0.58, 0.0082], # YEN
[0.016, 0.020, 1.72, 1, 0.014], # FAKE RUB
# [0.016, 0.021, 1.72, 1, 0.014], # RUB
[1.12, 1.47, 121.37, 70.60, 1] # EUR
] # real prices at time of program 7/16/19 20:34
# Fake RUB was created because RUB -> USD -> RUB and RUB -> CAD -> RUB (without fees) are instant answers
possibilities = 0
def currencyConversion(targetCurrency, amount=1, listOfCurrencies=[]):
global possibilities
# print(amount, listOfCurrencies)
if(listOfCurrencies == []):
listOfCurrencies = [targetCurrency]
if(amount * currencyArray[listOfCurrencies[-1]][targetCurrency] > 1):
possibilities += 1
for i in listOfCurrencies:
print(currencyNames[i], " -> ", end="")
print(currencyNames[targetCurrency])
return # This makes sure you don't have a bunch of repeating results
for i in range(0, len(currencyArray)):
if(i not in listOfCurrencies):
currencyConversion(targetCurrency, amount*currencyArray[listOfCurrencies[-1]][i], listOfCurrencies+[i])
targetCurr = 0
currencyConversion(targetCurr)
print("Possibilities: ",possibilities)
| true |
ecda9a22b4d510e8c8ad3908a4c372b9ea0a467d | Neminem1203/Puzzles | /DailyCodingProblem/34-palindromeInsert.py | 2,170 | 4.25 | 4 | '''
Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically).
For example, given the string "race", you should return "ecarace", since we can add three letters to it (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically.
As another example, given the string "google", you should return "elgoogle".
'''
def palindromeInsert(word):
checkInd = 0
newWord = ""
dupeWords = []
for i in word:
newWord += i
while(checkInd < len(newWord)):
if newWord[checkInd] in newWord[checkInd:]:
for ind in range(len(newWord)-1, checkInd, -1):
if(newWord[ind] == newWord[checkInd]):
dupeWords += [newWord[checkInd]]
newWord = newWord[:checkInd] + newWord[(checkInd+1):ind] + newWord[(ind+1):]
checkInd -= 1
break
checkInd += 1
palindrome = ""
while(dupeWords != [] and newWord != ""):
if(word[-1] == dupeWords[0]):
palindrome += dupeWords[0]
dupeWords = dupeWords[1:]
word = word[:-1]
continue
palindrome += newWord[-1]
newWord = newWord[:-1]
word = word[:-1]
if(dupeWords == []):
palindrome += newWord[-1:0:-1]
palindrome = palindrome + newWord[0] + palindrome[::-1]
if(newWord == ""):
for i in dupeWords:
palindrome += i
palindrome = palindrome + palindrome[::-1]
print(palindrome)
breakTest = "ramgrma" # This should be ramrgrmar but my program gives me grammarg which is completely wrong
# Idea: use a pivot point for the words if there's no pairs in the middle
secondTest = "ragamaror" #roramagamaror
palindromeInsert(breakTest)
palindromeInsert(secondTest)
palindromeInsert("google")
palindromeInsert("race")
palindromeInsert("ragaaz")
| true |
c052d1bdbab67f90d16cada85d8e90cfd74b84b9 | Neminem1203/Puzzles | /DailyCodingProblem/47-hindsightStockTrade.py | 723 | 4.125 | 4 | '''
Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it.
For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and sell it at 10 dollars.
'''
def stocktrade(company):
current_low = company[0]
profit = 0
for price in company:
if(price - current_low > profit):
profit = price-current_low
if(current_low > price):
current_low = price
return profit
print(stocktrade([9, 11, 8, 5, 7, 10]))
print(stocktrade([9, 20, 1, 5, 7, 11])) | true |
b66b7a2364ee0a85b1a02312ca6612663033a4ff | Kellytheengineer/Plotting-Graphs-in-Python | /function.py | 547 | 4.15625 | 4 | #Functions in Python
#Like in mathematics where a function takes an arguement and produces a result
#does so in Python as well !
#The general form of a Python function is:
#def function name(arguments):
# {Lines telling the function what to do to produce the result}
# return result
#Let's consider producing a function that return x^2 + y^2
def squared(x,y):
result = x**2 + y**2
return result
print(squared(10,2))
#A new function
def born(country):
return print("I am from " + country)
born("England") | true |
55b0801451db7915d07c2a094f462bdb969583c9 | DamienOConnell/MIT-600.1x | /Final_Exam/print_without_vowels.py | 522 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 4 14:20:57 2019
@author: damien
"""
def print_without_vowels(s):
"""
s: the string to convert
Finds a version of s without vowels and whose characters appear in the
same order they appear in s. Prints this version of s.
Does not return anything
"""
newstr = ""
vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
for char in s:
if char not in vowels:
newstr += char
print(newstr)
| true |
3b8c172962321c61a644fabab4e24362e64fb679 | DamienOConnell/MIT-600.1x | /Problem_Set_5/build_shift_dict.py | 1,222 | 4.34375 | 4 | #!/usr/bin/env python3
#
# -*- coding: utf-8 -*-
import string
# A = 65
# Z = 90
# a = 97
# z = 122
# ORD() IS THE REVERSE OF CHR()
def build_shift_dict(shift: int):
""" return a dictionary that maps all upper and lower alphabet letters
mapped to their Caesar cipher, shift by 'shift' characters
"""
lowerCaseLetters = list(string.ascii_lowercase)
lowerCaseCaesar = lowerCaseLetters[:]
upperCaseLetters = list(string.ascii_uppercase)
upperCaseCaesar = upperCaseLetters[:]
# shift lower case for Caesar ordering
for i in range(shift):
next = lowerCaseCaesar.pop()
lowerCaseCaesar.insert(0, next)
# shift upper case for Caesar ordering
for i in range(shift):
next = upperCaseCaesar.pop()
upperCaseCaesar.insert(0, next)
alphaList = lowerCaseLetters + upperCaseLetters
alphaCaesar = lowerCaseCaesar + upperCaseCaesar
caesarDict = {letter: value for letter, value in zip(alphaList, alphaCaesar)}
return caesarDict
print(build_shift_dict(2))
print("-" * 80)
print(build_shift_dict(24))
print("-" * 80)
print(build_shift_dict(26))
print("-" * 80)
print(build_shift_dict(53))
print("-" * 80)
| true |
974f14fface0264a97a219c23bd5311f3fb39420 | DamienOConnell/MIT-600.1x | /Week_1/int_to_binary.py | 428 | 4.25 | 4 | #!/usr/bin/env python3
entered = int(input("enter a number to convert to binary: "))
num = entered
if num < 0:
isNeg = True
else:
isNeg = False
num = abs(num)
result = ""
if num == 0:
result = 0
while num > 0:
result = str(num % 2) + result
num = num // 2
print("num so far: ", result, " num is now ", num)
if isNeg:
result = '-' + result
print("Integer: ", entered, " yields binary: ", result)
| true |
311587a8db2c28f9d850ee7c86425ea61b95cc00 | DamienOConnell/MIT-600.1x | /MidTerm_Exam/sumDigits.py | 324 | 4.21875 | 4 | #!/usr/bin/env python3
#
# -*- coding: utf-8 -*-
def sumDigits(N):
"""
recursive Python function, return the sum of its digits.
"""
if N >= 10:
return N % 10 + sumDigits(N // 10)
else:
return N % 10
print(sumDigits(1))
print(sumDigits(11))
print(sumDigits(126))
print(sumDigits(0))
| true |
5237a567cc0af876fcaf45507fb62019039dc19d | ryanthomasdonald/python | /week-2/lectures/stack.py | 2,491 | 4.25 | 4 | # RECURSION
# It's an algorithm.
# It's a function that calls itself.
# Call Stack:
# Global frame is its native/idle state
# Functions get "stacked" on top
# class Stack():
# def __init__(self):
# self.data = []
# self.length = 0
# def push(self, value):
# self.data.append(value)
# self.length += 1
# def pop(self):
# if self.length == 0:
# return None
# removed_item = self.data.pop()
# self.length -= 1
# return removed_item
# def peek(self):
# if self.length == 0:
# return None
# return self.data[self.length - 1]
# stack = Stack()
# look up "balanced brackets python" (Google)
# def call_me():
# call_me() # This is a "stack overflow"
# call_me()
# Recursion how-to:
# 1. Define a base case
# 2. Identify a recursive case
# 3. Return when appropriate
# Lab 1:
# Write a function called power which accepts a base and an exponent.
# The function should return the power of the base to the exponent.
def power(base, exponent):
# base case:
if exponent == 0:
return 1
return base * power(base, exponent - 1)
power(2, 4) # Should equal 16
# Lab 2:
# Write a function factorial which accepts a number and returns
# the factorial of that number. A factorial is the product of an
# interger and all the integers less than the starting integer. Factorial four (4!) is
# equal to 24, because 4 * 3 * 2 * 1 equals 24. Factorial zero (0!) is always 1.
def factorial(num):
if num == 0:
return 1
return num * factorial(num - 1)
print(factorial(4))
# 1
# 1 * factorial(0) | 1 * 1 = 1
# 2 * factorial(1) | 2 * 1 = 2
# 3 * factorial(2) | 3 * 2 = 6
# 4 * factorial(3) | 4 * 6 = 24
# factorial(4)
# Lab 3:
# Write a function called recursive_range which accepts a number and adds up all
# the numbers from 0 to the number passed to the function
def recursive_range(num):
if num == 0:
return 0
return num + recursive_range(num - 1)
print(recursive_range(6))
# 4. Write a recursive function called reverse which accepts
# a string and returns a new string in reverse
# 5. Write a recursive function called isPalindrome which returns
# true if the string passed to it is a palindrome (reads the same forward and backward).
# Otherwise returns false.
# 6. Write function called product_of_array which takes in
# an array of numbers and returns the product of them all | true |
57a5829e97b7afa2d56e4d543448c383b46c2eb9 | dvaqueroh/project_python | /tuplas01.py | 991 | 4.1875 | 4 | # tupla es una lista inmutable, NO SE PUEDE MODIFICAR
# al extraer una porcion, se crea una nueva dupla
# se puede comprobar si extiste un elemento
# nombreTupla( elem1, elem2, elem3...) como la lista pero con ( )
miTupla = ("David","Eva","Luis","Carmen","Luis")
print ( miTupla ) # muestra todo
print ( miTupla[2])
#convertir Tupla en Lista
miLista = list(miTupla)
# convertir Lista en Tupla
miTupla = tuple(miLista)
# cuantos elementos tiene la Tupla LEN
print ("cuantos elementos tiene la tupla?: ", len(miTupla))
# comprobar un elemento, si existe
print ("Luis esta en la Tupla? ","Luis" in miTupla)
# indice de un elemento
print (miTupla.index("Eva"))
# cuantas veces se repite un elementos
print ("cuantes veces esta Luis: ", miTupla.count("Luis") )
# Desempaquetado de Tupla, asignar elementos a variable
miTupla2 = ("David",2,"Enero",1985)
nombre,dia,mes,anio = miTupla2 #asigna los elementos a las variables
print(nombre,"nacio el dia ",dia," de ",mes," de ",anio) | false |
afbc0f86cf05352e5a3510e6c7939e343b132318 | micmor-m/Calculator | /main.py | 1,129 | 4.1875 | 4 | from art import logo
# Add
def add(n1, n2):
return n1 + n2
# Subtract
def subtract(n1, n2):
return n1 - n2
# Multiply
def multiply(n1, n2):
return n1 * n2
# Divide
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
}
def calculator():
print(logo)
running = "y"
is_first_loop = True
while running == "y":
num1 = float(input("What is the first number?: "))
# Print list of operation to user:
for operation in operations:
print(operation)
operation_symbol = (input("Pick an operation from the line above: "))
function = operations[operation_symbol]
if is_first_loop:
num2 = float(input("What is the second number?: "))
else:
num2 = result
result = function(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {result}")
running = input(f"Type 'y' to continue calculating with {result}, or type 'n' to exit: ")
is_first_loop = False
if running == "n":
calculator()
calculator()
| true |
ac5b811ac557aa8ff69abfe12b304437bf46fc3c | mkdika/learn-python | /basic/if-conditional.py | 675 | 4.125 | 4 | """
PYTHON CONDITIONAL:
1. if
2. if..else
3. expression condition
4. boolean operator
"""
family_name = "chandika"
if family_name == "chandika":
print('Good morning boss!')
age = 29
if age > 17:
print('permit to enter')
else:
print('age restriction')
# expression condition, ternary
birth_year = 1999
permission = 'Please Enter' if birth_year < 2000 else 'No Enter'
print(permission)
# boolean operator
if family_name == "chandika" and age < 20:
print("You are my young master")
elif family_name == "chandika" or birth_year > 1990:
print("Okay future master")
my_name = "john"
if my_name != "maikel":
print("Sorry, you're not my master")
| false |
e5ee0988bbe6350dbb9b7a7743e6f80c2d8a1071 | teoespero/PythonStuff | /Chapter-04/tuples-01.py | 767 | 4.28125 | 4 | # Python and tuples
# Teo Espero
# GIST I
# BOF
# defining a Tuple
my_tuple = ('leonard', 'westbrook', 'davis', 'james', 'curry', 'harden')
print('defining a Tuple')
print(my_tuple)
# creating a list
my_list = []
# initialize the list from the Tuple
print('initialize the list from the Tuple')
ctr = 0
for element in my_tuple:
my_list.insert(ctr, element.title())
ctr = ctr + 1
# print the list
print('print the list')
print(my_list)
# sort the list
print('sort the list')
my_list.sort()
# print the sorted list
print('print the sorted list')
print(my_list)
# store the sorted list in the current Tuple
print('store the sorted list in the current Tuple')
my_tuple = my_list
# print the sorted tuple
print('print the sorted tuple')
print(my_tuple)
# EOF
| true |
c8895aa4821f9a9785fc06f4d9378709831ffff9 | teoespero/PythonStuff | /Chapter-06/dictionaries-04.py | 925 | 4.21875 | 4 | # A list of dictionaries
# Teo Espero
# GIST I
# BOF
# define our list
alien_0 = {
'color': 'green',
'points': 5,
'power': ['telepathy', 'time travel']
}
alien_1 = {
'color': 'red',
'points': 10
}
alien_2 = {
'color': 'yellow',
'points': 15,
'power': ['invisibility', 'fly']
}
alien_3 = {
'color': 'pink',
'points': 20,
'power': ['electricity', 'stop time']
}
# define our dictionary containing our list
print('define our dictionary containing our list')
aliens = [alien_0, alien_1, alien_2, alien_3]
# print our aliens
print('print our aliens')
print(f'Our dictionary has {len(aliens)} aliens.')
for alien in aliens:
print(alien)
# add new items to the list
print('add new items to the list')
alien_0['speed'] = '100'
alien_1['speed'] = '200'
alien_2['speed'] = '300'
alien_3['speed'] = '400'
# print the new alien dictionary
for alien in aliens:
print(alien)
# EOF
| true |
331f2c8ebad4e9dc377e682d6c0c976d904500a3 | 121910314005/lab-1 | /l6.Node of list.py | 2,114 | 4.40625 | 4 | class Node:
def _init_(self,data):
self.data = data;
self.next = None;
class CreateList:
#Declaring head and tail pointer as null.
def _init_(self):
self.head = Node(None);
self.tail = Node(None);
self.head.next = self.tail;
self.tail.next = self.head;
#This function will add at the start of the list.
def addAtStart(self,data):
newNode = Node(data);
#Checks if the list is empty.
if self.head.data is None:
#If list is empty, both head and tail would point to new node.
self.head = newNode;
self.tail = newNode;
newNode.next = self.head;
else:
#Store data into temporary node
temp = self.head;
#New node will point to temp as next node
newNode.next = temp;
#New node will be the head node
self.head = newNode;
#Since, it is circular linked list tail will point to head.
self.tail.next = self.head;
#Displays all the nodes in the list
def display(self):
current = self.head;
if self.head is None:
print("List is empty");
return;
else:
print("Adding nodes to the start of the list: ");
#Prints each node by incrementing pointer.
print(current.data),
while(current.next != self.head):
current = current.next;
print(current.data),
print("\n");
class CircularLinkedList:
cl = CreateList();
#Adding 1 to the list
cl.addAtStart(1);
cl.display();
#Adding 2 to the list
cl.addAtStart(2);
cl.display();
#Adding 3 to the list
cl.addAtStart(3);
cl.display();
#Adding 4 to the list
cl.addAtStart(4);
cl.display();
OUTPUT:
Adding nodes to the start of the list:
1
Adding nodes to the start of the list:
2 1
Adding nodes to the start of the list:
3 2 1
Adding nodes to the start of the list:
4 3 2 1
| true |
d3fae9dd8e5b7538edcc0405847e6e06b17b6021 | malcabaut/AprendiendoPython | /100 Curso aulapharos/003 ListasTuplasDiccionarios/Listas.py | 1,097 | 4.375 | 4 | nombres = ["Pedro", "Juan", "Ana"] # Declarmos una lista de nombres.
nombres.append("Maria")# Agregamos un nombre.
print("La variable nombres es del tipo: "+str(type(nombres))
+" contiene "+str(nombres)
+" y su id en memoria es "
+ str (id(nombres)))
nombres.append("Eva")# Agregamos un nombre, y no se podifica su direcion de memoria
print("La variable nombres es del tipo: "+str(type(nombres))
+" contiene "+str(nombres)
+" y su id en memoria es "
+ str (id(nombres)))
#Imprimiendo partes de la lista
print("El primer elemento 0: "+nombres[0])
print("El ultimo elemento -1: "+nombres[-1])
nombres.append("Ana")# Agregamos un nombre.
print("La variable nombres es del tipo: "+str(type(nombres))
+" contiene "+str(nombres)
+" y su id en memoria es "
+ str (id(nombres)))
#Conocer el indice de de la primera Ana
print("El indice de Ana : "+str(nombres.index("Ana")))
#Modificamos un elemento:
nombres[-1]="Ali"
print("La variable nombres es del tipo: "+str(type(nombres))
+" contiene "+str(nombres)
+" Tiene "+str(len(nombres))+" elementos"
+" y su id en memoria es "
+ str (id(nombres)))
| false |
3607de3b41112931b7266704d0c20b7776fe715c | malcabaut/AprendiendoPython | /100 Curso aulapharos/001 VariablesInOutComentarios/TiposPrimitivos.py | 2,242 | 4.3125 | 4 | # No es neceario declarar el tipo de variables antes de asignarla.
####
# Tipos cadenas
####
nombre = 'Tiffany'
# Strings se crean con " o '
apellido = "Dolorido"
# Los strings se puede concadenar
print(nombre+" "+apellido)
# Se puede conocer el tipo de la variable con type(variable)
print(type(nombre)) # el tipo string es (str)
# Un string puede ser tratado como una lista de caracteres
print(nombre[0])
# % pueden ser usados para formatear strings
"%s pueden ser %s" % ("strings", "interpolados")
print("Nombre: %s\n Apellido: %s "%(nombre.upper()[0:5].replace('F','f'),apellido.lower()))
####
# Tipos numericos
####
entero = 45 # Tipos enteros (int)
# Puedes realizar traformaciones entre tipos distintos
print("El numero " + str(entero)+" es del tipo " + str(type(entero)))
flotante = 50.23 # Tipo flotantes (float)
print("El numero " + str(flotante)+" es del tipo " + str(type(flotante)))
complejo = 4 + 50.23j # Tipo complejos (complex)
print("El numero " + str(complejo)+" es del tipo " + str(type(complejo)))
####
# Tipos booleanos
####
continuarFlujo = True
continuarFlujo = False
print("Continuar Flujo es: "+str(continuarFlujo) +
" Que es de la clase: " + str(type(continuarFlujo)))
####
# Tipos lista
####
lista = ['texto', 45, 13.14, 4 + 2j, True]
print("Esto es un Array de varios tipos "+str(lista) +
" tipo en python: " + str(type(lista)))
lista[0] = "Cambio"
print("Esto es un Array de varios tipos "+str(lista) +
" tipo en python: " + str(type(lista)))
####
# Tipos tupla
####
tupla = ('texto', 45, 13.14, 4 + 2j, True)
print("Esto es un tupla de varios tipos "+str(tupla) +
" tipo en python: " + str(type(tupla)))
""" Esto no funcionaria ya que las tuplas no puede ser cambiadas.
tupla[0] = "Cambio"
print("Esto es un tupla de varios tipos "+str(tupla) +
" tipo en python: " + str(type(tupla)))
"""
####
# Tipos diccionarios
####
diccionario = {"rojo":"FF0000","verde":"00FF00","azul":"0000FF"}
print("Esto es un diccionario de colores "+str(diccionario) +
" tipo en python: " + str(type(diccionario)))
####
# Tipos vacio
####
celebro = None
print("Que hay en esta variable llamada celebro: "+str(celebro) +
" tipo en python: " + str(type(celebro))) | false |
a944d1fb9cc85f1761202598fe81c7f71ba9aec8 | Mojo2015/PythonFun | /Beginning Python for Dummies Practice/Lists/Sorting a list.py | 501 | 4.53125 | 5 | Colors = ["Red", "Orange", "Yellow", "Green", "Blue"] #Creates a list to the variable Color
for Item in Colors:
print(Item, end=" ") #This will print the list in the order they occur, end=" " makes sure the list prints to one line
print()
Colors.sort() #Simple, sorts the list in alphabetical order
Colors.reverse() #This will sort them in reverse alphabetical order, you need the sort command above it first
for Item in Colors:
print(Item, end=" ") #The items will be in order.
print()
| true |
8b7195f7fc7240ff87567f4f58f4c2832abe9883 | AnyKovarova/pyladies | /07/cesar.py | 1,452 | 4.125 | 4 | def caesar_encrypt (plaintext, key):
ciphertext = ''
for c in plaintext:
if c == ' ':
ciphertext = ciphertext + c
elif c.isupper():
ciphertext = ciphertext + chr((ord(c) + key - 65) % 26 + 65) # zašifruje velká písmena - hodnota "A" v ASCII je 65, ord() získá hodnotu ASCII a po odečtení hodnoty A zjistí fce chr() písmeno
else:
ciphertext = ciphertext + chr((ord(c) + key - 97) % 26 + 97) # zašifruje malá písmena - hodnota "a" v ASCII je 97, postup stejný jako u velkých písmen
return ciphertext
def caesar_decrypt (ciphertext, key):
decrypted = ' '
for c in ciphertext:
if c == ' ':
decrypted = decrypted + c
elif c.isupper():
decrypted = decrypted + chr((ord(c) - key - 65) % 26 + 65) # rozšifruje zpět, protože odstraní posun, takže zjistíme původní hodnoty (písmena)
else:
decrypted = decrypted + chr((ord(c) - key - 97) % 26 + 97)
return decrypted
print('Vítej ve skriptu pro Césarovu šifru!\n')
text = input('Zadej svůj text: ')
while True:
key = input('Zadej svoje tajné šifrovací číslo:')
try:
int(key)
except ValueError:
print('Musí to být celé číslo, zkus to znovu!')
else:
key = int(key)
break
print('Původní text:\n ', text)
print('Zašifrovaný text:\n ', caesar_encrypt(text, key))
print('Pro kontrolu zpět rozšifrováno:\n ', caesar_decrypt(caesar_encrypt(text,key),key))
| false |
c0e6a8ae3f283f90247c61210981ba3bc03f1711 | i1196689/GitPython | /python_lessons/day_01.py | 354 | 4.125 | 4 | #字符串与字符串之间的连接方式有5种。
###1.用 "+"
s1="hello"
s2="word"
s=s1+s2
print(s)
# 2 直接连接
s="hello""word"
print(s)
##3 ","连接
print("hello","word")
##4格式化
s="<%s> <%s>"%(s1,s2)
print(s)
##5 join
s=" ".join([s1,s2])
print(s)
#字符串与非字符串如何连接
#1 “+”
n=20
s=s1+str(n)
print(s)
#2 格式化
| false |
ea2e2c52133d5968d0e074a11de742ff8098b382 | candytale55/Practice_Makes_Perfect_Py_2 | /get_rid_of_vowels.py | 564 | 4.6875 | 5 | # function anti_vowel takes one string "text", as input and returns the text with all of the vowels removed.
# For example: anti_vowel("Hey You!") should return "Hy Y!". Don’t count Y as a vowel. Make sure to remove lowercase and uppercase vowels.
vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
def anti_vowel(text):
no_vowels = ""
for letter in text:
if letter not in vowels:
no_vowels += letter
return no_vowels
print anti_vowel("abcdefghi")
# https://discuss.codecademy.com/t/why-does-anti-vowel-fail-in-some-cases/339348
| true |
ab6df2284ed54f5a91eb512a13ffc4f4a54c76ad | candytale55/Practice_Makes_Perfect_Py_2 | /censor_a_word.py | 1,166 | 4.5 | 4 | # function _censor_ takes two strings, _text_ and _word_, as input.
# It should return the text with the word you chose replaced with asterisks.
# For example: censor("this hack is wack hack", "hack") should return "this **** is wack ****"
# Assume your input strings won’t contain punctuation or upper case letters.
# The number of asterisks you put should correspond to the number of letters in the censored word.
def censor (text, word):
word_list = text.split()
censored_word = "*"*len(word)
for i in range(len(word_list)):
if word_list[i] == word:
word_list[i] = censored_word
return " ".join(word_list)
print censor("hey hey mother fucker", "fucker")
# Other ways to create the censored word:
def censor_a_word_with_for(word):
censored_word = ""
for char in word:
censored_word += "*"
return censored_word
print censor_a_word_with_for("hellou")
# https://discuss.codecademy.com/t/how-can-i-use-split-to-make-censor/339351
# https://discuss.codecademy.com/t/why-do-we-need-to-use-a-count-variable-in-censor/346785
# https://discuss.codecademy.com/t/why-do-we-need-to-use-a-count-variable-in-censor/346785
| true |
4ffdba4441ca471d09e4b000db4860db828dd700 | JKinsler/lists_trees_graphs | /hash_table.py | 682 | 4.21875 | 4 | """Implement a hash table using only arrays."""
table = [None]*5
lst = ["hi", "amber", "yellow", "stone"]
pairs = {"hi": "a", "amber": "b", "yellow":"c", "stone":"d"}
def make_hash_table(pairs):
"""add values to the hash table"""
for item in pairs:
code = hash(item)
arr_val = code % len(table)
if table[arr_val] is None:
table[arr_val] = [[item, pairs[item]]]
else:
table[arr_val].append([item, pairs[item]])
return table
def look_up(key):
"""return the key's index in the hash table."""
return hash(key) % len(table)
if __name__ == '__main__':
print(make_hash_table(pairs))
| true |
122d72efd4e5722f965f75fd5c05c6fcc1d299fe | golubot/python_tutorial | /tutorial/tests/oop/DogsTestCase.py | 1,195 | 4.28125 | 4 | import unittest
from tutorial.solutions.oop.Dog import Dog
class MyTestCase(unittest.TestCase):
def test_dogs(self):
"""
Create dog class that will be used to instantiate different dog objects.
"""
my_schnauzer = Dog(breed="Schnauzer", name="Fido", spots=False)
type(my_schnauzer)
my_dalmatian = Dog(breed="Dalmatian", name="Chejs", spots=True)
type(my_dalmatian)
self.assertNotEquals(my_schnauzer, my_dalmatian)
self.assertTrue("Fido", my_schnauzer.name) # get name attribute
self.assertTrue("Fido", my_schnauzer.get_name()) # get name function
self.assertTrue("Chejs", my_dalmatian.get_name())
self.assertTrue("mammal", my_dalmatian.species) # should be class object attribute
self.assertTrue("mammal", Dog.species) # another way to access class object attributes
# Make Dog inherit Animal and write the same test against Animal. Don't forget to call the super constructor and pass the Dog reference to Animal
# Test if all Dog objects can eat if created this way
# Overwrite eating method to return "I am a dog eating"
if __name__ == '__main__':
unittest.main()
| true |
20f31409fb94f05979ed4f8f19f6c86b989eaeaa | consumerike/Fundamental_warm_ups | /dictionary_warmup.py | 876 | 4.46875 | 4 | #looping through all key-value pairs:
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print(key)
print(value)
#loop through all key-value pairs and print keys:
for key in user_0.keys():
print(key)
#looping through the keys only is the default behavior of looping
# through dictionaries thus this statement is equal to the one above
for key in user_0:
print(key)
#using the keys method to determine if a key is present in a dictionary:
fav_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
if 'erin' not in fav_languages.keys():
print('please take the quiz erin')
#sorted keys loop:
for name in sorted(fav_languages.keys()):
print(name)
#loop through all values:
for languages in fav_languages.values():
print(languages) | true |
4ffdf17b7982e04916e4af3b31195aa07dc61311 | ToddBenson/sample | /kata/exercise.py | 2,137 | 4.3125 | 4 | """
Create an object that returns the positions and the values of the "peaks"
(or local maxima) of a numeric array.
For example, the array arr = [ 0 , 1 , 2 , 5 , 1 , 0 ] has a peak in position 3
with a value of 5 (arr[3] = 5)
The output will be returned as an object with two properties: pos and peaks.
Both of these properties should be arrays. If there is no peak in the given
array, then the output should be {pos: [], peaks: []}.
All input arrays will be valid numeric arrays (although it could still be
empty), so you won't need to validate the input.
The first and last elements of the array will not be considered as peaks
(in the context of a mathematical function, we don't know what is after and
before and therefore, we don't know if it is a peak or not).
Also, beware of plateaus !!! [1,2,2,2,1] has a peak while [1, 2, 2, 2, 3] does
not. In case of a plateau-peak, please only return the position and value of
the beginning of the plateau. For example: pickPeaks([1,2,2,2,1])
returns {pos:[1],peaks:[2]}
"""
def pick_peaks(arr):
peaks = []
pos = []
answer = []
# for n in range(1, len(arr) - 1):
# if arr[n] >= arr[n + 1] and arr[n] > arr[n - 1]:
# peaks.append(arr[n])
# pos.append(n)
# return {"pos": pos, "peaks": peaks}
values = [[n, arr[n]] for n in range(len(arr))]
new_values = [values[r] for r in range(1, len(values)) if values[r][1] != values[r - 1][1]]
# if values[r][1] == values[r + 1][1]:
# print values[r][1]
print values
print new_values
#new_values2 = [new_values[x] for x in range(len(new_values), - 1) if new_values[x + 1][1] >= new_values[x][1] and new_values[x][1] > new_values[x - 1][1]]
for x in range(len(new_values)):
if new_values[x][1] >= new_values[x - 1][1] and new_values[x][1] > new_values[x + 1][1]:
print "TEST"
answer.append(new_values[x])
print answer
for n in range(1, len(arr) - 1):
if arr[n] >= arr[n + 1] and arr[n] > arr[n - 1]:
peaks.append(arr[n])
pos.append(n)
return {"pos": pos, "peaks": peaks}
| true |
fc4408ca667648cbe83d0cda8809e28848a7b745 | IsraMejia/Python100DaysOfCode | /D4_ProjectRPS.py | 1,506 | 4.28125 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
# print(rock)
def print_choice(choice):
if(choice == 1):
print(rock)
elif(choice == 2):
print(paper)
elif(choice == 3):
print(scissors)
else:
print('Impossible, GameOver')
while True:
print('\n\nAre u ready for play Rock, Paper, Scissors with a computer xd?')
choice = int(input('What do you choice? Type 1 for Rock, 2 for Paper or 3 for Scissors'))
computer_choice = random.randint(1, 3)
print_choice(choice)
print('My computer choice is:')
print_choice(computer_choice)
if choice >= 4 or choice < 1:
print("You typed an invalid number, you lose!")
elif choice == 1 and computer_choice == 3:
print("You win!")
elif computer_choice == 1 and choice == 3:
print("You lose")
elif computer_choice > choice:
print("You lose")
elif choice > computer_choice:
print("You win!")
elif computer_choice == choice:
print("It's a draw")
choise_play = input('Dou you wanna play again? ').lower()
# print(f'choise : {choise_play}')
if (choise_play == 'no'):
break
# python3 D4_ProjectRPS.py | false |
3c6220e75c2dfcfa7edd85fa2ddda95dd3813a43 | Fabricio1984/Blue_Python_VS_CODE | /Aula06_Funcao/aula6ex002.py | 430 | 4.15625 | 4 | # 2. Faça um programa, com uma função que necessite de um argumento.
# A função retorna o valor de caractere ‘P’, se seu argumento for positivo,
# ‘N’, se seu argumento for negativo e ‘0’ se for 0.
def funcao():
ex2 = int(input('Digitr um número para verificar se é positivo ou negativo: '))
if ex2 > 0:
print('P')
elif ex2 == 0:
print('0')
else:
print('N')
funcao()
| false |
87415d8088973f0aeed3bb5576edfc535602510f | Darrenrodricks/IntermediatePythonNanodegree | /ObjectOrientedProgramming/CustomInit.py | 1,062 | 4.25 | 4 | class House:
def __init__(self, size, color='white'):
self.size = size
self.color = color
home = House(1000, color='red')
print(home.size)
print(home.color)
mansion = House(25000)
print(mansion.size)
print(mansion.color)
# ******************* MINI QUIZ **************************
# Define a class object Notebook that can be instantiated with three arguments - a number of pages
# (required), a paper size description (optional, defaulting to 'a4'), and a spacing description
# (optional, defaulting to 'college')
# Your class should be able to be initialized like:
# journal = Notebook(80, size='letter', spacing='wide')
# You should set three attributes on the instance object in the initializer - pages, size, and spacing.
# Have some fun here too! Are there other attributes you would like your notebook to have?
class Notebook:
def __init__(self, pages, size='a4', spacing='college'):
self.pages = pages
self.size = size
self.spacing = spacing
journal = Notebook(80, size='letter', spacing='wide')
| true |
7d70e5a031e3c76e9ee654490982f2e3ac44947f | nikelily/PyLearn-Codes | /160919/guidemo.py | 1,373 | 4.28125 | 4 | #GUI
#Python 支持多种图形界面的第三方库
#但是 Python 自带的库是支持 Tk 的 Tkinter,
#Tkinter
#Tk 是一个图形库,支持多个操作系统,使用 Tcl 语言开发;
#Tk 会调用操作系统提供的本地 GUI 接口,完成最终的 GUI。
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.helloLabel = Label(self, text='Hello, world!')
self.helloLabel.pack()
self.quitButton = Button(self, text='Quit', command=self.quit)
self.quitButton.pack()
app = Application()
# 设置窗口标题:
app.master.title('Hello World')
# 主消息循环:
app.mainloop()
#第二个GUI
def center_window(w = 300, h = 200):
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry("%dx%d+%d+%d" % (w, h, x, y))
root = Tk(className='python gui')
center_window(500, 300)
root.mainloop()
#GUI 程序的主线程负责监听来自操作系统的消息,并依次处理每一条消
#息。因此,如果消息处理非常耗时,就需要在新线程中处理。
#Python 内置的 Tkinter 可以满足基本的 GUI 程序的要求,如果是非常复
#杂的 GUI 程序,建议用操作系统原生支持的语言和库来编写
| false |
6ff21fef736fdf04f08e02ed3a33446200e02d3e | nikelily/PyLearn-Codes | /160907/variety.py | 527 | 4.1875 | 4 | #在 Python 中,等号=是赋值语句,可以把任意数据类型赋值给变量,同
#一个变量可以反复赋值,而且可以是不同类型的变量,例如:
a = 123 # a 是整数
print(a)
a = 'ABC' # a 变为字符串
print(a)
#一种除法是/ /除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数:
print(10/3)
#还有一种除法是//,称为地板除,两个整数的除法仍然是整数,整数的地板除//永远是整数,即使除不尽:
print(10//3)
| false |
6554f52d20b731d419580eb7a1b736e2581a61a4 | Reena-Kumari20/Files | /demofile.py | 667 | 4.125 | 4 | #To open the file, use the built-in open() function.
def demo(file):
with open(file,'r') as filename:
words=filename.read()
print(words)
filename.close()
demo("demofile.txt")
#use of read
f=open("demofile.txt","r")
a=f.read()
print(a)
f.close()
#use of readline
x=open("demofile.txt","r")
b=x.readline()
print(b)
x.close()
# use of readlines
y=open("demofile.txt","r")
c=y.readlines()
print(c)
y.close()
# use of read numbers
p = open("demofile.txt", "r")
print(p.read(5))
#use of readline
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
# use of for loop
f = open("demofile.txt", "r")
for x in f:
print(x)
| true |
16e434820e144fe776255251a713db3fa6e853d6 | mbarbachov/alexGIT | /stuff for aops/week4/week4_problem3.py | 350 | 4.34375 | 4 | print('I will convert hours + minutes + seconds into seconds')
hours = int(input('How many hour(s)? '))
minutes = int(input("How many minute(s)? "))
seconds = int(input('How many second(s)? '))
def convert_to_seconds(h, m, s):
return s + 60 * m + 3600 * h
print('The number of seconds is :', int(convert_to_seconds(hours, minutes, seconds)))
| false |
56b7d63145f03b95046c82896ef6fd9fc9c40513 | mbarbachov/alexGIT | /stuff for aops/week4/week4_problem7.py | 1,094 | 4.53125 | 5 | # ask for birth year,month, and day
year = int(input('What is the year the person was born? '))
month = int(input('What is the month the person was born? '))
day = int(input('What is the day the person was born? '))
# ask for current year,month, and day
year2 = int(input("What is the current year? "))
month2 = int(input("What is the current month? "))
day2 = int(input("What is the current day? "))
# we create the function
def mongo_age(birth_year, birth_month, birth_day, current_year, current_month, current_day):
# we convert the dates from the start into mongo terms
birth_in_days = birth_year * 26 * 15 + birth_month * 26 + birth_day
current_in_days = current_year * 26 * 15 + current_month * 26 + current_day
# we subtract the two conversions
difference = current_in_days - birth_in_days
# we return the difference
return '%.10f' % (difference / (26 * 15))
info = list(map(int, input('Enter the information for the age : ').split(',')))
print('The age of person on planet mongo is : ', mongo_age(info[0], info[1], info[2], info[3], info[4], info[5]))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.