blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
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... |
05d3835f466737814bb792147e8d7b34a28d912f | qiqi06/python_test | /python/static_factory_method.py | 1,038 | 4.1875 | 4 | #-*- coding: utf-8 -*-
"""
练习简单工厂模式
"""
#建立一工厂类,要用是,再实例化它的生产水果方法,
class Factory(object):
def creatFruit(self, fruit):
if fruit == "apple":
return Apple(fruit, "red")
elif fruit == "banana":
return Banana(fruit, "yellow")
class Fruit(object):
def __init__(self, name, ... |
bf1579ed5e6abab53aa502637d8be30591fef51a | sdurgut/ToyProjects | /NetflixMovieRecommendationSystem/testProject2Phase1a.py | 2,066 | 3.59375 | 4 | '''
>>> userList = createUserList()
>>> len(userList)
943
>>> userList[10]["occupation"]
'other'
>>> sorted(userList[55].values())
[25, '46260', 'M', 'librarian']
>>> len([x for x in userList if x["gender"]=="F"])
273
>>> movieList = createMovieList()
>>> len(movieList)
1682
>>> movieList[27]["title"]
'Apollo 13 (1995)... |
c056c7e6e90f54a6a42b7a7d5c408c749debffed | michaszo18/python- | /serdnio_zaawansowany/sekcja_1/funkcja_id_operator_is.py | 1,399 | 4 | 4 | a = "hello world"
b = a
print(a is b)
print(a == b)
print(id(a), id(b))
b += "!"
print(a is b)
print(a == b)
print(id(a), id(b))
b = b[:-1]
print(a is b)
print(a == b)
print(id(a), id(b))
a = 1
b = a
print(a is b)
print(a == b)
print(id(a), id(b))
b += 1
print(a is b)
print(a == b)
print(id(a), id(b))
b -= 1
print(a i... |
f98a82205815d1acef54f565f03bfafe1df4f0aa | mertcankurt/temizlik_robotu_simulasyonu | /evarobotmove_gazebo/scripts/Interface/Database.py | 583 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
def createTable():
connection = sqlite3.connect('login.db')
connection.execute("CREATE TABLE USERS(USERNAME TEXT NOT NULL,EMAIL TEXT,PASSWORD TEXT)")
connection.execute("INSERT INTO USERS VALUES(?,?,?)",('motar','motar@gmail.com','motar'))
... |
478ea10daafffde5120ff8962eba92c173cd1ade | nosy0411/Object_Oriented_Programming | /homework2/example.py | 285 | 3.546875 | 4 | # import turtle
# # t=turtle.Turtle()
# # for i in range(5):
# # t.forward(150)
# # t.right(144)
# # turtle.done()
# spiral = turtle.Turtle()
# for i in range(20):
# spiral.forward(i*20)
# spiral.right(144)
# turtle.done()
# import turtle
# pen = turtle.Turtle()
|
e3c32038f58505113c4477596d1708390c510d98 | dgriffis/autocomplete | /MyAutoComplete.py | 3,298 | 4.15625 | 4 | #!/usr/bin/env python
import sys
class Node:
def __init__(self):
#establish node properties:
#are we at a word?
self.isaWord = False
#Hash that contains all of our keys
self.keyStore = {}
def add_item(self, string):
#Method to build out Trie
#This is do... |
deae850e32102c9f22d108c817cfd69eebd4344f | szzhe/Python | /ActualCombat/TablePrint.py | 854 | 4.28125 | 4 | tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
# 要求输出如下:
# apples Alice dogs
# oranges Bob cats
# cherries Carol moose
# banana David goose
def printTable(data):
str_data = ''
... |
54033a39aaf84badb53bb8266b6f882ca5d5a96c | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /Grocery_List/main.py | 697 | 3.8125 | 4 | def remove_smallest(numbers):
y = numbers
if len(numbers) == 0:
return y , NotImplementedError("Wrong result for {0}".format(numbers))
y = numbers
y.remove(min(numbers))
return y, NotImplementedError("Wrong result for {0}".format(numbers))
print(remove_smallest([1, 2, 3, 4, 5])) # , [2,... |
91308a237cd5b5ac06c0c26d67f8dd1795819687 | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /BinaryHexadecimalConversion/main.py | 1,164 | 4.03125 | 4 | print("\n:: Welcome to the Binary/Hexadecimal Converter App ::")
computeCounter = int(input("\nCompute binary and hexadecimal value up to the following decimal number: "))
dataLists = []
for nums in range(computeCounter+1):
dataLists.append([nums, bin(nums), hex(nums)])
print(":: Generating Lists....complete! ... |
30ad077dc68f5b4f369d146dd278be4d69c89fa9 | christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | /GuessMyNumberApp/main.py | 879 | 4.09375 | 4 | from random import randint
print(":: Welcome to the Guess My Number App ::\n")
name = input("Please input your name:\n")
number = randint(1, 20)
print("We the computer are thinking of a number between 1 - 20")
print("You have 5 tries to guess the number before we blow you up. Choose wisely\n")
for x in range(1,6):... |
52a4a2e5afcf1f190f75dc69e38ef404e392be79 | rudyardrichter/globus-automate-client | /globus_automate_client/cli/callbacks.py | 6,310 | 3.5625 | 4 | import json
import os
import pathlib
from typing import AbstractSet, List
from urllib.parse import urlparse
from uuid import UUID
import typer
import yaml
def url_validator_callback(url: str) -> str:
"""
Validates that a user provided string "looks" like a URL aka contains at
least a valid scheme and net... |
8c9bf8a07c5057a5b2bdd73f2b8a84d20b4b6b7d | CichonN/BikeRental | /BikeRental.py | 3,607 | 3.984375 | 4 | # ----------------------------------------------------------------------------------------------------------------------------------
# Assignment Name: Bicycle Shop
# Name: Neina Cichon
# Date: 2020-07-26
# ----------------------------------------------------------------------------... |
63fbe3a8ecd0fd1716226f819458bc604a8faefe | dxfl/pywisdom | /try_one.py | 1,182 | 3.53125 | 4 | #!/usr/bin/env python3
'''
example adapted from stackoverflow:
https://stackoverflow.com/questions/26494211/extracting-text-from-a-pdf-file-using-pdfminer-in-python
'''
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAPara... |
c6d84e1f238ac03e872eea8c8cb3566ac0913646 | Cpeters1982/DojoPython | /hello_world.py | 2,621 | 4.21875 | 4 | '''Test Document, leave me alone PyLint'''
# def add(a,b):
# x = a + b
# return x
# result = add(3, 5)
# print result
# def multiply(arr, num):
# for x in range(len(arr)):
# arr[x] *= num
# return arr
# a = [2,4,10,16]
# b = multiply(a,5)
# print b
'''
The function multiply takes two parameter... |
12769258a066d58da3c740c75205211755481d0f | Cpeters1982/DojoPython | /OOP_practice.py | 5,376 | 4.40625 | 4 | # # pylint: disable=invalid-name
# class User(object):
# '''Make a class of User that contains the following attributes and methods'''
# def __init__(self, name, email):
# '''Sets the User-class attributes; name, email and whether the user is logged in or not (defaults to true)'''
# self.name = ... |
787b69242140019629701eaf9e35c4eb97eaec44 | Doctus5/FYS-STK4155 | /project2/nn.py | 11,991 | 3.625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math as m
#Fully Connected Neural Network class for its initialization and further methods like the training and test. Time computation is quite surprisingly due to the matrix operations with relative smallamount of datasets compared to life... |
c02f664998073d00a27a016e5edfe0f289b785b9 | aditdamodaran/incan-gold | /deck.py | 898 | 3.875 | 4 | import random
class Deck:
# The game starts off with:
# 15 treasure cards
# represented by their point values,
# 15 hazards (3 for each type)
# represented by negative numbers
# 1 artifact (worth 5 points) in the deck
def __init__(self):
self.cards = [1,2,3,4,5,5,7,7,9,11,11,13,14,15,17] \
... |
c8633e4755e9dfd08535a9806245154b042526b2 | gersongroth/maratonadatascience | /Semana 01/01 - Estruturas Sequenciais/07.py | 135 | 3.84375 | 4 | lado = float(input("Informe o lado do quadrado: "))
area = lado ** 2
dobroArea = area * 2
print("dobro do área é %.1f" % dobroArea) |
cbbe2be00332fe79c2b2f47a9ee1abf4e3606d1c | gersongroth/maratonadatascience | /Semana 01/03 - Estruturas de Repetição/02.py | 444 | 3.859375 | 4 | """
Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
"""
def getUser():
user=input("Informe o nome de usuário: ")
password= input("Informe a senha: ")
return user,password
user,passw... |
44b81e47c1cd95f7e08a8331b966cf195e8c514d | gersongroth/maratonadatascience | /Semana 01/02 - Estruturas de Decisão/11.py | 1,156 | 4.1875 | 4 | """
As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes.
Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual:
salários até R$ 280,00 (incluindo) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.