blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
51640e43dbe3038b807c52fb2d65462cad9e226b
ultimabugger/python_homework
/func_num.py
463
3.609375
4
def div(*args): try: arg_1 = float(input("Укажите число x: ")) arg_2 = float(input("Укажите число y: ")) res = arg_1 / arg_2 except ValueError: return "Что-то пошло не так :) Попробуйте еще раз" except ZeroDivisionError: return "На ноль делить нельзя!" ...
6a1bd810422f098ca321fab3dfe9afa4a284e9a0
lukkwc-byte/CSReview
/Queues.py
894
3.84375
4
#Init of a Queue #Enqueue #Dequeing from LinkedLists import * class QueueLL(): def __init__(self): self.LL=LL() def __str__(self): return str(self.LL) def Enqueue(self, node): LL.AddTail(self.LL, node) return def Dequeue(self): ret=self.LL.head ...
f308cd2e7a7c979ab741b91fdc859b338ec453c9
sency90/allCode
/acm/python/1850.py
157
3.515625
4
def gcd(b,s): if s==0: return int(b) else: return gcd(s,b%s) a,b = map(int, input().split()) g = gcd(a,b) i = 0 for i in range(g): print(1, end='')
721e5d6a05f065535b8fdec251e728310ecb9748
neeraj1909/100-days-of-challenge
/project_euler/problem-1.py
448
3.796875
4
#!/bin/python3 import sys def sum_factors_of_n_below_k(k, n): m = (k -1) //n return n *m *(m+1) //2 t = int(input().strip()) for a0 in range(t): n = int(input().strip()) total = 0 #for multiple of 3 total = total + sum_factors_of_n_below_k(n, 3) #for multiple of 5 total = total + sum...
02a7e4eafa99a2c99c8c54e45846ef23e6358522
konnomiya/algorithm021
/Week_02/589.N-ary_Tree_Preorder_Traversal.py
553
3.578125
4
class Solution: # iteration def preorder(self, root: 'Node') -> List[int]: stack, res = [root,], [] while stack: node = stack.pop() if node: res.append(node.val) stack.extend(node.children[::-1]) return res # recursive def ...
08e72c506ad7c81b8295b6e3a2d16ff46cb3236d
sayanm-10/py-modules
/main.py
3,660
3.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- __author__ = "Sayan Mukherjee" __version__ = "0.1.0" __license__ = "MIT" import unittest import os from datetime import datetime, timedelta from directory_analyzer import print_dir_summary, analyze_file def datetime_calculator(): ''' A helper to demonstrate the datetim...
df11433519e87b3a52407745b274a6db005d767c
jtquisenberry/PythonExamples
/Interview_Cake/hashes/inflight_entertainment_deque.py
1,754
4.15625
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/inflight-entertainment?section=hashing-and-hash-tables&course=fc1 # Use deque # Time = O(n) # Space = O(n) # As with the set-based solution, using a deque ensures that the second movie is not # the same as the current movi...
e7d72e428f84364bde9130e8bcecc818ee628a94
jtquisenberry/PythonExamples
/Interview_Cake/arrays/merge_meetings.py
2,921
4.09375
4
import unittest # https://www.interviewcake.com/question/python/merging-ranges?course=fc1&section=array-and-string-manipulation # Sort ranges of tuples # Time: O(n * lg(n)) because of the sorting step. # Space: O(n) -- 1n for sorted_meetings, 1n for merged_meetings. # First, we sort our input list of meetings by star...
8eeff2df65c400e2ae316070389736e46dc1fc2b
jtquisenberry/PythonExamples
/Jobs/bynder_isomorphic_strings.py
1,227
3.609375
4
import unittest def is_isomorphic(str1, str2): if len(str1) != len(str2): return False character_map = dict() seen_values = set() for i in range(len(str1)): if str1[i] in character_map: if str2[i] != character_map[str1[i]]: return False ...
dbfbd24fa14eeef9f495b3e6c08b428e8274159f
jtquisenberry/PythonExamples
/Simple_Samples/list_comprehension_multiple.py
104
3.578125
4
X = [['a','b','c'],['z','y','x'],['1','2','3']] aaa = [word for words in X for word in words] print(aaa)
e1c7953b7d1f52122d545583785a842e187a7bd7
jtquisenberry/PythonExamples
/Simple_Samples/array_to_tree.py
2,656
3.734375
4
import math from collections import deque class Node(): def __init__(self, value, left_child = None, right_child = None): self.value = value self.left = None self.right = None def __str__(self): return str(self.value) nodes = [1,2,3,4,5,6,7,8] current_index = 0 unlinked_nodes =...
5e5c7d41a7344b9eb94f9f9dbde5dbe48390b5f6
jtquisenberry/PythonExamples
/Interview_Cake/trees_and_graphs/graph_coloring.py
6,495
4.3125
4
import unittest # https://www.interviewcake.com/question/python/graph-coloring?section=trees-graphs&course=fc1 # We go through the nodes in one pass, assigning each node the first legal color we find. # How can we be sure we'll always have at least one legal color for every node? In a graph with maximum degree DDD, ...
fcbb62045b3d953faf05dd2b741cd060376ec237
jtquisenberry/PythonExamples
/Jobs/maze_runner.py
2,104
4.1875
4
# Alternative solution at # https://www.geeksforgeeks.org/shortest-path-in-a-binary-maze/ # Maze Runner # 0 1 0 0 0 # 0 0 0 1 0 # 0 1 0 0 0 # 0 0 0 1 0 # 1 - is a wall # 0 - an empty cell # a robot - starts at (0,0) # robot's moves: 1 step up/down/left/right # exit at (N-1, M-1) (never 1) # length(of the shortes...
ba8395ab64f7ebb77cbfdb205d828aa552802505
jtquisenberry/PythonExamples
/Interview_Cake/arrays/reverse_words_in_list_deque.py
2,112
4.25
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1 # Solution with deque def reverse_words(message): if len(message) < 1: return message final_message = deque() current_word = [] for i ...
37506921175e5dfec216a7b8c0433d421e0cdbd1
jtquisenberry/PythonExamples
/numpy_examples/multiplication.py
365
3.703125
4
import numpy as np X = \ [ [3, 2, 8], [3, 3, 4], [7, 2, 5] ] Y = \ [ [2, 3], [4, 2], [5, 5] ] X = np.array(X) Y = np.array(Y) print("INPUT MATRICES") print("X") print(X) print("Y") print(Y) print() print("DOT PRODUCT") print(np.dot(X, Y)) print() print...
8236247559f5951c95d1bd1a5074393c8feb8967
jtquisenberry/PythonExamples
/Leetcode/triangle4.py
488
3.640625
4
from functools import lru_cache triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] class Solution: def minimumTotal(self, triangle): @lru_cache() def dfs(i, level): if level == len(triangle): return 0 left = triangle[level][i] + dfs(i, level + 1) right = ...
6abe6859f0ce87b6a8d6cdd400a0c910246b0f0d
jtquisenberry/PythonExamples
/Leetcode/1342_number_of_steps_to_reduce_a_number_to_zero.py
408
3.71875
4
from typing import * class Solution: def numberOfSteps(self, num: int) -> int: steps = 0 while num > 0: # print(num, bin(num)) if num & 1: steps += 1 steps += 1 num = num >> 1 # print(steps) if steps - 1 > -1: ...
83cf3df4820c5d6a21118a51a2869080067a7870
jtquisenberry/PythonExamples
/Interview_Cake/combinatorics/find_duplicated_number_set.py
1,037
3.984375
4
import unittest # https://www.interviewcake.com/question/python/which-appears-twice?course=fc1&section=combinatorics-probability-math # Find the number that appears twice in a list. # This version is not the recommended version. This version uses a set. # Space O(n) # Time O(n) def find_repeat(numbers_list): #...
9adfabfbc83b97a11ee5b2f23cea5ec2eb357dd5
jtquisenberry/PythonExamples
/Interview_Cake/sorting/merge_sorted_lists3.py
1,941
4.21875
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/merge-sorted-arrays?course=fc1&section=array-and-string-manipulation def merge_lists(my_list, alices_list): # Combine the sorted lists into one large sorted list if len(my_list) == 0 and len(alices_list) == 0: ...
2950d12a2c1981f470e285bb6af54e51bdc6fa94
jtquisenberry/PythonExamples
/Pandas_Examples/groupby_unstack.py
1,464
3.890625
4
import pandas as pd import matplotlib.pyplot as plt # https://stackoverflow.com/questions/51163975/pandas-add-column-name-to-results-of-groupby # There are two ways to give a name to an aggregate column. # It may be necessary to unstack a compound DataFrame first. # Initial DataFrame d = {'timeIndex': [1, 1, 1, 9, 1...
e8d9dccc13de722b93bf91f8b33e5702a2a9b96b
jtquisenberry/PythonExamples
/Jobs/stellar/triangle2.py
557
3.84375
4
#https://leetcode.com/problems/triangle/ from copy import deepcopy triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]] def minimumTotal(triangle): print(triangle) #triangle2 = triangle.copy() # updates triangle and triangle2 #triangle2 = list(triangle) # updates triangle and triangle2 #triangle2 = ...
148c6d9d37a9fd79e06e4371a30c65a5e36066b2
jtquisenberry/PythonExamples
/Jobs/multiply_large_numbers.py
2,748
4.25
4
import unittest def multiply(num1, num2): len1 = len(num1) len2 = len(num2) # Simulate Multiplication Like this # 1234 # 121 # ---- # 1234 # 2468 # 1234 # # Notice that the product is moved one space to the left each time a digit # of the top number is multip...
d59ccfe23de3862992af4e1e16cd5d67c838ca21
jtquisenberry/PythonExamples
/Classes/getters_and_setters.py
1,094
3.609375
4
import unittest class Cat(): def __init__(self, name, hair_color): self._hair_color = hair_color # Use of a getter to return hair_color @property def hair_color(self): return self._hair_color # Setter has the name of the property # Use of a setter to throw AttributeError wi...
0812620e8371ba84710baa5a1eee9992804a3408
jtquisenberry/PythonExamples
/Simple_Samples/array_as_tree.py
609
3.75
4
# Calculate the sum of the left side and the right side tree = [1,2,3,4,0,0,7,8,9,10,11,12,13,14,15,16] # 1 # 2 3 # 4 5 6 7 # 8 9 10 11 12 13 14 15 # 16 left_side = 0 right_side = 0 power_of_two = 1 while len(tree) > 2**(power_of_two - 1): left_index = (2**p...
b8b7d0a3067b776d6c712b2f229ef65448b9a4d9
jtquisenberry/PythonExamples
/Interview_Cake/arrays/reverse_words_in_list_lists.py
2,120
4.375
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1 # Solution with lists only # Not in place def reverse_words(message): if len(message) < 1: return current_word = [] word_list = [] fina...
5ed8d9b76cd9a1443a8f0fa9a7ee46604b6e3dfd
mansigoel/GitHackeve
/project2.py
417
3.875
4
def factorial(number_for_factorial): # Add code here return #Factorial number def gcd(number_1, number_2): # Add code here return #gcd value def is_palindrome(string_to_check): # Add code here return #boolean response #Take input for fib in variable a print(fib(a)) #Take input for is_prime in varia...
7aec878186d13b42ac12dd05d1580fc47662520e
devSantos16/pythonDice
/main.py
2,139
3.671875
4
from builtins import dict from Jogada import Jogada from Jogada import mostrarTodosOsDados from Jogada import deletar from Jogada import verificarDadoNulo # Modo usuario loop = True while loop: menu = int(input("SEJA BEM VINDO! \n" "Digite o modo de entrada\n" ...
a274889dd5ea83c37dd31a7df6c5ea88d1f1f2bb
libp2p/py-libp2p
/libp2p/peer/addrbook_interface.py
1,673
3.5625
4
from abc import ABC, abstractmethod from typing import List, Sequence from multiaddr import Multiaddr from .id import ID class IAddrBook(ABC): @abstractmethod def add_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: """ Calls add_addrs(peer_id, [addr], ttl) :param peer_id...
5d730b83244e0a0d7773556652ff0332d0857ef8
Hananja/DQI19-Python
/01_Einfuehrung/prime_factors_simple.py
727
3.90625
4
# -*- coding: utf-8 -*- # Berechnung der Primfaktoren einer Zahl in einer Liste from typing import List loop = True while loop: # Eingabe input_number : int = int(input("Bitte Nummer eingeben: ")) number : int = input_number # Verarbeitung factors : List[int] = [] # Liste zum Sammeln der Faktor...
c53deedb3e49ee964abe0fd4b3a83f2a327a0a08
flofl-source/Pathfinding
/Maier_Flora_Td5.py
3,354
4.03125
4
# Advanced Data Structure and Algorithm # Parctical work number 5 # Exercice 2 #Graph 2 : Negative weight so we use the #Bellman-Ford algorithm #Graph 1 : #Number of edges : 13 #Number of nodes : 8 #Complexity of the dijkstra algorithm : 64 #Complexity of the Bellman-Ford algorithm : 104 #Complexi...
1aa6ba8516a4e996c07028bc798bdb13064add85
jaeyun95/Algorithm
/code/day05.py
431
4.1875
4
#(5) day05 재귀를 사용한 리스트의 합 def recursive(numbers): print("===================") print('receive : ',numbers) if len(numbers)<2: print('end!!') return numbers.pop() else: pop_num = numbers.pop() print('pop num is : ',pop_num) print('rest list is : ',numbers) ...
a76ed6a1b76c2f0771acb387e63bcafb86b73b96
jaeyun95/Algorithm
/code/day06.py
398
3.640625
4
#(6) day06 가장 많이 등장하는 알파벳 개수 구하기 def counter(word): counter_dic = {} for alphabet in word: if counter_dic.get(alphabet) == None: counter_dic[alphabet] = 1 else: counter_dic[alphabet] += 1 max = -1 for key in counter_dic: if counter_dic[key] > max: ...
1786d5bd32505970f897ff9691259f3a1cc785a7
phypm/Pedro_Motta
/Ex8_maiornota.py
791
3.765625
4
import sys i=0 nota=0 boletim=[] while True: try: a = int (raw_input("Digite a nota do Aluno ")) while a >= 0: boletim.append(a) i += 1 nota = a + nota print "Nota total e: ", nota a = int (raw_input("Digite a nota do Aluno ")) else...
4b8c656ea711a2274df26c044ec6a7d7ce7b33bc
bojanuljarevic/Algorithms
/BST/bin_tree/bst.py
1,621
4.15625
4
# Zadatak 1 : ručno formiranje binarnog stabla pretrage class Node: """ Tree node: left child, right child and data """ def __init__(self, p = None, l = None, r = None, d = None): """ Node constructor @param A node data object """ self.parent = p self.le...
99421729232987d7fe4d317883032134d21d07b3
bojanuljarevic/Algorithms
/sorting/quicksort.py
1,342
3.75
4
#!/usr/bin/python import random import time def random_list (min, max, elements): list = random.sample(range(min, max), elements) return list def partition(A, p, r): x = A[r] i = p - 1 for j in range(p, r): if A[j] <= x: i = i + 1 A[i], A[j] = A[j], A[i] A[i+1]...
6157e34614e49830e4899261da0db857eac845f2
ZhaoHuiXin/MachineLearningFolder
/Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression_practice2.py
764
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 12 17:29:51 2019 @author: zhx """ import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,0:1].values y = dataset.iloc[:,1].values from sklearn.model_selection import trai...
9956ac773c8fc68668abb55eb445a6be2b3aea4f
kalewford/Python-
/Bank/main(submission).py
2,516
4
4
# Dependencies import csv import os # Files to Load file_to_load = "Bank/budget_data.csv" file_to_output = "Bank/budget_analysis.txt" # Variables to Track total_months = 0 total_revenue = 0 prev_revenue = 0 revenue_change = 0 great_date = "" great_increase = 0 bad_date = "" worst_decrease = 0 rev...
5f5e0b19e8b1b6d0b0142eb63621070a50227142
steven-liu/snippets
/generate_word_variations.py
1,109
4.125
4
import itertools def generate_variations(template_str, replace_with_chars): """Generate variations of a string with certain characters substituted. All instances of the '*' character in the template_str parameter are substituted by characters from the replace_with_chars string. This function generate...
14deebd3730600c4c34d2ef5ae3cd3f110dcaf0c
SharanSMenon/Sharan-Main
/guessTheNumber.py
484
3.828125
4
import random while True: n = random.randint(0,100) count = 0 while True: guess = int(input('Guess a number between 1 and 100:')) if guess == n: print("You win") count += 1 print("You tried "+str(count)+" times.") play_again = input('Do you want to play again?') if play_again == 'no': print('B...
f84682bb7f6a6df4644cff27e69d48cf0b1a6fc2
cdanh-aptech/Python-Learning
/PTB2.py
787
3.5
4
import math def main(): print("Giai Phuong Trinh Bac 2 (ax2 + bx + c = 0)") hs_a = int(input("Nhap he so a: ")) hs_b = int(input("Nhap he so b: ")) hs_c = int(input("Nhap he so c: ")) giaiPT(hs_a, hs_b, hs_c) def giaiPT(a, b, c): if a == 0: print(f"La phuong trinh bac 1, x = {-c/b...
dbc393cb1fe09bc5cb54992be1294e154cf023a1
KuleshovaY/Python_GB
/Lesson_3/task_3.5.py
1,594
3.875
4
# Программа запрашивает у пользователя строку чисел, разделенных пробелом. # При нажатии Enter должна выводиться сумма чисел. # Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. # Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. # Но если вместо числа вводится с...
c1bdaf6db92db9e09dce8e58127041436842b4ce
KuleshovaY/Python_GB
/Lesson_2/task _2.6.py
951
3.6875
4
i = 1 goods = [] n = int(input('Сколько товаров хотите ввести? ')) for _ in range(n): name = input('Введите название товара ') price = int(input('Введите цену ')) quantity = int(input('Введите колличество ')) measure = input('введите единицы измерения ') goods.append((i, {'название': name, 'цена': p...
a0e648ea664458c9752d4013b8b91b6cee690dfa
jackjyq/COMP9021_Python
/ass01/highest_scoring_words/highest_scoring_words.py
5,438
3.859375
4
# Author: Jack (z5129432) for COMP9021 Assignment 1 # Date: 25/08/2017 # Description: Qustion 3 from itertools import permutations from collections import defaultdict import sys # Function: CombineLetters # Dependency: itertools.permutations # Input: a list such as ['a', 'b', 'c'] # Output: a set such as {'ab', ...
7b8489895a95d9870f1caff4edf870e1e496da11
jackjyq/COMP9021_Python
/ass01/highest_scoring_words/Permutations.py
406
3.765625
4
# Function: Permutations # Dependency: # Input: list such as ['e', 'a', 'e', 'o', 'r', 't', 's', 'm', 'n', 'z'], and a integer such as 10 # Output: set of permutations of your input # Description: def Permutations(input_list, number): return # Test Codes if __name__ == "__main__": Letters = ['e', 'a', 'e'...
54f286be437cb160aa7c49f4e9630d1a5072a8ce
jackjyq/COMP9021_Python
/quiz04/sort_ratio.py
1,049
3.546875
4
from get_valid_data import get_valid_data from get_ratio import get_ratio from get_top_n_countries import get_top_n_countries def sort_ratio(courtry_with_ratio): """ sort_ratio Arguements: an unsorted list[(ratio1, country1), (ratio2, country2), (ratio3, country3) ...] Returns: A list sorted by ratio. If t...
2514877d40f20ee981d6cb981cdf0b0dd92b263d
jackjyq/COMP9021_Python
/ass01/pivoting_die/pivoting_die.py
2,703
3.984375
4
# Author: Jack (z5129432) for COMP9021 Assignment 1 # Date: 23/08/2017 # Description: ''' ''' import sys # function: move # input: null # output: die[] after moved def move_right(): die_copy = die[:] die[3] = die_copy[2] # right become bottom die[2] = die_copy[0] # top become right die[0] = die_copy...
a4d065a288fb455ede7cf37fc3e4b4d3eabf6c9f
jackjyq/COMP9021_Python
/ass01/poker_dice/roll_dice.py
571
4.03125
4
from random import randint from random import seed def roll_dice(kept_dice=[]): """ function Use to generate randonly roll, presented by digits. Arguements: a list of kept_dice, such as [1, 2] default argument if [] Returns: a list of ordered roll, such as [1, 2, 3, 4, 5]. Dependency: r...
cc3a1d58b9a459e87baba1db1667b8c3eafaed7a
jackjyq/COMP9021_Python
/ass01/poker_dice/hand_rank.py
1,577
4.21875
4
def hand_rank(roll): """ hand_rank Arguements: a list of roll, such as [1, 2, 3, 4, 5] Returns: a string, such as 'Straight' """ number_of_a_kind = [roll.count(_) for _ in range(6)] number_of_a_kind.sort() if number_of_a_kind == [0, 0, 0, 0, 0, 5]: roll_hand = 'Five of a kind' el...
c889b0c75a22a5de5204de652db5adc535c8d190
eunic/bootcamp-final-files
/wordcount.py
495
3.65625
4
def words(stringofwords): dict_of_words = {} list_of_words = stringofwords.split() for word in list_of_words: if word in dict_of_words: if word.isdigit(): dict_of_words[int(word)] += 1 else: dict_of_words[word] += 1 else: ...
dd79781c62f4547d9d74d2ac395464642b02ec89
mtasende/usd-uyu-dashboard
/src/data/world_bank.py
3,125
4.0625
4
""" Functions to access the World Bank Data API. """ import requests from collections import defaultdict import pandas as pd def download_index(country_code, index_code, start_date=1960, end_date=2018): """ Get a JSON response for the index data of one ...
00fd9d33ece481fe3d2e98eaca624aeb2e595b1c
YuvalHelman/adventofcode2020
/adventOfCode/day2.py
1,368
3.5625
4
from pathlib import Path from typing import Callable from itertools import filterfalse import re FILE_PATTERN = re.compile(r"(?P<min>[0-9]+)-(?P<max>[0-9]+)\s*(?P<letter_rule>[A-Za-z]):\s*(?P<password>[A-Za-z]+)") INPUT_PATH = Path("inputs/day2_1.txt") def is_count_of_char_in_sentence(char: str, sentence: str, min: ...
c758312e57e9cbab57c6a448cb7cfb90331ebbad
tskkst51/lplTrade
/PTP/trading_platform_shell/string_parsers.py
2,493
3.59375
4
# # # def string_to_value(s): s = s.strip().lower() if s[-1] == 'k': try: value = float(s[:-1]) return value * 1000.0 except ValueError: return None try: value = float(s) return value except ValueError: pass ...
903ba4783c8c4e7af8d4087dfab2759cd3579919
mailtsjp/FinPy
/Filetoticker.py
1,825
3.5625
4
import pandas_datareader.data as web import datetime #read ticker symbols from a file to python symbol list symbol = [] with open('tickers.txt') as f: for line in f: symbol.append(line.strip()) f.close #datetime is a Python module #datetime.datetime is a data type within the datetime module #wh...
0cadee6937b8b5954877cfd8de03660fa983407f
Miguel-21904220/pw_python_03
/pw-python-03/Exercisio 1/analisa_ficheiro/acessorio.py
369
3.625
4
import os def pede_nome(): while True: try: nome_ficheiro = input("Introduza o numero do ficheiro: ") with open('analisa_ficheiro/' + nome_ficheiro, 'r') as file: return nome_ficheiro except: print("Nao existe") def gera_nome...
007ef0564c214ab11f0b9ef081cb08c0b2315029
cassiano-r/Spark
/MapReduceSparkHadoopProject/gastos-cliente.py
787
3.65625
4
from pyspark import SparkConf, SparkContext # Define o Spark Context, pois o job será executado via linha de comando com o spark-submit conf = SparkConf().setMaster("local").setAppName("GastosPorCliente") sc = SparkContext(conf = conf) # Função de mapeamento que separa cada um dos campos no dataset def MapCliente(lin...
cb7c7e5bdfd3b741a4b3a77d7264736ec61e184f
joker507/exercise
/UA.py
1,229
3.71875
4
#用于求大学物理实验中的A类不确定度和平均值,今后将考虑自动取好不确定度的有效数字和求解b类不确定度并取相应的有效数字并计算总不确定度,但现实践有限,不做实现 #physics average,求平均值 def phsaver(a): m = len(a) aver = [] for i in range(m): sum = 0 for num in a[i]: sum = sum + num aver.append(sum/len(a[i])) return aver #physics undecided 求A类不确定度 def phsunde(a): m = len(a) ud = [] for ...
e0408bdb6b3251bf3472b3a3836ad7ec8ec0ed4d
madhurigorthi/sdet-1
/python/Activity3.py
537
3.859375
4
input1=input("Enter player1 input :").lower() input2=input("Enter player2 input :").lower() if input1 == input2: print("Its tie !!") elif input1 == 'rock': if input2 == 'scissors': print("player 1 wins") else: print("player 2 wins") elif input1 == 'scissors': if input2 == '...
54893e3be825167355e17ed579f00053945d924a
madhurigorthi/sdet-1
/python/Acitvity1.py
161
3.921875
4
name=input("Enter your name ") age=int(input("Enter your age ")) year=str((2020-age)+100) print(name + " you will become 100 years old in the year " + year)
ddc9a3d2c6c1933dc8a404084ee9afc146a3cfae
wojciechuszko/random_Fibonacci_sequence
/random_fibonacci_sequence.py
769
3.546875
4
import numpy as np import matplotlib.pyplot as plt n = int(input("Enter a positive integer n: ")) vector = np.zeros(n) vector[0] = 1 vector[1] = 1 for i in range(2,n): rand = np.random.rand() if rand < 0.5: sign = -1 else: sign = 1 vector[i] = vector[i-1] + sign * vector[i-2] x = ...
7947bfed24a33be65cecd3bca43eba6d76adf3eb
dkout/6.006
/pset3/code_template_and_latex_template/search_template.py
3,381
3.875
4
################################### ########## PROBLEM 3-4 ########### ################################### from rolling_hash import rolling_hash def roll_forward(rolling_hash_obj, next_letter): """ "Roll the hash forward" by discarding the oldest input character and appending next_letter to the input. ...
30a9dcb344404f005a6f62031701c9b5c856d0fa
Blasius7/Python-homeworks
/guess.py
1,274
3.6875
4
import random attempts = 0 end_num = [5,15,50] while True: difficulty = input("Milyen nehézségi fokon játszanád a játékot? \n (Könnyű, közepes vagy nehéz): \n") if difficulty == "könnyű": end_num = 5 break elif difficulty == "közepes": end_num = 15 break elif difficulty ...
8960e2ef84431879e95ccdaa62d78c55e8b30311
michelle-chiu/Python
/Gauss.py
246
3.984375
4
#Add the numbers from 1 to 100 #Think about what happens to the variables as we go through the loop. total = 0 #will be final total for i in range(101): #i will be 0, 1, 2, 3, 4, 5, etc total = total + i #change total by i print(total)
2e199b2cde6f32ac5008f72558d50c717657146e
hilaryweller0/talks2013
/SS/HilaryNotes/pythonExamples_HW/GaussQuad.py
951
3.59375
4
# Calculate the approximate integral of sin(x) between a and b # using 1-point Gaussiaun quadrature using N intervals # First import all functions from the Numerical Python library import numpy as np # Set integration limits and number of intervals a = 0.0 # a is real, not integer, so dont write a = 0 b ...
805a3bf16a9afccf42a465d3968bb3e2e7365abe
jgkr95/CSPP1
/Practice/M5/p2/square_root.py
348
3.875
4
'''Write a python program to find the square root of the given number using approximation method''' def main(): '''This is main method''' s_r = int(input()) ep_n = 0.01 g_s = 0.0 i_n = 0.1 while abs(g_s**2 - s_r) >= ep_n and g_s <= s_r: g_s += i_n print(g_s) if __name__ ...
0e9d74abf1c2592ec74bdfef35ed89f4cb480f7c
jgkr95/CSPP1
/Practice/M3/compare_AB.py
243
4.03125
4
varA=input("Enter a stirng: ") varB=input("Enter second string: ") if isinstance(varA,str) or isinstance(varB,str): print("Strings involved") elif varA>varB: print("bigger") elif varA==varB: print("equal") elif varA<varB: print("smaller")
05736db1424292838f160b8ca66ea94d911a752e
jgkr95/CSPP1
/Practice/M3/iterate_even.py
139
4.0625
4
count = 0 n=input() print(n) for letter in 'Snow!': print('Letter # ' + str(3)+ ' is ' + letter) count += 1 break print(count)
8dbfcde0a480f44ea8f04d113a5214d7ddb9d290
jgkr95/CSPP1
/Practice/M6/p1/fizz_buzz.py
722
4.46875
4
'''Write a short program that prints each number from 1 to num on a new line. For each multiple of 3, print "Fizz" instead of the number. For each multiple of 5, print "Buzz" instead of the number. For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number. ''' def main(): '''Read numbe...
86c07784b9a2a69756a3390e8ff70b2a4af78652
Ashishrsoni15/Python-Assignments
/Question2.py
391
4.21875
4
# What is the type of print function? Also write a program to find its type # Print Funtion: The print()function prints the specified message to the screen, or other #standard output device. The message can be a string,or any other object,the object will #be converted into a string before written to the screen. p...
6575bbd5e4d495bc5f8b5eee9789183819761452
Ashishrsoni15/Python-Assignments
/Question1.py
650
4.375
4
#Write a program to find type of input function. value1 = input("Please enter first integer:\n") value2 = input("Please enter second integer:\n") v1 = int(value1) v2 = int(value2) choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for multiplication:\n") choice = int(choice) if choice...
a745d249dcd6eaf6bbd7c4b08bf1f8a9998291df
LeoM98/Nomina-industrial
/Explosiones.py
3,338
3.796875
4
def caso_explosion(): #definimos el algoritmo mezclas=int(input("digite el numero de mezclas "))#pedimos al usuario que introduzca un valor nombre_o=[raw_input("ingrese el nombre del operario " + str (a+1)+ ": ")for a in range(5)]# establecemos los nombres de los operarios en la lista explosion=[[0 for ...
ea4c7aaefa309e8f0db99f4f43867ebd1bd52282
Shahriar2018/Data-Structures-and-Algorithms
/Task4.py
1,884
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to i...
be6417755aa43edf9a4eab63392fe474a08c561d
killercatfish/AdventCode
/2018/Advent2018/Tree.py
2,945
3.828125
4
# http://openbookproject.net/thinkcs/python/english2e/ch21.html class Tree: def __init__(self, cargo, left=None, right=None): self.cargo = cargo self.left = left self.right = right def __str__(self): return str(self.cargo) def total(tree): if tree == None: return 0 ret...
15ded2b85a743b4c14f7c816f6284a5496f0a2bf
killercatfish/AdventCode
/2018/Advent2018/Day2/day2_part1.py
829
4.03125
4
''' Advent of code 2018 1) How do you import from a file a) Did you create a file for input? 2) What format would you like the input to be in? a) Ideally, what type of value would the input have been? 3) What data structure could you use to organize your input? 4) What is the question asking? a) How should ...
8e32b2bb8de4fff23664083acc690e27e145447a
killercatfish/AdventCode
/2018/Advent2018/Day7/day7_try2.py
4,027
3.828125
4
''' In order to copy an inner list not by reference: https://stackoverflow.com/questions/8744113/python-list-by-value-not-by-reference ''' from copy import deepcopy input_list = [] ''' step_time: list of letter values printable: heading for printing second_list: [workers current job, seconds remaining], done list ''' '...
0ba5f660e4518f026991b66f02b793d5aa836199
kiner-shah/CompetitiveProgramming
/Hackerrank/Pythonist 2/find_angle_mbc.py
254
3.765625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math x=int(raw_input()) y=int(raw_input()) h=math.hypot(x,y) v=math.asin(x/h)*180/math.pi if v<math.floor(v)+0.5: print int(math.floor(v)) else: print int(math.ceil(v))
586d1398fa085b65390f464ae8a6d23b3f4cdef9
kiner-shah/CompetitiveProgramming
/Hackerrank/Pythonist 2/swap_case.py
269
3.640625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT x=raw_input() l=list(x) for i in range(0,len(l)): if l[i]>='a' and l[i]<='z': l[i]=chr(ord(l[i])-32) elif l[i]>='A' and l[i]<='Z': l[i]=chr(ord(l[i])+32) p="".join(l) print p
75f8fb51306ab728df6ea35bf73fc6a04f88bfba
jpalat/AdventOfCode-2020
/day5/day51.py
1,279
3.53125
4
import struct import math def seatDecoder(passid): print('passid:', passid) instructions = list(passid) row_instructions = instructions[:7] col_instructions = instructions[-3:] row = parseRow(row_instructions) col = parseCol(col_instructions) seat = (row * 8) + col # print(row_instructi...
e5f5ccdcada9074dbc77cda74ff0af195394ec11
uva-slpl/nlp2
/resources/project_neuralibm-2019/vocabulary.py
3,647
3.53125
4
#!/usr/bin/env python3 from collections import Counter, OrderedDict import numpy as np class OrderedCounter(Counter, OrderedDict): """A Counter that remembers the order in which items were added.""" pass class Vocabulary: """A simple vocabulary class to map words to IDs.""" def __init__(self, corpus=N...
3e019a6dda73376db4bcc04bb99f07c9fdf214bc
jucariasar/Proyecto_POO_UNAL_2017-1_Python
/ingenierotecnico.py
1,385
3.6875
4
from empleado import Empleado class IngenieroTecnico(Empleado): MAX_IT = 4 # Constante de clase para controlar el numero máximo de elementos que puede prestar #un IngenieroTecnico areas = {'1':'Mantenimiento', '2':'Produccion', '3':'Calidad'} def __init__(self, ident=0, n...
b440521c3f550e35b63bfb7687f6a94d3d0d61a0
arnizamani/Networks
/AdditionEnv.py
1,984
3.90625
4
# -*- coding: utf-8 -*- """ Created 17 Feb 2016 @author: Abdul Rahim Nizamani """ from network import Network import random class AdditionEnv(object): """Environment feeds activation to the sensors in the network""" def __init__(self,network): print("Initializing Environment...") self.network...
67354d9d9ffdbe84f8348ecf1efa127c56ec33c5
dickersonsteam/CircuitPython_ToneOnA0
/main.py
2,451
3.796875
4
# This example program will make a single sound play out # of the selected pin. # # The following are the default parameters for which pin # the sound will come out of, sample rate, note pitch/frequency, # and note duration in seconds. # # audio_pin = board.A0 # sample_rate = 8000 # note_pitch = 440 # note_length = 1 #...
3842e494b165c2442a0205ea752e0f3aeafb5c12
WillGreen98/Project-Euler
/Tasks 1-99/Task 15/Task-15.py
641
3.75
4
# Task 15 - Python # Lattice Paths import time from functools import reduce binomial = lambda grid_size: reduce(lambda hoz, vert: hoz * vert, range(1, grid_size + 1), 1) def path_route_finder(grid_size_to_check): # As size is perfect cube - I have limited calculations instead of n & m size = grid_size_to_che...
50f0cbdf511231ae28bff1dbe993b9a57befc6f5
WillGreen98/Project-Euler
/Tasks 1-99/Task 10/Task-10.py
898
4.03125
4
# Task 10 - Python # Summations Of Primes import math import time is_prime = lambda num_to_check: all(num_to_check % i for i in range(3, int(math.sqrt(num_to_check)) + 1, 2)) def sum_of_primes(upper_bound): fp_c = 2 summation = 0 eratosthenes_sieve = ((upper_bound + 1) * [True]) while math.pow(fp_c,...
74083ac38b480e5c26bf58cd405728e1f2999e9d
AJSterner/UnifyID
/atmosphere_random.py
2,851
3.703125
4
import urllib2 from urllib import urlencode from ctypes import c_int64 def random_ints(num=1, min_val=-1e9, max_val=1e9): """ get random integers from random.org arguments --------- num (int): number of integers to get min_val (int): min int value max_v...
fae39f809f9202288cfe12ab7de8e63a05fd6341
Rayban63/Coffee-Machine
/Problems/Calculator/task.py
583
4
4
first_num = float(input()) second_num = float(input()) operation = input() no = ["mod", "div", "/"] if second_num == (0.0 or 0) and operation in no: print("Division by 0!") elif operation == "mod": print(first_num % second_num) elif operation == "pow": print(first_num ** second_num) elif operation == "*": ...
d54a81b17a5d535737681a88420bbc1c87fdad97
mattikus/advent2017
/day_1/1.py
307
3.640625
4
#!/usr/bin/env python3 import sys def inverse_captcha(captcha): arr = list(map(int, captcha)) return sum(i for idx, i in enumerate(arr) if i == (arr[0] if idx == (len(arr) - 1) else arr[idx+1])) if __name__ == "__main__": problem_input = sys.argv[1] print(inverse_captcha(problem_input))
cc50953b5b3fb569c4ee7b792b2b4ef02ddaa182
MatiasLeon1/MCOC2020-P0
/MIMATMUL.py
615
3.5625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def mimatmul(A,B): f=len(A) c=len(B) result=np.zeros([f,c]) #Creamos una matriz de puros ceros for i in range(len(A)): #Itera las filas de la matriz A for j in range(len(B[0])): #I...
9e8b97dfce807ab9655b0d7c32c344f875c4fdec
SiddharthaPramanik/Assessment-VisualBI
/music_app/songs/models.py
1,061
3.5625
4
from music_app import db class Songs(db.Model): """ A class to map the songs table using SQLAlchemy ... Attributes ------- song_id : Integer database column Holds the id of the song song_title : String databse column Holds the song name seconds : String databs...
9d8a9f005a7261d963be2c06d7281563deddf157
PowersYang/houseSpider
/houseSpider/test.py
1,772
3.703125
4
# -*- coding: utf-8 -*- import time, datetime kHr = 0 # index for hour kMin = 1 # index for minute kSec = 2 # index for second kPeriod1 = 0 # 时间段,这里定义了两个代码执行的时间段 kPeriod2 = 1 starttime = [[9, 30, 0], [13, 0, 0]] # 两个时间段的起始时间,hour, minute 和 second endtime = [[11, 30, 0], [15, 0, 0]] # 两个时间段的终止时间 sleeptime = 5 #...
f24a10c953482e69f0131e4acf6e13d83fc36cdd
sushrao1996/DSA
/Recursion/Factorial.py
276
4
4
def myFact(n): if n==1: return 1 else: return n*myFact(n-1) num=int(input("Enter a number: ")) if num<0: print("No negative numbers") elif(num==0): print("Factorial of 0 is 1") else: print("Factorial of",num,"is",myFact(num))
22ad07d51d6377717ab69018e34652e03140f837
sushrao1996/DSA
/Queue/CircularQueue.py
1,868
3.953125
4
class CircularQueue: def __init__(self,size): self.size=size self.queue=[None for i in range(size)] self.front=self.rear=-1 def enqueue(self,data): if ((self.rear+1)%self.size==self.front): print("Queue is full") return elif (self.front==-...
7add6d6db4a6824b60f4ee5d5ea150e55f0cb69c
amites/davinci_2017_spring
/codewars/carry_over.py
852
3.625
4
# https://www.codewars.com/kata/simple-fun-number-132-number-of-carries/train/python def number_of_carries(a, b): y = [int(n) for n in list(str(a))] x = [int(n) for n in list(str(b))] # reverse order so beginning with smallest # and going to biggest y.reverse() x.reverse() # figure out w...
d9177b87da9f04a0d1c4406abf65d2996449fc11
v-lubomski/python_start
/old_lessons/func_with_param.py
134
4.125
4
def printMax(a, b): if a > b: print(a, 'is max') elif a == b: print(a, 'equal', b) else: print(b, 'is max') printMax(5, 8)
41f729db17f24ba77f849434e75b4519ea93c9af
kordaniel/AoC
/2020/day8/main.py
2,212
3.671875
4
import sys sys.path.insert(0, '..') from helpers import filemap # Part1 def walk(code): ''' Executes the instructions, stops when reach infinite loop and returns the value''' idx, accumulator = 0, 0 visited = set() while True: if idx in visited: break visited.add(idx) ...
95a68ebdcb01557a83900a8f34f3c57417a0c60f
abnormalmakers/object-oriented
/super.py
378
3.53125
4
class A(): def fn(self): print("A被调用") def run(self): print('A run') class B(A): def fn(self): print("B被调用") def run(self): super(B,self).run() super(__class__,self).run() super().run() a = A() a.fn() b = B() b.fn() b.__class__.__base__.fn(b) print('...
cd44060db334e79d426b1cd69aa2f5e798a9a1cb
thaynnara007/ATAL_listas
/lista02/questao03.py
1,368
3.71875
4
PESO = 0 VALOR = 1 def mochilaBinaria( valorAtual, capacidadeAtual, i, conjuntoAtual): global capacidadeMochila global itens global qntdItens global conjunto global maiorValor if i <= qntdItens: if capacidadeAtual <= capacidadeMochila: if valorAtual > maiorValo...
d218fc784ea19385eb5aff0517529af3c6a513f0
LucHighwalker/CaptainRainbowSpaceMan
/spaceman.py
3,855
3.5
4
import random import os secret_word = '' blanks = list() guessed = list() attempts_left = 7 game_won = False game_lost = False help_prompt = False running = True def load_word(): global secret_word f = open('words.txt', 'r') words_list = f.readlines() f.close() words_list = words_list[0].spl...
e29240d2ac37a9fdeedfd1795ed92bc4d5c59359
MagdaM91/Python
/GUI.py
573
3.609375
4
from tkinter import * root = Tk() #thLable = Label(root, text="This is to easy") #thLable.pack() '' topFrame = Frame(root) topFrame.pack() bottomFram = Frame(root) bottomFram.pack(side=BOTTOM) Firstbutton = Button(topFrame, text="FirstButton",fg="red") Secondbutton = Button(topFrame, text="SecondButton",fg="blue") Th...
f728bb9426eeb04961d39186b2bd98532e02a167
TaiCobo/practice
/checkio/to_encrypt.py
819
3.796875
4
def to_encrypt(text, delta): #replace this for solution alphabet = "abcdefghijklmnopqrstuvwxyz" ret = "" for word in range(len(text)): if text[word] == " ": ret += " " else: ret += alphabet[(alphabet.index(text[word]) + delta) % 26] return ret if __name__ =...
f5a72e136b367e877afd5632cadb843e5944d8db
TaiCobo/practice
/checkio/left_right.py
1,049
3.765625
4
def left_join(phrases): """ Join strings and replace "right" to "left" """ ret = "" return ",".join(phrases).replace("right", "left") def checkio(number: int) -> int: nnn = str(number) ret = 1 for i, val in enumerate(range(0, len(nnn))): if nnn[i] == "0": con...