blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
dc771e5709014b7f6ab75445632907b44f4e0f57
alminhataric/Python_Basic
/12_list_comprehension/code.py
661
4.09375
4
""" numbers = [1, 3, 5] doubled = [x * 2 for x in numbers] """ ####################################################################################################### """ friends = ["Rolf", "Sam", "Samantha", "Saurabh", "Jen"] starts_s = [friend for friend in friends if friend.startswith("S")] print(starts_s) """ ...
f6525d6a0ffa7ad816792bcdae0045084f8ebf82
WhalesZhong/ADT
/QuickSort.py
924
3.71875
4
#!/usr/local/bin/python #-*-coding:utf-8-*- def QuickSort(inlist): right = len(inlist)-1 left = 0 r = right l = left stack = [] def partition(inlist,l,r): if l >= r: return inlist key = inlist [l] while l < r: while l < r and inlist[r] >= key: r -= 1 inlist[l] = inlist[r] ...
725806bb5e71ac503bdca2f38b2a6da2bbcacddb
Charles-8/ProjectStartup_Python
/Python_Part_1/ex28_print_reverse_list.py
166
4.1875
4
list = [] number = 1 while number != 0: number = (int(input("Digite um numero: "))) if number != 0: list.append(number) list.reverse() print(list)
a6b95f537ef689381b7af70f65589cbe710ea6f8
oalhamedi/Projects
/DataProjects/College/college.py
3,291
3.671875
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 16 19:49:45 2020 @author: omar """ import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np df = pd.read_csv("college_datav3.csv") # Display a regression plot for Tuition sns.regplot(data=df, y='Tuition', x="SAT_AVG...
3310c990e5707bb20952fde6d2c1bdabf997b308
KevinCastroP/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
485
3.703125
4
#!/usr/bin/python3 """ Function to return the perimeter of an island """ def island_perimeter(grid): """Calculating the island perimeter""" k = 0 c = 0 for a in range(len(grid)): for b in range(len(grid[a])): if grid[a][b] == 1: if a > 0 and grid[a - 1][b] == 1: ...
736c77ade5c8978cae7ec86bef385bb24a333a8c
Ruhami/Kalah-Python
/kalah_simulator.py
974
3.515625
4
from kalah import Kalah def parse_game(lines): steps = [] banks = [] num_board = {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "bank1": 6, "A": 7, "B": 8, "C": 9, "D": 10, "E": 11, "F": 12, "bank2": 13} for line in lines: for s in line[3:].split(): x = s.split("...
7868d087bf1d464e3f15d0e2330c5af8d6f114d8
afonsinasoares/pdti-aula01
/resposta06.py
239
4
4
#Faça um algoritmo que peça o raio de um círculo, calcule e mostre sua área # A = pi * (r * r) import math raio = int(input('Digite o valor do raio de císculo: ')) area = math.pi * raio ** 2 print("Área do circúlo = %.2f" %(area))
f2b6a321afaf78266ca5a364cbfd608a9c428b71
arhaverly/connect4-genetic-algorithm
/game.py
3,378
3.65625
4
import numpy class Game(): def __init__(self): self.board = numpy.zeros((6, 7)) self.player1_turn = True def print_board(self, file): if self.player1_turn == True: file.write('player1\'s turn\n') else: file.write('player2\'s turn\n') for row in...
d75bd13056e393d514eb3839ce77e6fc4599392a
GaoFuhong/python-code
/study7/special_class.py
506
4.125
4
# Author:Fuhong Gao #创建类的普通方法: ''' class Foo(object): def __init__(self, name): self.name = name f = Foo("Fuhong Gao") print(type(f)) #f对象由Foo类创建 print(type(Foo)) #Foo类由type类创建 ''' #创建类的特殊方法: def __init__(self, name,age): self.name = name self.age = age def func(self): print("Hello,%s." %self....
3ec8658a72e274c7f058f2d411ebc73dd1812933
daniel-reich/ubiquitous-fiesta
/79tuQhjqs8fT7zKCY_23.py
448
3.671875
4
def postfix(expr): stack = [] for a in expr.split(): if a.isdigit(): stack.append(int(a)) else: x, y = stack.pop(), stack.pop() if a == '+': stack.append(y + x) elif a == '-': stack.append(y - x) elif a ...
a0b0c8e9f16d1d4eb0bb006bcf3005451aa13be8
PythonAberdeen/user_group
/2020/2020-09/solutions/beginners/Lux-Ferre/main.py
1,185
3.75
4
import os from datetime import date data_set = {} def load_data(): data_set["Stephen King"] = date.fromisoformat("1947-09-21") data_set["Roger Federer"] = date.fromisoformat("1981-05-08") data_set["Lewis Hamilton"] = date.fromisoformat("1985-05-07") data_set["Lewis Capaldi"] = date.fromisoformat("199...
bb43ffe9d2863ff0a5f8e7a89a5247c5a0410571
A01630323/Learn-To-Program
/Mastery28.py
547
3.90625
4
print ("************************") print ("*** TIPOS DE ENTRADA ***") print ("************************") Entero1=int(input("Coloca el año de tu nacimiento: ")) Decimal1=float(input("Coloca el valor de la constante de euler: ")) Cadena1=input("Coloca el nombre de tu pais de origen: ") print() print(Entero1) print(Decima...
c0e3a5048f81f3e3243f66545e8b65003857794d
martinmarchese/scripting_practice
/BST.py
1,262
4.125
4
class Node: left, right, value = None, None, 0 def __init__(self,val): self.left = None self.right = None self.value = val class Tree: def __init__(self): self.root = None def setRoot(self,node): self.root = node def addNode(self,root,node): ...
72c010e5c184e6118d44c888719fdaee3330f399
Psycojoker/drill-progra-2017
/code/example.py
680
3.53125
4
def find(li1, li2): lx = [] lx2 = [] y = z1 = z2 = xx = yy = zz2 = 0 for a1 in li2: y = y + 1 z1 = 1 for a2 in li1: z2 = 1 for a3 in li2: if a2 == a3 and z2 == zz2 + 1: lx.append(z1) xx = xx + 1 zz2 = z2 ...
888e65c520c3e3e62053226f51bfd638a6371bcf
Cody-Hayes97/cs-module-project-hash-tables
/applications/crack_caesar/crack_caesar.py
931
3.828125
4
# Use frequency analysis to find the key to ciphertext.txt, and then # decode it. alphabet = ['E', 'T', 'A', 'O', 'H', 'N', 'R', 'I', 'S', 'D', 'L', 'W', 'U', 'G', 'F', 'B', 'M', 'Y', 'C', 'P', 'K', 'V', 'Q', 'J', 'X', 'Z'] # Your code here def decrypt(): dict = {} cipher_dict = {} result = ""...
ab1808cacd72cfd9eff29e8ba79555e2f0f32347
bukiayegbusi/Assignment2
/main.py
667
3.90625
4
x = False y = 2000 while x == False: print("£",y) y = y * 0.9 if y < 1000: x = True ##Program on how to make a cup of tea cup_tea =("Get some kettle on and pour some hot water in the cup with a teabag.") print(cup_tea) milk = int(input("Do you want milk? Enter 3 if 'Yes' and 4 if not. ")) sugar =...
9b14338d3383ad26eec0327a0f2223a6c5124326
arjunaugustine/fss16ASE
/code/3/bdayparadox.py
903
3.671875
4
from __future__ import division, print_function from random import randint import sys def has_duplicates(bdays): return len(bdays) != len(set(bdays)) def get_random_day(): return randint(1, 365) def get_random_day_list(n): bdays = [] for _ in range(n): bdays.append(get_random_day()) ret...
c25e8874ad808db83efa65b7dbc71ab2e4277558
spearfish/python-crash-course
/practice/08.10_great_magicians.py
350
3.875
4
#!/usr/bin/env python3 magicians = ['david', 'mike', 'eric'] def show_magicians(names) : for name in names : print(name) def make_great(names) : print(type(enumerate(names))) for index, name in enumerate(names) : names[index] = "the Great {}".format(name.title()) make_great(magicians...
e470bdded15bec713d1bb3509169f8c447fc5dc5
mearajennifer/melon-delivery-report
/produce_summary.py
1,140
3.90625
4
def print_report(report_lst): """ Takes in list of report names, prints out deliveries """ day = 0 # iterate through reports in list for report in report_lst: # up counter for days by 1 then print header day += 1 print("Day {}".format(day)) # open the file from ...
d6bbda7092e6e956419ba93388f3d5789c75c91d
steinitzu/inventor
/inventor/util.py
1,703
3.65625
4
class FixedDict(dict): """A dict where keys can not be added after creation (unless `extendable` is True). Keys are also marked as dirty when their values are changed. Accepts a list of `keys` and an optional `values` which should be a dict compatible object. Any key not in `values` will be implic...
0eae343e516e33fdb5e7415410f552d12eccc23c
michelprojets/Ensimag1
/BPI/TP3/ressources.py
3,500
3.546875
4
#!/usr/bin/env python3 """ manipulations complexes de tableaux : listes d'intervalles. """ class Ressources: """ On stocke une liste de ressources, compressee par plages contigues. """ def __init__(self, nombre_ressources, intervalles=None): # invariant : les intervalles sont tries par indices...
fc9e3ee150393a0837c017f7fffa1c6ae012aefb
aaqingsongyike/Python
/Python_Core/demo-20.py
756
3.65625
4
#functools 工具函数 import functools print(dir(functools)) #functools中常用函数 print("-"*20) #partial 偏函数(第一次执行默认传入的参数) print("偏函数partial") def showargs(*args, **kw): print(args) print(kw) p1 = functools.partial(showargs, 1, 2, 3) p1() p1(4, 5, 6) p1(a="python", b="itcast") print("-"*20) #wraps...
b588ba2707873be07fb9f2e4eb6fd4687057caa1
zsmountain/lintcode
/python/permutation/33_n_queens.py
1,802
4.15625
4
''' The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen...
81590eaa93b1a5b4788c1a3b29e7d0d95a1dbf3e
git-ysz/python
/day10-函数/08-拆包.py
238
3.796875
4
# 元组拆包 def return_num(): return 100, 200 num1, num2 = return_num() print(num1, num2) # 字典拆包 def return_dict(): return { 'name': 'Tom', 'age': 25 } a, b = return_dict().items() print(a, b)
37d7fe19c10d830cad93ec99467f72445a69d05b
riverfour1995/Leetcode
/27. Remove Element.py
285
3.5625
4
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ nums[:] = [x for x in nums if x != val] return len(nums) A = Solution() print(A.removeElement([3,2,1,3],3))
117e1ef964f5da83ef94177daa7f051cead1d555
eroncevich/Factoring
/bruteforce.py
499
3.8125
4
import math import sys # takes as input n and returns first found factors # returns tuple of factors or empty tuple if prime def factor(n): max_steps = int (math.floor(math.sqrt (n))) print "Max steps:", max_steps for i in range(2,max_steps): if (n % i) == 0: return (i,int (n / i)) r...
f86873db1a25311c58199af74fc209b58db9e6db
kburr6/Python-Projects
/Python Basics/Functions/next_perfect_square.py
741
4.125
4
from math import sqrt def is_perfect_square(number): if sqrt(number).is_integer(): return True else: return False def next_perfect_square(number): ''' Returns the next perfect square of the input number, if the input number is not a perfect square, returns -1. Ex: next_pe...
153a85d47045036c84a38196f0fcf0a63ae121a9
fau-masters-collected-works-cgarbin/cot6405-analysis-of-algorithms
/weighted-interval-scheduling/quiz4-question8-weighted-interval-scheduling.py
1,128
3.75
4
''' Calculates the p(i) values for a scheduling problem. p(i) is the first non-overlapping request to the left of the current request. ''' def find_p(s, f): assert (len(s) == len(f)) print('--------------------------') # visualize the requests for i, p in enumerate(zip(s, f)): print('{}: {},...
9d42729c185a5d3cd126b83690af46e619a7642f
Modupeolawuraola/python_examples
/multiply.py
419
4.15625
4
# You are given two numbers. Your task is to multiply the two numbers and print the answer. # Input Description: # You are given two numbers ‘n’ and ‘m’. # Output Description: # Print the multiplied answer # Sample Input : # 99999 99998 # Sample Output : # 9999700002 n=int(input("Enter a number here:")...
f7d3882a043df26aa823b7678de7bce112f82eb7
Bajer1515/Cryptography
/List_3/oracle.py
1,285
3.515625
4
import pdb import cipher def run(keystore_data): text_or_files = input("Would you like to run oracle for [F]iles of [T]ext?: ") number_of_entities = int(input("How many entities would you like to encrypt?: ")) if text_or_files == "F": oracle_files(number_of_entities, keystore_data) else: ...
779c803bd7d737bc87100ed431d0c1201f34203f
ifrs-alunos/rap_tutoriais
/solucoes/python/029.py
1,466
3.84375
4
#29. Um Posto de combustíveis deseja determinar qual de seus produtos tem a preferência de seus clientes. # Para isso, desenvolva um programa para ler o nome do cliente e o tipo de combustível abastecido: # 1. álcool 2.gasolina 3.diesel 4.Finalizar. # Caso o usuário informe um código inválido, isto é, fora da faixa ...
1cabeb006066211f927bccb94207674c9988f225
elfosardo/100-days-of-code
/words_counter/words_counter.py
1,146
4.125
4
import argparse import collections import fileinput def count_words(text_file): counted_words = 0 with open(text_file) as text_file: for line in text_file: counted_words += len(line.split()) return counted_words def count_most_frequent_words(lines, top): words = collections.Count...
08202c5fa6d6de90918198fa3c52449045991ee8
quanaimaxiansheng/1805-2.py
/01day/1-联系.py
442
3.59375
4
''' name=input("请输入要备份的名字") f=open(name,'r') while True: if f.read(1024) == "": break content=f.read() a=name.rfind('.') newname=name[:a]+"back"+name[a:] f1=open(newname,'w') f1.write(content) f.close() f1.close() ''' name=input("请输入你要备份的文件名") f=open(name,'r') a=f.read() position=name.rfind(".") new_name=name[:pos...
f182c0b54893c300c410b61f3241f33b4e80ef68
rsoemardja/Udacity
/Intro to Programming Nanodegree Program/07. Intro to Python, Part 3/02 Web APIs/24 Weather report/weather.py
1,276
3.859375
4
# TO DO: # 1. Have display_weather print the weather report. # 2. Handle network errors by printing a friendly message. # # To test your code, open a terminal below and run: # python3 weather.py import requests API_ROOT = 'https://www.metaweather.com' API_LOCATION = '/api/location/search/?query=' API_WEATHER = '/a...
fcd8b237ece8abb707df8ebfb003645f987a785b
traveller6168/python
/trunk/test.py
1,068
3.9375
4
#!/user/bin/python3 import sys def printinfo(str,*vartuple): print("定义的参数为:",str) print("循环取为定义的参数:") var_len = len(vartuple) print("元组个数为:",var_len) var = 0 while var < var_len: print(vartuple[var]) var += 1 print("元组测试结束!") return; printinfo(80,'test','hhh'); def ...
86c4a1c51782d51d4674ec4fcafa3bde27ff4a05
kasm2015/PythonExamples
/FlowControlExamples/for_loop.py
215
4.09375
4
#FOR LOOP EXAMPLES x=0 #print number from 0-10 using range method for x in range (0,11): print(x) #mention list of values instead of range in for loop expression for x in [2,30,45,50]: print(x)
59cc895e574940275d215b2f4c05bec1051ed688
ddsihongliang/python_learning
/rabit.py
279
3.875
4
n =input ("How many pairs of rabbits are here? ") month = input("How many months after? ") x = [n,n] + [0]*month for i in range(0, (month-2)): x[i+2] = x[i]+x[i+1] print x[i], "pairs of rabbits" print x[month-2], "pairs of rabbits" print x[month-1], "pairs of rabbits"
decf75af508e34c8804d76656e7812c4a955504b
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-4/4-1-2-6-How-functions-communicate-with-their-environment-Mixing-positional-and-keyword-arguments.py
1,733
4.65625
5
#!/usr/bin/python3 """ Mixing positional and keyword arguments You can mix both fashions if you want - there is only one unbreakable rule : you have to put positional arguments before keyword arguments. If you think for a moment, you'll certainly guess why. To show you how it works, we'll use the following simple th...
2247fa4a4fdcd4c081db516e8978e7c0d7b3824f
JumiHsu/HeadFirst_python
/nestPrint/nestPrint_old.py
2,544
4.1875
4
''' 功能:print 出一個,混和 str/int/list 形式的 巢狀 list,並在 內嵌list 前縮排。 return:無''' def a(list): print_nest_indent(list,4) # 功能差異:可在 內嵌list 前縮排。(建議使用此版本) def print_nest_indent_marson(items, indent=4): print_nest_indent_rec(items, 0, indent, " ") # 功能差異:可在 內嵌list 前縮排。 def print_nest_indent(anyList, indent=4 ):...
a2a754666c73adef74564a9aecbbbb0567a01153
Sheyma83/LPTHW
/ex3.py
488
4.25
4
# - *- coding: utf- 8 - *- print "I will now count my chickens:" print "Hens", 25 + 30 / 6 #hens count print "Roosters", 100 - 25 * 3 % 4 #rooster count #(25*3)=75 75%= 0.75 *4=3 _ 100-3=97 print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # مفيش ارقام عشرية يا حج حكيم print "Is it...
4023021bc8a84a08a88897d2069787bf5575c42b
driscollis/labs-cpp-gtest
/pyset/pyset.py
1,240
3.84375
4
class Set(object): def __init__(self): self.storage = [] def is_empty(self): if self.storage: return False else: return True def append(self, item): if isinstance(item, list): for i in item: self.storage.a...
5ff8c76167c638769cc0ee395d8f3cbe4eee48d8
juannieves17/WordCount-Interleaving-Python
/wordcount.py
2,030
3.875
4
lineCounter = 0 def word_count_dict(filename): word_count = {} # Map each word to its count input_file = open(filename, 'r') global lineCounter for line in input_file: lineCounter = lineCounter +1 words = line.split() for word in words: word = word.lower()...
d442ad0328232ffae8bb223d4d0b25843267c4bd
1Edtrujillo1/Hangman
/hangman.py
4,382
4.21875
4
# 0.0 Import modules ---- import random import time # 1.0 Define necessary functions ---- def play_loop(): """When this function is run, the game will start iteratively. Returns: Iterative game until the user stop it. """ play_game = "" input("Do You want to play?\n") while pl...
79f4e7c93e855770e74ab63483a7d5ddd06a7f70
AceSrc/datagon
/build/lib.linux-x86_64-2.7/datagon/generator/parser.py
3,152
3.75
4
class Number: def __init__(self, value=0, offset=0): self.value = value class String: def __init__(self, name): self.name = name class Function: def __init__(self, type, params): self.type = type self.params = params class Interval: def __init__(self, left=Number(), ri...
556a67c4b7ac101b78a4eef65d1c29c6b9503b2b
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex002.py
92
3.9375
4
nome = str(input("Qual o seu nome?")) print("É um prazer em te conhecer, {}!".format(nome))
eff0930aeb90113a2becc8079937bf55a0dc788b
Arihant1467/PreCourse_1
/insert_in_binary_tree.py
1,316
4.0625
4
from collections import deque class Node: def __init__(self,val): self.val = val self.left = None self.right = None class BinaryTree: def __init__(self): self.root=None def insert(self,val): if self.root==None: self.root = Node(val) els...
169c36e77f75c86fdc53c4cd5ee174f94043d431
liliumka/py_basics
/Ivanova_Tatiana_dz_3/task_1.py
1,165
4.375
4
""" 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. """ def my_divider(a, b): """ Осуществляет деление a на b. Возращает результат в видет числа с плавающей точкой, округлен...
5516d378a197f12727f33e492bcab49e4ace205e
cmkatarn/Mastermind
/Mastermind.py
1,446
3.75
4
from array import array import random sequence = array('c', [' ', ' ', ' ', ' ']) turnsTaken = 1 combinationNotYetFound = True def generate_random_number(): return random.randint(0, 4) def get_letter_from_number(number): switcher = { 0: 'R', 1: 'G', 2: 'B', 3: 'Y' } ...
fcf824789f26fa62c0edf07e5d8d94cd1440bc9f
ESMCI/github-tools
/ghtools/comment_time.py
2,835
3.859375
4
"""Class for holding the time information for a GitHub comment """ class CommentTime: """Class for holding the time information for a GitHub comment""" def __init__(self, creation_time, last_updated_time, updated_time_is_guess=False): """Initialize a CommentTime object Args: creation_...
de97cbc8a9a813a9e8f42957a339b6041499935f
Less-Zhang555/dataAnalysis
/set_range_of_axis.py
338
3.546875
4
import matplotlib.pyplot as plt import numpy as np x = np.arange(-10, 11, 1) y = x ** 2 plt.plot(x, y) # 设置x轴的显示范围,同理可得y轴 # plt.xlim([-5, 5]) # 可以调x轴的左右两边 # plt.xlim(xmin=-4) # 只调一边 # plt.xlim(xmax=4) # 只调一边 plt.xlim(xmin=0) plt.ylim(ymin=0) plt.show()
39877a3a62d13facf5d1a8f094606824360f1658
taogangshow/python_Code
/第1章 python基础/Python基础05/1-匿名函数.py
326
3.90625
4
def test1(a, b): return a+b result1 = test1(11,22) test2 = lambda a,b:a+b result2 = test2(11,22)#调用匿名函数 print("result1=%d,result2=%d"%(result1, result2)) def test3(c,d): return c+d result3 = test3(33,44) test4 = lambda c,d:d-c result4 = test4(33,44) print("result3=%d,result4=%d"%(result3,result4))
87cd70a21694b7e09d6da30a141be2d5d1acf12e
NeilCrerar/udemy-selenium-with-python
/Example_Selenium_Framework/utilities/test_results.py
3,205
3.5625
4
""" Example Selenium Framework filename: test_results.py @author: Neil_Crerar CheckPoint class implementation. Maintains a list of verification results and provides functionality to assert a final result based on whether the list contains any failures. Example: self.check_point.mark_final("test name"...
218dc3f296f6882f310f455c91b84988349ed007
JonRivera/DS-Unit-3-Sprint-2-SQL-and-Databases
/Study_Guide_Resources/Queries_Titanic.py
3,630
3.96875
4
# How many passengers survived, and how many died? # How many passengers were in each class? # How many passengers survived/died within each class? # What was the average age of survivors vs nonsurvivors # What was the average age of each passenger class? # What was the average fare by passenger class? By survival? # H...
ca99db6311777682273cbf7b30d7e684da4f5635
dorabelme/Python-Programming-An-Introduction-to-Computer-Science
/chapter11_programming4.py
3,432
3.96875
4
# Give the program from the previous exercise(s) a graphical interface. # You should have Entrys for the input and output file name and a button for # each sorting order. from chapter10_gpa import Student, makeStudent from graphics import * from chapter10_button import Button def readStudents(filename): infile = ope...
bd59fb71e4709c3f0159ea1b49f2d49d5d586d3b
NickYxy/LeetCode
/Algorithms/401_Binary Watch.py
3,130
3.71875
4
__author__ = 'nickyuan' ''' A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. For example, the above binary watch reads "3:25". Given a non-negative intege...
9b4a92285c526daf8a8dba54e2be73c9a73d5238
sobriquette/interview-practice-problems
/Coursera/Data Structures/HashFunction.py
473
3.578125
4
""" Implementations of simple hashing algorithms. The one-at-a-time hash reaches avalanche quickly, (i.e. changing a single bit produces a wildly different hash). """ def fnv_hash(key, key_len, fnv_offset_basis, fnv_prime): h = fnv_offset_basis for i in range(key_len): h = (h * fnv_prime) ^ key[i] return h def ...
e1c2482bae582cecb61e2ecdbf00e1ad91c471bd
Ashan23Perera/Data-Structures-and-Algorithms
/Sorting Algorithms/file.py
368
3.875
4
#Some random number write to Data.txt file #When Insertion,Bubble,Selection sort codes run #Inputs send by reading Data.txt file # Open a file import random fo = open("Data.txt", "wb") #Enter a amount of numbers N = input(); for i in range(0,N): w = random.randrange(0,1000,2); fo.write(str(w)); f...
e789833d0a22b32c95178cae246d4905a3e405c9
sidharthEY/darcmatcher
/matcher.py
1,533
3.515625
4
import Levenshtein from ngram_matcher import find_ngram_match from constants import LOOKUP_DICT INVERSE_LOOKUP_DICT = dict() for key in LOOKUP_DICT: for item in LOOKUP_DICT[key]: INVERSE_LOOKUP_DICT[item] = key def lookup(text): # either returns matching value or raises KeyError try: re...
4779a85bbea78213f47ad74ea67809341c1297be
learncodesdaily/PP-Pattern
/Pascals Triangle Pattern.py
393
3.75
4
def numberPattern(n): for i in range(0, n): for j in range(0, i + 1): print(function(i, j), " ", end="") print() def function(n, k): res = 1 if (k > n - k): k = n - k for i in range(0, k): res = res * (n - i) res = res // (i + 1) ...
272310720dc796edff2768c9e2a7e2e5da8a70b3
lehoangvu20031996/PyProjects
/if_elif_else3.py
227
4.25
4
# program to check weather a number is positive , negative and zero. num = int(input("Enter any number: ")) if num < 0: print("negative number") elif num == 0: print("zero") else: print('positive number')
e09abbab0a52dee216fba81f8a842980c4ac06fb
lmacionis/Exercises
/13. Files/Exercise_4.py
697
4.09375
4
""" Write a program that undoes the numbering of the previous exercise: it should read a file with numbered lines and produce another file without line numbers. """ # Some parts are copied some writen by me. numberate_file = open("newfile.txt") not_numbered_file = open("filewithoutlinenumbers.txt", "w") while True: ...
5484f645ecbbb01fa6d7150c4e875219a8bf5658
heechul90/study-python-basic-1
/Python_coding_dojang/Unit 16/for_range1.py
316
3.765625
4
### Unit 16. for 반복문으로 Hello, world! 100번 출력하기 ## 16.1 for와 range 사용하기 ## for 변수 in range(횟수): ## 반복할 코드 for i in range(10): print('Hello, world') ## 16.1.1 반복문에서 변수의 변화 알아보기 for i in range(10): print('Hello, world!', i)
75052857d773992d2d35e93d198cfd09869d8793
guest7735/kkutu
/manitto.py
954
3.640625
4
import random list_ = [] names = ["박시우", "채지훈", "이예원", "김민서", "임예영", "김은영", "송나린", "박건우", "최지송", "조석준", "오동언", "유지상", "최민규", "인태영", "이현민", "심예원"] random.shuffle(names) a = 8 member = 17 names.remove("채지훈") list_.append("채지훈") names.remove("김민서") list_.append("김민서") #print(names) #print(list_) for i in range(1, a): ...
015ffb128502d847930c4465a9cc139a2666068a
PeterZhangxing/codewars
/test_recursive.py
468
4.09375
4
#!/usr/bin/python3.5 def fib(num): ''' 用递归算法求一个数的阶乘 :param num: :return: ''' if num == 1: rec_mul = 1 else: rec_mul = fib(num-1)*num return rec_mul if __name__ == "__main__": while True: num = input("number you want to calculate the factorios :") if...
10de2c3d29081a480e221c38656fbe46327cff34
andymakespasta/Tactile_Reader
/GlobalSettings.py
1,220
3.5625
4
"""Global Settings is a container for Global Settings and reads json""" import json import os def save_settings(): f = open('settings.json','w') f.write(json.dumps(Settings, sort_keys=True, indent=2, separators=(',', ': '))) f.close() #imports user settings and creates default if no file try: f = ope...
3209a16e92f869c301e1278702632afed50955ee
DanielP-coder/Teste
/op_arit.py
299
3.921875
4
n1 = int (input("digite o primeiro valor: ")) n2 = int (input("digite o segundo valor: ")) s = n1+n2 m = n1*n2 d = n1/n2 di = n1//n2 expo = n1**n2 print ("A soma é {}, o produto é {}, a divisão é {}, ".format(s, m, d)) print ("A divisão inteira é {}, a exponenciação é {}".format(di, expo))
5f0239f2793c231c819f9f42301ae84b237c3771
preetising/function
/2.To find max value.py
151
3.75
4
def max(numbes): i=0 max=0 while i<len(numbers): if numbers[i]> max: max=numbers[i] i+=1 print(max) numbers=[3,5,7,34,2,89,2,5] max(numbers)
550e5a9774546f4b93621f09cfaa71853d8bb960
corenel/algorithm-exercises
/basics_data_structure/binary_tree.py
10,230
4.3125
4
""" Binary Tree https://algorithm.yuanbin.me/zh-hans/basics_data_structure/binary_tree.html """ import unittest from collections import deque class TreeNode: def __init__(self, val) -> None: """ Node for bianry tree :param val: value :type val: Any """ self.val...
cbbde315954424469f821d942cb328f13c27eefc
wiacekm/simplegenerator
/simplegenerator/keys.py
1,694
3.703125
4
# -*- coding: utf-8 -*- """String hashing module This module containts various methods to create string hashes. It is based on python mosules that are already avaialble """ from abstract import AbstractGenerator from Crypto.PublicKey import RSA import ecdsa import os __all__ = ['RSAKey', 'ECDSAKey'] class RSAKey(...
abf40914fbb2d2318c3ccc6606c3e635db3609a5
ezquire/python-challenges
/dutchFlag.py
401
3.5
4
def dutchFlag(arr): r = 0 b = len(arr) - 1 i = 0 while i <= b: if arr[i] == 'R': arr[i], arr[r] = arr[r], arr[i] i += 1 r += 1 elif arr[i] == 'G': i += 1 else: arr[i], arr[b] = arr[b], arr[i] b -= 1 retur...
a673003b187006ff4fa1aa9e5581ec2458d01dd9
ndjman7/Algorithm
/Leetcode/average-salary-excluding-the-minimum-and-maximum-salary/source.py
363
3.515625
4
class Solution: def average(self, salary: List[int]) -> float: max_salary = 0 min_salary = 100000000 for i in salary: min_salary = min(i, min_salary) max_salary = max(i, max_salary) count = len(salary) - 2 sum_salary = sum(salary) - (min_salary + max_...
8759f8f4e07a5f73c9a92e53d406db004024f16a
jseok1/Sorting-Algorithm-Visualizer
/SortingAlgorithms.py
4,714
4.375
4
import Visualizer def bubble_sort(screen, lst): """Bubble sort implementation in Python.""" for i in range(len(lst)): for j in range(len(lst) - i - 1): if lst[j] > lst[j + 1]: lst[j], lst[j + 1] = lst[j + 1], lst[j] Visualizer.update(screen, lst.copy(), {j, j + ...
ce60aead28baf7cf407a82ec363ecb950634bbae
PavelStransky/PCInPhysics
/python/turtle/ChasingCurve.py
4,361
3.78125
4
from turtle import Turtle import numpy as np import matplotlib.pyplot as plt VCOEF = 1.1 # Coefficient for accelerating and decelerating of the hunter def init_hunter(x=-400, y=300): """ Initializes the hunter object """ hunter = Turtle() hunter.penup() hunter.speed(...
44054b8308323d69e8adf88089270d963b925ed4
daniellopesdarocha1/python
/app.py
2,245
4.3125
4
# -*- coding: UTF-8 -*- def listar(nomes): print ('Listando nomes:') for nome in nomes: print (nome) def cadastrar(nomes): print ('Digite o nome:') nome = input() nomes.append(nome) def remover(nomes): print ('Qual nome voce gostaria de remover?') para_remover = input() if (...
b7c303431b5b297bbf4b321039afc66cd696a753
alinejeronimo/pywork
/PPZ/lista 1 - ex 8.py
76
3.78125
4
F = int(input("insira a temperatura em °F: \n")) C =5/9*(F-32) print(C)
a0c4060e0ac87280c205bb517e5edca7271011bc
xngel028/plataforma_digital2
/python/ejercicio007.py
403
4.375
4
"""" Ejercicios de operadsores matematicos """ mun1 = 5 num2 = 2 exponente = 5 ** 2 #5 suma = 5 + 2 #7 resta = 5 - 2 #3 multiplicacion = 5 * 2 #10 divicion = 5 / 2 #2.5 divi_entero = 5 / 2 #2 modulo = 5 % 2 #1 print("exponente",exponente) print("suma",suma) print("resta",resta) print("multiplicacion",multiplicacion) ...
e5ee66705596798fb8bcac78c532bdde7220de77
dsbrown1331/Python1
/ListLoops/list_intro.py
463
4.625
5
#this is how you make an empty list empty_list = [] #here is list with three integer elements three_nums = [1,2,3] #we can access elements in the list using [] print("Printing out items in list:") print(three_nums[0]) print(three_nums[1]) print(three_nums[2]) #we can have lists of strings days_of_week = ["Sun", "Mon...
9bbdc674928cf1e96bd26bd00b6bc89782df833f
albertmenglongli/Algorithms
/DP/placePlot.py
1,886
3.59375
4
def count_ways_2n_rec(n): if n == 0: return 0 if n == 1: return 1 if n == 2: return 2 return count_ways_2n_rec(n - 1) + count_ways_2n_rec(n - 2) def count_ways_2n(n): if n == 0: return 0 if n == 1: return 1 if n == 2: return 2 a, b = 1, ...
9aa074cdfb589acf79b87fcad5f8034ed25d7369
erika-jing/Test_PythonProject_jing
/zuoye/money.py
731
3.640625
4
''' 原有存款1000元,发工资之后存款变为2000元 定义模块 1. money.py saved_money = 1000 2. 定义发工资模块 send_money,用来增加收入计算 3. 定义工资查询模块 select_money 用来展示工资数额 4. 定义一个start.py 启动文件展示最终存款金额 ''' saved_money = 1000 def send_money(): send_money = 1000 global saved_money print(f"发工资前,有存款{saved_money}元") saved_money = saved_money + sen...
fe8f85895295dee5c253ebf9bc9cd891cc3c3f85
StonyBrookNLP/wumpus-python
/utils/string_utils.py
860
3.84375
4
__author__ = 'chetannaik' def is_valid_sentence(sentence, tokens): # Sentence has just one full-stop. if sentence.count('.') != 1: return False # Sentence doesn't have the following symbols. if any(symbol in sentence for symbol in ['?', '_', '<']): return False # Sentence length ...
e151e515bbbc51884d2ab085b8cbe18695735165
derickdeiro/curso_em_video
/aula_17-listas-pt1/desafio_79-valores-unicos-lista.py
828
4.1875
4
""" Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente. """ lista = [] while True: numero = int(input('Digite um númer...
83a0930d9c9bdefb046b35535350679cb9c911e0
moontree/leetcode
/version1/826_Most_Profit_Assigning_Work.py
2,313
3.84375
4
""" We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job. Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i]. Every worker can be assigned at most one job, but ...
84fc62cb037f2464c643557b8b084488a24131e5
CiprianBodnar/BattleShip
/BattleShip/BattleShip.py
2,347
3.6875
4
from random import randint import os # x->ratat # O-> neatins de nimic # 1-> nava # *->distrus # in aux tin navele # in board tin focurile def createTable(size): boardGame=[] for i in range(0,size): line=["O"]*size boardGame.append(line) return boardGame def customP...
630a5e5d73670fc02838c29851536a351401a784
asperaa/programming_problems
/linked_list/ll_create_prac.py
2,278
4.5
4
# Class for Node class Node: # function to initialise the node def __init__(self, data): self.data = data # adding data to the node self.next = None # pointing the next of node to null # class for linked list data structure class LinkedList: # function to initialise a linked l...
eea1d30f97c3bea1faba3a04bb85f1e89d018896
Kenny-WilliamsStockdale/PythonPlay
/adventure_game.py
5,087
3.84375
4
# Start adventure at the forest - can go left to the mountain or right to the castle. Which way do you want to go? # variable choice # if choice is = input something # elif the other choice #print final outcome for choices import PySimpleGUI as sg """ Adventure Game - open and closing windows simultaneously. ...
4130731717ac4147e5a73e688c45ac102fe9b80a
nolanev/Distributed-File-System
/Database.py
382
3.71875
4
import os import os.path def find_file(filename): print("the file we are looking for is ", filename) if filename in os.listdir("DB_Files/"): print("file exists on db") file_path= "DB_files/" + filename return file_path else: print("file does not exist on db. creating file") file_path= "DB_files/" + file...
0e2f122cc81ff0a59b1c608348fa95339bd993da
younkyounghwan/python_class
/lab6_3.py
2,439
3.90625
4
""" 쳅터: day 6 주제: class 문제: fraction 클래스는 애트리뷰트로 numer(분자)와 denom(분모)를 가진다. 초기화하는 메쏘드를 정의하라. 작성자: 윤경환 작성일: 18 10 23 """ #분수 클래스 정의 class Fraction: def __init__(self,n,d): """ 분수를 초기화하는 메쏘드 :param n: 분자에 해당하는 값 :param d: 분모에 해당하는 값 """ self.numer=n self.denom=...
1f029b85e3b14c26f37d1d6765228c83c9a206ba
Capoqq/InteligenciaComputacional
/segunto taller/punto7.py
241
3.609375
4
añosAntiguedad = int(input("Escriba sus años de antiguedad")) if añosAntiguedad >= 1: bonoInicio = 100000 bonofinal = (añosAntiguedad - 1)*120000 + bonoInicio else: print("No tienes la antiguedad necesaria") print(bonofinal)
9762c0c7218ce91146869bfa0928b9a3e81953f7
vpontis/euler
/243.py
1,775
3.84375
4
# we know a fraction is divisible by anything it shares common factors with # so what we can do is find out the prime factorization of the number # then we want to know how many numbers the prime numbers knock off # so we take multiples of the prime numbers up to the frac and store that in a set # 1-len(set) is going t...
345b1dd584a8ed4622ea745faa48ad9f38509dd9
SAR0S/python-algorithm
/basic/least_common_multiple.py
346
3.75
4
def calc_LCM(a, b, c): i = 2 while i <= a * b * c: if (i % a == 0) and (i % b == 0) and (i % c == 0): break i = i + 1 print("{}, {}, {}의 최소공배수 : {}".format(a, b, c, i)) if __name__ == "__main__": a, b, c = map(int, input("세 가지 숫자 a b c 입력> ").split()) calc_LCM(a, b, c)
6c7a24869988f4c9fb4c9317a5769dc036b5237f
arturchique/labs_and_kourses
/TeorgraphKp8/kp8var1.py
2,197
3.53125
4
# библиотеки для ввода данных пользователем from tkinter import * from tkinter import messagebox from tkinter import ttk # библиотеки для работы с графом и его визуализации import networkx as nx from networkx.algorithms.shortest_paths.generic import shortest_path root = Tk() root.title('Enter matrix size') nodes_cou...
e338acdbeaf33e6c12691d60cff2899df3ca41e9
ospluscode/Tree
/binaryTreeList.py
2,149
4.09375
4
# Binary Tree implementation using List # Create Traverse Search Insert Delete # Binary tree has always at most 2 children # Creating is O(n), rest is O(1) # Linked list Insert is O(n) but also spcae complexity is O(n) class BinaryTree: def __init__(self, size): self.customList = size * [None] self...
e1d35a40769de3f45cc87fc614673e01f25a7f53
Legion-web/Refresh
/Calculator(2).py
295
4.34375
4
num1=float(input("Enter a number:")) op=input("Enter operator:") num2=float(input("Enter a second number:")) if op=="+": print(num1+num2) elif op == "-": print(num1 - num2) elif op == "*": print(num1 * num2) elif op == "/": print(num1 / num2) else: print("Invalid operator")
2d595097fe603e7f85f982e512bcefe002118f90
tianyunzqs/LeetCodePractise
/leetcode_81_100/97_isInterleave.py
3,169
3.875
4
# -*- coding: utf-8 -*- # @Time : 2019/7/28 23:00 # @Author : tianyunzqs # @Description : """ 97. Interleaving String Hard Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. Example 1: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true Example 2: Input: s1 = "a...
37fa5429c9e7f09cc602e952e66ad18e2417b010
BenTildark/Project_py
/functions/multiplier.py
242
3.921875
4
def times_two(multiplicand): multiplier = 2 return multiplicand * multiplier number = 5 # bigger_number = times_two(number)​ # print("{} * 2 = {}".format(number, bigger_number))​ print("{} * 2 = {}".format(number, times_two(number)))
d17158c9d2dfc78712287732ddb7bb602d07e1c5
ultra161/python
/lesson-2/L2p5.py
536
3.65625
4
my_list = [7, 5, 3, 3, 2] m = 'y' print("Текущий рейтинг:", my_list) while m == 'y': i = int(input("Введите новый элемент рейтинга:")) n = 0 for el in my_list: if i > el: my_list.insert(n, i) i = 0 n = n + 1 if i != 0: my_list.append(i) print("Текущий ...
0ccaea8697cf5727cf37a6e21eb4557a5093469c
theYBFL/20.21.10.1
/10a-if4.py
162
3.703125
4
ort=55; #0-100 if ort<50: #ort>=50 print("1") elif ort<60: print("2") elif ort<70: print("3") elif ort<85: print("4") else: print("5") print("aaa")
dff7aa92382e10a11928888508c72697dbbcd7ff
AlexanderSoftman/battle_field
/battle_field/slam/least_squares_method.py
925
3.59375
4
import logging LOG = logging.getLogger("least_squares_method") # input: list of tuples - [(x1,y1), (x2,y2), ... ] # output: (k, b) if line is y=kx+b or (x value) if line is x=3 # None if count of dots == 0 def approximate_line(dots): x_sum = 0 y_sum = 0 x_square_sum = 0 xy_sum = 0 count_of_dots =...
426cecbaa931ab5fea3fbdf4c8e28d69cf64607c
mccornet/project_euler_2014
/problem_084.py
4,525
3.65625
4
from random import * from collections import Counter from collections import deque """ Monopoly Odds - Project Euler 84 The heart of this problem concerns the likelihood of visiting a particular square. That is, the probability of finishing at that square after a roll. For this reason it should be clear that, with th...
bcee0f6ac4f8b07773a64dc47b715b168b9bcefb
hernanrengel/test-excercise
/main.py
389
3.921875
4
import math # get the result of the operation def getSquare(n): calc = (3 + math.sqrt(5))**n # format the entire result result = "{:.5f}".format(calc) # return a string splitted by "." # and getting the last 3 characters of the result return str(result).split(".")[0][-3:] for n in range(1, 31)...