blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
692995abf9f738ff1123dc99bf09d3760abe6cf2
tatumgb/rps
/RPS.py
1,108
4.125
4
#Program plays three games of rock, paper, scissors # imports input program from choice_choice import choice def compare ( choice1, choice2): """compares rock, paper, scissors""" if choice1 == "rock": if choice2 == "rock": print ("tie") elif choice2 == "paper": print ("paper...
d7a844d6241edf6b4ca3e9fe5b4ee9ea4e9a00ab
v-nitisha/Minerva-a-Personal-Assistant-Project
/SpeechRecognition001/ConvertMP3toWAV.py
1,122
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 22 15:49:55 2020 @author: Vera J. Morgana """ import os from pydub import AudioSegment def convertOne (file, name): mp3_sound = AudioSegment.from_mp3(file) #rename them using the old name + ".wav" mp3_sound.export("{0}.wav".format(...
904ce54abd3d6fb34a6b881c7a2579ab45695ade
DavidBorstner/FaksNalogePreverjanja
/1. letnik 17_18/Programiranje1/Naloge/Naloga01Dodatna.py
1,056
3.640625
4
import random import math from math import* DolzinaStrela = random.randint(10000,50000) print("Vpiši vrednosti, da boš lahko zadel cilj, ki se nahaja na dolžini: " + str(DolzinaStrela) + "m. Zadenite ± 1000 od cilja.") cilj = 0 kot_topa =0 hitrost = 0 DolzinaMinus = DolzinaStrela - 1000 DolzinaPlus = DolzinaStrela + 10...
14247d6758af0df556163a0ee3d3526f55a4f78b
Danielarwj/CSE
/notes/OOP Notes.py
1,540
4.21875
4
""" Objects have two main characteristics: Attributes and behavior. The object parrot has the name,age,and color as attributes and dancing and singing as behavioral patterns """ """ The term DRY- Don't Repeat Yourself- is used widely with OOP programming OOP follows some very basic concepts: Inheritance- The process ...
22bfc600a809bd8970851aa579c817dda927110e
DanielFloripa/assessment
/tests/config.py
792
3.671875
4
books_list = [ { 'id': 1, 'title': 'Java How to Program', 'author': 'Deitel & Deitel', 'edition_year': 2007 }, { 'id': 2, 'title': 'Patterns of Enterprise Application Architeture', 'author': 'Martin Fowler', 'edition_year': 2002 }, { ...
219e150d8b98bc414f13140076893e00249b8648
malbasini/Corso-Python
/Set/Program.py
662
4.03125
4
def Set(): myset = set()#CREIAMO UN INSIEME VUOTO myset = set([10,20,30,40])#CREIAMO UN INSIEME INIZIALIZZATO myset={10,20,30,40}#CREIAMO UN INSIEME INIZIALIZZATO #myset{} ERRORE STIAMO CREANDO UN DIZIONARIO VUOTO myset=set() myset.add(10) myset.add(20) myset.add(30) myset.add(40) ...
4810ae2c0b0092675f06faba8521a795df6c9523
b1ueskydragon/PythonGround
/dailyOne/P143/three_partition02.py
672
4
4
def three_partition(x, lst): """ O(n) time and O(1) space :param x: pivot :param lst: list :return: """ left, right = 0, 0 last = len(lst) - 1 while right <= last: if lst[right] == x: right += 1 elif lst[right] < x: swap_value(lst, left, right...
167532ab968772a04d9121fd2fd0ef3bdf1ec564
Jason30102212/python_basics_refresher
/19.ForLoop.py
350
4.21875
4
# 19.ForLoop array = ["one", "two", "three"] for letter in "This is a string": print(letter) for name in array: print(name) for index in range(3, 10): print(index) for index in range(len(array)): print(index) for index in range(5): if index == 0: print("First Iteration") el...
858b7e352e6f45098dea839ec1747c8b2157039b
sysuwsh/My-Leetcode-Solution
/python/116填充每个节点的下一个右侧节点指针.py
1,966
3.90625
4
class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next # 递归的方式,注意递归中解决问题的方式,是从中间最紧密的部分进行递归操作的 class Solution2: def connect(self, root: 'Node') -> 'Node': ...
e57b069af722c091c113e550cdc4f1e44b2f534b
dalealleshouse/learn_python
/fundamentals/comprehensions.py
830
3.65625
4
#!/usr/bin/env python3 from math import factorial, sqrt import os import glob words = ("Why sometimes I belived as many as six impossible things before " "breakfast").split() x = [len(word) for word in words] print(x) # list f = [factorial(x) for x in range(20)] print(f) # set f = {factorial(x) for x in r...
fa34699c6acc8c8699fe8f87b4f2a4a0109797d6
Sangavi-123/HackerRank-samples
/cutTheSticks.py
1,088
3.921875
4
#Library imports/dependencies #____________________________ import pandas as pd import numpy as np import re #code flow #_________ #get array from user or default #______________________________ arr=[1,2, 3, 4, 3, 3, 2, 1] l=len(arr) #looping logic #_____________ while(l!=0): count=len(arr) print(count) ...
25ac38a5e2060b80c5629844ed8318b4f1465d9b
krzysztof-adamski/bl-predictor
/bl_predictor/models.py
18,506
3.609375
4
""" This module contains code for different prediction models. """ import numpy as np import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf from scipy.stats import poisson class PoissonModel: """ A model that predicts the winning team out of two given teams, based on a po...
10c85bd661192dcedcdc92c959f6259748448a7b
kyleicban/Optimization-Algorithms
/secant.py
857
3.5625
4
import math def secant(f, p_0, p_1, tol, it_max): it = 2 q_0 = f(p_0) q_1 = f(p_1) while(it - 1 < it_max): print("Iteration: " + str(it - 1)) print("q_" + str(it-2) + " = " + str(f(p_0))) print("q_" + str(it-1) + " = " + str(f(p_1))) p = p_1 - q_1*(p_1 - p_0)/(q_1 - q_0...
7a29a2bc50311fad0f5edd613f6361345d261aa9
FibrePhotonics/Fresnel-Diffraction
/fresnel_diffraction_from_a_slit.py
2,494
3.71875
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 26 11:45:42 2014 Fresnel Diffraction From A Slit @author: Stephen James, Cranfield University """ import scipy import numpy as np from scipy.special import fresnel import matplotlib import matplotlib.pyplot as plt d = 0.75 # slitwidth mm lam = 2.66e-4 ...
e2aa47011c92592966d6146713f660f60080395f
chuqidecha/leetcode
/leetcode100/leetcode100.py
1,254
3.8125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 18-7-28 下午5:01 # @Author : yinwb # @File : leetcode100.py # Definition for a binary tree node. from collections import deque class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Soluti...
5ebc6a1ee90fff98e3d62491d82f0608630bddf4
MarkovAnton/Problem-solving-with-LeetCode
/35.Search_insert_position.py
359
3.5
4
''' Ссылка на описание задачи: https://leetcode.com/problems/search-insert-position/ ''' class Solution(object): def searchInsert(self, nums, target): try: ind = nums.index(target) except: nums.append(target) nums.sort() ind = nums.index(target) ...
1ad28cdaed2c64fa25054fd2b700e5bf8e1b4e2c
srina1h/DAA
/Assignment-1-205/Selection Sort/selsort5.py
593
3.765625
4
def minimum(a,low,high): n = len(a) mini = 100000 index = low for i in range(low,high): if(a[i] < mini): mini = a[i] index = i return(index) def selsort(a): n = len(a) for i in range(n): x = minimum(a,i,n) temp = a[i] a[i] = a[x] a[x] = temp print("FINAL SORTED ARRAY") print(a) print("ente...
6926013d46a5692d6c91c30b9108276b6f4ac865
annyhiss/switch_tosin
/classwork.py
706
4.03125
4
WORD_LIST = ["name","class","place","team","switch"] import random def pick_word(listword): return random.choice(listword) def get guess(): guess=input("Guess a word : ") if not guess=="": return guess else: print"word cannot be empty" get_guess() def evaluate guess(): wo...
99c8b8b735b20de80ff3de56bd77e7d362c84691
harihavwas/pythonProgram
/Exam/Exam 2/ani_dog.py
651
3.859375
4
class Animal: def __init__(self,name,cat): self.name=name self.cat=cat def printval(self): print("Name : ",self.name) print("Category : ",self.cat) class Dog(Animal): def __init__(self,life,age,name,cat): super().__init__(name,cat) self.age=age self.li...
7cd95284564a9c4a2170d4bb0db6457b82cf8283
conservativeghosts/CT_codesandstuff
/listAppV3.py
3,643
4.25
4
import random """ Program Goals: 1. Get the input from the user! 2. Convert that input to an INT 3. Add that input to a list 4. Pull values from a specific intex positions """ listyBoi = [] unique = [] def mainProgram(): while True: try: print("yo, we're gonna work with some list...
d3651c22a7509d613041cdf333090901984a28eb
shreybm26/Tkinter-Basics
/SPS.py
3,963
3.515625
4
import tkinter import random from tkinter import StringVar, END, BOTH from PIL import ImageTk, Image #define window root=tkinter.Tk() root.title("The Stone Paper Scissor Game") root.iconbitmap("icon.ico") root.geometry("800x800") root.resizable(1,1) #defining the internal logic of the game a="stone" b="...
e32f2a70a6332605b848ee02a03886337166b742
sa1ntsadosn/lab1
/programm6.py
242
3.9375
4
print('Введите четырёх значное число:') a = int(input()) b = a a = b%10 b = (b*0.1)//1 c = b%10 b = (b*0.1)//1 d = b%10 b = (b*0.1)//1 f = b%10 print('Произведение цифр числа', a*c*d*f)
5f3219d42cda504a6a31ecb2e28959b16f97647e
filippo82/microbit
/mpl_seis_animation_simple.py
859
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 9 21:26:04 2018 @author: filippo """ """ ===== microseisms ===== This example showcases a real-time animation of a microbit accerleromter. """ import serial, time import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as a...
f20e527028069d86f616c95efad4e2f2b08ebd01
iamshubhamsalunkhe/Python
/nested_function/nested_func.py
238
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 14:52:56 2019 @author: Shubham """ #nested functions def gm(): print("Good Morning") def hello(): gm() print("HELLO") def welcome(): hello() print("Welcome") welcome()
8a729f119612acf6b08b2b9d5ed08a594cbf9c54
eric496/leetcode.py
/backtracking/79.word_search.py
1,444
3.953125
4
""" Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F',...
9ddc32bdb7c6f7ed1019ff87c749ad3a799a32de
kirillzx/my_python
/HW_2/str_op.py
235
3.859375
4
s = 'У лукоморья 123 дуб зеленый 456' print(s.find('я')) print(s.count('у')) if s.isalpha() == False: print(s.upper()) if len(s) > 4: print(s.lower() ) print(s.replace('У','О'))
1d975e62147deb01312e7d7ae15648ea455bb566
maoxiaomai/Py100
/Py100/1-50/024.py
354
3.828125
4
# -*- coding: utf-8 -*- # 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 # 程序分析:请抓住分子与分母的变化规律。 fenzi = 2 fenmu = 1 result = [] for i in range(1, 21): result.append(fenzi/fenmu) fenzi, fenmu = fenmu + fenzi, fenzi print(result) print(sum(result))
dd6f9c29eb2e1c76064db12035e5a3769694cd1c
chandmohammad21/SQL-GUI-Utility-Python-Tkinter
/SqlGUI/SqlGUI.py
6,930
3.59375
4
from tkinter import * import pyodbc # Function to connect to SQL Database def connect(server, database, username, password): conn = pyodbc.connect( 'DRIVER={ODBC Driver 17 for SQL Server};' + ';SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + pas...
72334714a377f6f45271484a05e8d08e2c5f4f13
sushantbhai/sequrity-system
/sequrity system project.py
995
4.1875
4
users = ["Ram","Shyam","Shiv","Sundar","Suraj","Sushant","Chikki","Khanak","Sonali","Pallavi"] print(len(users)) while True: print("Hi! My name is chitthi and I am the security system robot.") name = input("What is your name?: ").strip().capitalize() if name in users: print("Hello ...
d724c9afe87eb109101c0bf78847dfbb2a0507a4
matthewdoles/python-practice
/zelle-python/chapter04/graphicsexamples.py
1,408
3.875
4
from graphics import * def graph(): win = GraphWin() p = Point(50, 60) p.draw(win) p2 = Point(140, 100) p2.draw(win) input("Press enter to exit") win.close() def graphshapes(): win = GraphWin('Shapes') center = Point(100, 100) circle = Circle(center, 30) circle.setFill('r...
66b77c2200cba23c7704eb77405fa4e361c5865d
antonplkv/itea-october
/lesson_18/source_code.py
282
3.96875
4
import random def number_randomize(quanity): if not isinstance(quanity, int): raise TypeError('Wrong type') numbers = [0, 2, 3, 4, 5, 6, 7, 8, 9, '1', '2', '3'] for i in range(quanity): yield random.choice(numbers) print(list(number_randomize(3)))
c243ac391e2b8707d7aa10a06505db7bad848925
KonradG666/SQL
/SQL2.py
2,154
3.640625
4
import sqlite3 def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: ...
857c5faad444fd23c4bbb4ca277720bf1ff7bdec
Zaitov-RM/Home_Works
/Курс Основы Python.Домашки/Функции/Функции.4.py
570
3.953125
4
name=str(input("Введите имя игрока №1 ")) player={"name":name,"damage":40,"health":100,"armor":3} name=str(input("Введите имя игрока №2 ")) enemy={"name":name,"damage":50,"health":100,"armor":2} print(player["name"]) print(enemy["name"]) def attack(player1,player2): player2["health"]= player2["health"]-dam_arm...
9db98d0e71afe1cd3d04ab33956eb1dd48b43b2f
code-project-done/Algorithms_for_Competitive_Programming_in_Python
/Graphs/count_connected_components.py
1,158
4.09375
4
""" We use DFS here to count the connected components There is another method using union find, see the example in Data_Structures/union_find.py """ from collections import * """ It is a little bit heavy, need 2 functions and the function dfs have a lot of arguments usually it is nicer to implement with just one func...
40692668de763e34b388343eeb79198f1c9e13c3
ChandanVerma/DataStructures-Algorithms
/yt_ds/yt_ds_1.py
775
3.984375
4
spendings = [2200, 2350, 2600, 2130, 2190] ## In Feb, how many dollars you spent extra compare to January? print(f'In feb money spent is {spendings[1] - spendings[0]}') ## Find out your total expense in first quarter (first three months) of the year. print(f'Spending of first quarter is {sum(spendings[0:3])}') ...
2734b3f4d4d517988076c52e3f293c89893d34d3
stldraxvii/code
/prime.py
341
4.15625
4
from factors import list_factors def find_primes(num): factors = list_factors(num) primes = [] for j in factors: if factors[j] == 'Prime': primes.append(j) return primes def main(): num = input("Enter a number:") num = int(num) print(find_primes(num)) if __name__ == '_...
690167ffdcb1d4a64f4bc171d8ea5a73d52af738
alvaresrubens/listas-python
/Lista 05/Exercicio6.py
336
4.28125
4
from unicodedata import normalize nome = input("Digite o nome de uma pessoa:") nome = normalize('NFKD', nome).encode('ASCII','ignore').decode('ASCII') nome = nome.lower() if "maria" in nome or "jose" in nome: print ("O nome digitado possui o prenome", nome) else: print ("O nome digitado não possui o prenome M...
18614c4b1a2344bc66c5dcedb24164e55ebc3c22
BhushanTayade88/Core-Python
/March/day 11 decorator/task2/dynamicdecorator.py
391
3.71875
4
def repeat(n): def call_printer(func): def inner(args): for i in range(n): print("*" * 15) func(args) print("*" * 15) return inner return call_printer a=int(input("How many times u want repeat msg :")) @repeat(a) def printer(ms...
cc5e55ffcfd525e33ff68dcd1a6dc711fa4a9599
xyktl/python-study
/02_函数/hm_03_打印分割线.py
435
3.578125
4
def print_line(char,times): """打印单行分割线 :param char: 分割线字符 :param times: 打印次数 """ print(char * times) def print_lines(char,times,lows): """打印多行分割线 :param char: 分割线字符 :param times: 每行打印的次数 :param lows: 行数 """ low = 0 while low <= lows - 1: print_line(char,time...
f71d84c461e46807941eeb51a83f6cb2ea422de6
Dadajon/100-days-of-code
/competitive-programming/hackerrank/algorithms/13-kangaroo/kangaroo.py
832
3.8125
4
#!/bin/python3 def kangaroo(x1, v1, x2, v2): """ Complete the function kangaroo. :param x1: starting position for kangaroo 1 :param v1: jump distance for kangaroo 1 :param x2: starting position for kangaroo 2 :param v2: jump distance for kangaroo 2 :return: return YES if they reach the sa...
00cd5265dfbc11c8923f05b22dbb9eea9c24a784
luchen29/Algorithm-Practice
/704_Binary_Search_None_recursion.py
669
3.75
4
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # None recursion method if not nums: return -1 start = 0 end = len(nums)-1 while(start <= end): ...
f0937abadb45c0c3a44e847dafa0f8dc32e8a57d
xiangjiaowangzi/demo
/demo/basic_grammar.py
2,028
4
4
# 多变量赋值 x, y, z = 10, 15, 20 x, y = z, x print("x: %d y: %d" % (x, y)) # 使用input等待用户输入 # msg = input("请输入内容") # print("内容是: " + msg) # 查看变量类型 print(type("字符")) print(type(5)) print(type(4.15151)) # 基本语句 # x = 0 # z = 1 if (x > y): print("x") elif (y > z): print("y") else: print("z") for letter in range...
1cb897ea38dd2a8c2e23dd59321eda096b19e78f
artur-oganesyan/python_basics
/lesson_3/task_1.py
470
4.03125
4
def divide(dividend, divisor): """ Quotient rounded to two decimal places """ try: dividend = float(dividend) divisor = float(divisor) result = round(dividend / divisor, 2) except ZeroDivisionError: result = "Division by zero is impossible" except ValueError: ...
30a46db97a1b339e11bcb60199131ef43e916310
earosselot/Python_UNSAM
/ejercicios_python/Clase01/esfera.py
161
3.625
4
# Ejercicio 1.13 # El volumen de una esfera import math radio = float(input('ingrese un radio de esfera: ')) volumen = 4/3 * math.pi * radio**3 print(volumen)
c3ee097732687f59416084f173f1d824652394b3
ChRiStIaN3421/programacion
/unidad_3.1/ejercicio30.py
495
4.09375
4
""" El programa debe: * Pedir al usuario una palabra * Verificar que sea una palabra y no un numero * Mostrar por pantalla las letras una a una * No producir errores """ while True: try: palabra=input("ingrese una palabra : ") if palabra.isalpha(): for i in (palabra): ...
f53784d2602857fe4e736240a97f09ab1a2662a1
y226xie/Documentations
/7. Python Notes/arrays.py
534
4.09375
4
# Arrays # Basic syntax cars = ["Ford", "Volvo", "BMW"] # An array is a spefial variable which can hold more than one value at a time # An array can hold many values under a single name, and you can access the values by referring to an index number # Access the elements of an array x = cars[0] length = len(cars) ...
adfe6bb77d5868893a831b21ad13aa015fe95fae
liberbell/py20
/basicpro.py
5,116
4.09375
4
# salary = int(input("Enter your salary amount: ")) # expenses = int(input("Enter your expenses: ")) # saving = salary - expenses # print("My total savings in a month is: ", saving) # first_num = int(input("Enter first variable: ")) # second_num = int(input("Enter second variable: ")) # first_num = first_num + secon...
3ecbb8c54f8ea6e5ce8bb17f5cf2e0abab8ef7f3
bisonliao/daydayup
/mxnet/rnn_classify.py
8,193
3.625
4
''' 让rnn学会对一个数学表达式的结果正负做判断 例如 "1+2"分类为正 "4-9"分类为负 ''' import mxnet as mx import mxnet.ndarray as nd import gluoncv import mxnet.gluon as gluon from mxnet.gluon.model_zoo import vision import mxnet.autograd as autograd import numpy as np import matplotlib.pyplot as plt import mxnet.gluon.nn as nn import mxnet.gluon.rnn...
24b04e68b0f8657d0b3ce8954debd831e48b131e
libowei1213/LeetCode
/56.合并区间.py
1,832
3.5625
4
# # @lc app=leetcode.cn id=56 lang=python3 # # [56] 合并区间 # # https://leetcode-cn.com/problems/merge-intervals/description/ # # algorithms # Medium (44.53%) # Likes: 833 # Dislikes: 0 # Total Accepted: 201.3K # Total Submissions: 450.7K # Testcase Example: '[[1,3],[2,6],[8,10],[15,18]]' # # 以数组 intervals 表示若干个区间的...
02d916c57e83297d93597da74ddd5e98f0b65442
NickBarty/Python-Interactive-Kivy-Project
/test_songlist.py
1,713
4.3125
4
""" Tests each method of the SongList class showing how each one works at an individual level """ from songlist import SongList from song import Song song = Song("Amazing Grace", "John Newton", 1779, True) # test empty SongList song_list = SongList() print(song_list) assert len(song_list.songs) == 0 # test loading s...
b92697db9801c3a592cd27fbeff839d684c040f5
usamalatif/Assignment---RA-ITU
/foreach.py
138
3.71875
4
def Sqr (x): return x*x def ForEach(Function,Array): for i in Array: Function(i) return True ForEach(Sqr,[1,2,3])
9cc5c33d16fde7763ba86b87f737a0c51897d3c0
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/1f964bda08864da1b833598762d82578.py
423
3.59375
4
class Bob(object): def hey(self, sentence=""): """ Receive a sentence and reply as a lackadaisical teenager @type sentence: string """ if not sentence or not sentence.rstrip(): return "Fine. Be that way." if sentence.isupper(): return "Woah, ...
466ecf4b84b09b2da8fe1838ad4dfa6eb8278548
Dkillingjoker/python
/text_wrap.py
627
4.15625
4
""" You are given a string and width . Your task is to wrap the string into a paragraph of width . >>Input Format The first line contains a string, S. The second line contains the width, w. >>Output Format Print the text wrapped paragraph. """ import textwrap def wrap(string, max_width): ...
5930855fe3c572b404123e4e351a280ba1fb69da
japeto/script_python
/scripts_mods/script_panda.py
1,568
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 5 15:54:45 2020 Pandas es una biblioteca con fundamento en numpy, su dato base es el DataFrame @author: japeto """ import numpy as np import pandas as pd # ============================================================================= # Crear una ser...
c5a3471e58def718acee502c6ae14af0ce1054aa
Samuel-Giftson/Global_Sequence_Alignment
/main.py
3,214
3.5625
4
from displayTable import DisplayTable as display from userErrorChecking import UserErrorChecking as error_check from tableCalculation import TableCalculation as table_calculate def main(): print("Welcome to Global Sequence Alignment") print("Information I need from you. Two strands, gap penalty, mismatch, and...
d62739c10f910bd217c9696b8bc7f4217bd07c0a
yujingsong1206/test
/demo.py
1,035
3.609375
4
#模拟抽奖 #中奖等级:一等奖,二等奖,三等奖 #中奖的范围: # [0,0.05)一等奖 # [0.05,0.4)二等奖 # [0.4,1.0)三等奖 #模拟这次有1000个人来参加活动,最后输出各个奖项的中奖人数 #判断中的是几等奖 写成一个函数 import random def lucky(): num = random.random()#[0,1) if(0<=num<0.05): return "一等奖" elif(0.05<=num<0.4): return "二等奖" else: re...
8ea6e95805901393d40570a147943ac0b1310674
Zjias-s/Electronic-dictionary-project
/dict_client.py
3,701
3.625
4
from socket import * import sys import getpass def main(): if len(sys.argv)<3: print('argv is error') return HOST=sys.argv[1] PORT=int(sys.argv[2]) s=socket() try: s.connect((HOST,PORT)) except Exception as e: print(e) return while True: prin...
6b8e6d7a512079f639cc32d5dadbeb8b7c9efde2
IrinaLokhvytska/PythonElementaryTasks
/manufacture.py
1,175
3.71875
4
class CarsManufacture(): cars = list () def __init__(self, country, city): self.country = country self.city = city def produceCar(self, kind, price, colour): cars = self.cars cars.append({kind: {'price':price, 'colour': colour}}) return Car(kind, price, colour) ...
77f369b7ca59a86807ea2f733da683c177bd5c3c
superhet/Python-Examples
/for_log.py
157
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 24 12:12:40 2014 @author: Alois_W """ n = 101 sum = 0 for i in range(1,n): sum = sum + i print (sum)
a1b09a2895e1d27eddd531cbc19c3535927441e4
hesajs/csit
/CA/add-8bit-signed-numbers.py
1,051
4.25
4
''' Program to add two 8-bit SIGNED numbers by using 2’s complement method ''' def check_8bit(x , y): if (len(x) and len(y))!=8: return True return False def signed_twos_complement(x, y): counter = len(x)-1 sum1 = [] carry=0 for i in range(0, 8): temp_sum = int(x[counter]) + in...
59658cf05a54e4a57f45925e24fbec4959e3ccf9
byung-u/HackerRank
/Algorithms/Implementation/breaking_the_records.py
380
3.5
4
#!/usr/bin/env python3 def getRecord(S): h, l = S[0], S[0] h_cnt, l_cnt = 0, 0 for s in S: if s > h: h_cnt += 1 h = s elif s < l: l_cnt += 1 l = s return [h_cnt, l_cnt] n = int(input().strip()) s = list(map(int, input().strip().split(' ')...
a188341667a1730a337be27abb5916c98bb80810
HomingYuan/Core-python-programming
/ex1.py
2,874
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 2.1 变量 str='ABC' num=13 num str print str print num print '%s' %str print '%d'%num #2.2 运算 #(a)验证加减乘除 #(b)9 #(c)不一样,运行脚本的话,无返回值 #(d)程序返回9,运行脚本,无返回值 #(e)按下面方法改进 print 1+2*4 #2.3 自己练习即可 #2.4数值和操作符 #(a) str2=raw_input('Enter the str:') print str...
c9a4ef7c53ba615abc8c1a2a58a0c05ad14715d7
jacobfdunlop/TUDublin-Masters-Qualifier
/strings13.py
93
4.0625
4
a = "#" while len(a) < 80: if len(a) <= 80: a += '#' print(a, end='')
dd55bcb88f4081b895a77e99d450d51503592721
enrro/TC1014-Files-done-in-class
/2.-dibujos en tkinter/FuncionesProblemas0.py
448
4
4
''' Created on 03/09/2014 Resolucion de problemas introduccion a las funciones. @author: A01221672 ''' def ask_Tacos(): print("Hello wellcome to Best Tacos & Tortas NA?") print("How many tacos have you eaten?") x = input() print("How many tortas have you eaten?") y = input() print("you owe us "...
e2c1b6ac9ba26771613450fec881e94eeffad4cf
forthing/leetcode-share
/python/106 Construct Binary Tree from Inorder and Postorder Traversal.py
914
4.1875
4
''' Given inorder and postorder traversal of a tree, construct the binary tree. ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, inorder, pos...
a16d5e2134b08d00ee380b8b6ebe0db10b57db3a
marciosobral/curso-python-intermediario
/Parte 1 - Revisão/Exercicio 1.py
405
3.8125
4
# -*- coding: utf-8 -*- # EXERCÍCIO 1 from time import sleep print("\nPrograma que soletra as três palavras contidas em um vetor.\n") sleep(1) vetor = ["um", "dois", "tres"] sleep(0.5) for palavras in range(len(vetor)): print(f"{palavras+1}ª palavra: ") for letras in range(len(vetor[palavras])): ...
efbe7eb27ca550692ccb25cf04f34a1dbae8145e
NilanjanTarafder/SimplePrograms-1
/Time Addition.py
334
3.796875
4
hour = int(input("Starting time (hours): ")) mins = int(input("Starting time (minutes): ")) dura = int(input("Event duration (minutes): ")) addmins = (mins+dura)%60 addhours = (mins+dura)//60 days = (addhours+hour)//24 hours=hour + addhours if days>0: hours -= (days*24) print(hours, ":", (mins+dura)-(6...
09f9dae891f9f971387fa63a1430a149cc951d64
ComBuss/python-study
/python/jungol/55.py
55
3.546875
4
t = ['a','b','c'] n = [1,2,3] print(list(zip(t,n)))
a8e052c327cd595d220857ffdcd9975c52ef899d
notsoseamless/python_training
/principles_of_computing/1_3_TTT_MC/ttt_mc.py
7,253
3.8125
4
""" Monte Carlo Tic-Tac-Toe Player """ import random import poc_ttt_gui import poc_ttt_provided as provided #import user40_AMu2IY1JvM_45 as TestSuite #import tic_tac_toe_monty_carlo_test.py as TestSuite # Constants for Monte Carlo simulator # You may change the values of these constants as desired, but ...
e7bfb25d1c731b656366ea8b8fe27e1550eea530
risky998/fastqparser
/reverseparser.py
1,189
3.578125
4
""" This Parser Functions in a very similar way to the first one, but instead produces and prints the sorted lines by reverse complement. """ file = open("/home/local/CORNELL/public/hw1_files/Sample_Alignment.fastq", "r") lines = file.readlines() dna_lines = [] for line in lines: line=line.strip("\n") ...
e061f5d6dbdc53ee64870e0519fdcefda8a5796e
rzwc/DLFindUniqBin
/cleaning_data_functions/strip_nonalphanumeric.py
1,952
4.375
4
# program used to strip all nonalphanumeric character from text file import sys # return list of characters from a string def split(word): return [char for char in word] # return true if alphanumeric character def isalphanumeric(b): return ord(b) >= ord('0') and ord(b) <= ord('9') or ord(b) >= ord('A') a...
5265c97a97289002b0d4b1de4f892677f18cace8
CosmicWill/gears-of-geeks
/2018-May/scripts/controller.py
10,007
3.546875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # # This file presents an interface for interacting with the Playstation 4 Controller # in Python. Simply plug your PS4 controller into your computer using USB and run this # script! # # NOTE: I assume in this script that the only joystick plugged in is the PS4 controller....
b787dcfd7ea23246e8b06b96ac02e2056f1e3e92
zmaas/scratch
/numeric/binom_memo.py
1,876
4.15625
4
#/env python3 # Author: Zachary Maas import math import time # Global cache to store binomial coefficent values. cache = {} def binom(n, k): """ Calculate the binomial coefficent using a cache. The speedup that we get from using a cache grows as we increase the number of values in the cache. ""...
5d03a97fea63677af2c4c092ae2cc085fd2e096b
SmartPracticeschool/SBSPS-Challenge-3406-
/Currency_Sum_Validator.py
1,528
4.03125
4
def bill_count(amount,bills): if amount<=0: raise Exception('Amount should not be negative or zero') #raises Exception if the amount or bills less than or equal to zero temp=amount total2=0 sum=0 while(temp!=0): if(bills!=[]): max1=max(bills) r=int(te...
6804454e413015b6a5c494fa1ec0b9e4145dbb76
swipswaps/Deep-Learning-Object-Oriented-Framework-Python
/src/ActivationFunctions/ActivationFunction.py
3,768
3.9375
4
from abc import ABC, abstractmethod import numpy as np # TODO: check this: https://stackoverflow.com/questions/42594695/how-to-apply-a-function-map-values-of-each-element # -in-a-2d-numpy-array-matrix # and this https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.expit.html class ActivationFunction(...
7812888a37a6cc7e1e682369d1c8cf6586402d0a
marcelomanchester/INTRODU-O
/16exerciciowikipython.py
284
3.734375
4
area = int(input('digite o tamanho da área a ser pintada:')) Qntlitros = area/3 print(Qntlitros) Qntlatas = Qntlitros/18 print(Qntlatas) if (Qntlatas/18)%1 != 0: Qntlatas = (Qntlitros//18) + 1 print('Serão necessárias %d latas no valor de %d'%(Qntlatas,(Qntlatas*80)))
5833616e046d11517e8b1061a8aee92ab4e2ef2e
govardhananprabhu/DS-task-
/min diff of pillar.py
1,324
3.546875
4
""" Akash needs to buy a gift for his girfriend,he is given with N number of coins with the amount of gift K, the cashier has no changes to give,so help akash to pick the coins which's sum exactly equals to K,print the minimum count of coins taken out.Note a coin can taken out many times. in des First line cont...
989324bf028719ec77f83dfd460012c6ce9e4bba
pedrocr83/algoritm_design
/fibonacci_last_digit_sum_Pedro.py
295
3.9375
4
PISANO = 60 def fibonacci_last_digit_sum(n): if n < 2: return n n %= PISANO results = [1, 1] for _ in range(n): # 2 results.append((results[-1] + results[-2]) % 10) # 3 return (results[-1] - 1) % 10 n = int(input()) print(fibonacci_last_digit_sum(n))
4bad227f50e38c98012602048e1b3d206ee430cb
Bytedance-fantastic/python-learning
/lesson6/base_data.py
1,103
4.40625
4
# encoding=utf8 #lesson 1,基础类型 # 两种基础类型: # 数值:包括,整型(整数)和浮点型(小数) # 字符串 # 主函数,程序的入口 if __name__ == '__main__': # 整数 a = 1 # 小数 b = 2.1 # 字符串 c = "hello world" # 变量可以相互赋值 a = b # 打印内容 print(a) print(b) print(c) print("*********分隔符1**********") # d是个变量,我们可...
a47d242c90902ccb969ca515885dd8f229d0261f
charliecheng/LeetCodeOJ
/MedianofTwoSortedArrays.py
1,379
3.53125
4
class Solution: # @return a float ''' It is said that it is better not to use recursion in python. By default Only 1000 times recursion is allowed sys.setrecursionlimit(10000) ''' def findMedianSortedArrays(self, A, B): m=len(A) n=len(B) if (m+n)%2==1: ret...
7d6f92807429036147bfb79e2d284918e774f5ab
stjohn/stjohn.github.io
/teaching/amnh/randomTurn.py
368
4.03125
4
#Include the random and turtle libraries import random import turtle #Create a turtle teddy = turtle.Turtle() #Have a loop that repeats 25 times for i in range(25): #Inside that loop, #Move forward 10 steps teddy.forward(10) #Turn a random amount teddy.right(random.randrange(360)) #C...
8e8ade2a842fd9b49622b243778231f549721c87
xizhang77/LeetCode
/String/657-robot-return-to-origin.py
2,008
4.15625
4
# -*- coding: utf-8 -*- ''' There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (r...
14e854f9a5582b4827627d3a3b48c95f522c1a21
elliotgunn/Graphs
/projects/graph/graph.py
9,225
4.28125
4
""" Simple graph implementation """ from util import Stack, Queue # These may come in handy class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): # for example: # self.vertices = {"A": set("B"), "B": set() # "C"...
cda7cbb0b688344997be1d1d4469cc0a4b5948c1
DevMindG/PythonProgramming
/PythonProgramming/EmbeddedFunctions/MapFunctions.py
396
3.953125
4
def double(x): return x * 2 map(double,[1,2,3,4,5,6,7]) list1 = list(map(double,[1,2,3,4,5,6,7])) print(list1) list2 = list(map(lambda x : x ** 2,(1,2,3,4,5,6,7,8,9,10))) print(list2) list3 = [1,2,3,4,5] list4 = [6,7,8,9,10] list5 = [11,12,13,14,15] list6 = list(map(lambda x,y : x*y, list3,list4)) print(list6)...
c2b393123feeb75810c4755a6038b08bcb1b5fef
supercavitation/Compsci
/CompSci class stuff(ignore)/gauss.py
298
3.671875
4
#Joshua Bloch #2/12/13 #gauss total=0 number=int(raw_input('Add up all of the numbers between 1 and: ')) difference=int(raw_input('What should the difference between each number be? ')) for i in range (1,number+1): if (difference*(i-1))+1<=101: total=total+((difference*(i-1))+1) print total
7b6c29d8bbde0597bbbbdc469263e0f2e8be59f9
madanaman/leetCodeSolutions
/linked_list/classicalProblems/oddEvenLinkedList.py
1,450
3.78125
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def create_ll(self, ip_array): head = None for i in range(0, len(ip_array)): if i == 0: head = ListNode(ip_arra...
ab216495dc39a5ea5efa29d481852ba60ea85ba8
JosueReyes13/tarea_Pablo
/8.py
123
3.765625
4
i=0 while(i<1): palabra=str(input("¿Cual es el nombre de la mamá de Goku?: ")) if(palabra=="Gine"): i+=1
d56c335541ccd783bce236e0393f55a42dffa0df
SmartPracticeschool/SBSPS-Challenge-4482-Sentiment-Analysis-of-COVID-19-tweets
/plot.py
50,119
3.796875
4
import pandas as pd import numpy as np import plotly.graph_objects as go import plotly.express as px import plotly.offline as offl from plotly.subplots import make_subplots class Plot(): '''Used to plot different graphs by passing relevant arguments; requires main data points; In this particular case thes...
8df9811cd0db9e5084df7f554171d55f86ec7137
bergamojoao/URI-EXERCICIOS
/1165.py
323
3.6875
4
n = int(input()) i=0 def isPrimo(n): if(n==1): return True if(n==2): return True for i in range(2,n): if(n%i==0): return False return True while(i<n): p = int(input()) if isPrimo(p): print("%d eh primo"%p) else: print("%d nao eh primo"%p) i+=1...
515ef68c4835a1d9c86bae7b1b51e1cb5fb4be64
sasi-0453/touristbot
/touristbot.py
4,993
4.25
4
""" This is a program for a chat bot... 1.The bot will start with a greeting and self intro and ask for name of the person 2.The bot will greet and welcome the person 3.Bot will ask what a person want to do, it will offer a choice of things based upon what the bot is designed for 4.It will respond to users input a...
babc2ef35f4341cd005be038b6271a11d2ff5d40
Lubo01/Python_HardWayTutorial
/ex37.py
4,683
4.0625
4
#Exercise 37: Symbol Review - Python Basic Keywords #Keywords and #logical and assert #testing method, a variant of check e.g. assertEqual(a,b) check that a==b e.g. assertTrue (x) check that bool(x) is True break #stops the loop class #define a class, e.g. class name(object) continue #don't pr...
83f9c690d7bace68149c7098b43c70dd9d53b9cc
Zpadger/Python
/100Days/Day13/stopIter4.py
319
4.09375
4
# StopIteration本质上是一个类,所以可以通过访问它的value属性获取这个return返回的值 def g3(): yield 'a' return '这是错误说明' yield 'b' g=g3() try: print(next(g)) #a print(next(g)) #触发异常 except StopIteration as exc: result=exc.value print(result)
c6b19cfc41ac239524ca8773017660296e27d192
UmidKhodzhaev/MyFirstGame
/My game/GOLL2/Новая папка (2)/grafika lesson 3/test1.py
344
3.84375
4
class Father: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print("Hello! My name is", self.name) class Son(Father): def say_goodbye(self): print("Goodbye! My name is", self.name) father = Father("Olkan", 45) father.say_hello() son = Son("Olkan's son", 19) son.say_hel...
91fc48d70350a171828a9120d52ff2144ed8f1dd
kinselsj/python-challenge
/PyBank/main.py
1,866
3.875
4
import os import csv # Path to collect data budget_csv = os.path.join('budget_data.csv') # Read in the CSV file with open(budget_csv, 'r') as csvfile: # Split the data on commas csvreader = csv.reader(csvfile, delimiter=',') months = [] header = next(csvreader) net_pl = [] change_pl =...
1c89622980499383ec6a16181c88c086f9085382
coherentus/sprint_13
/D. Печеньки.py
485
3.640625
4
def check(zhadn, sizes): for _ in range(0, len(sizes)): cur_size = sizes.pop(0) if cur_size >= zhadn: return True return False def main(): _ = int(input()) f_zh = list(map(int, input().split())) _ = int(input()) sizes = list(map(int, input().split())) f_zh.sort...
c7d1b1f5153d9daeed4f04777e543ba0e0a40c58
jasonwhwang/cs440
/mp3/part1/perceptron.py
3,887
3.734375
4
import numpy as np class MultiClassPerceptron(object): def __init__(self, num_class, feature_dim): """Initialize a multi class perceptron model. This function will initialize a feature_dim weight vector, for each class. The LAST index of feature_dim is assumed to be the bias te...
c94335df1d32d885f1a77dcaeafe681d5f14a4b3
samuel-72/ProblemSolving
/Divide_Without_Division_Operator.py
763
4.09375
4
def get_quotient(dividend, divisor): """ Takes as input a dividend and divisor and returns the quotient """ if not dividend: print("Dividend needs to be provided.") return None if not divisor: print("Divisor needs to be provided.") return None sign = -1 if (dividend < 0) ^ (divisor < 0) else...
261d838e5b9f22fa0ce2fc2404d190dcc6cf0d70
arontommi/FindSV
/internal_scripts/frequency_filter.py
409
3.6875
4
#first argument is the input vcf, second argument is the frequency limit, prints all variants lower or equal to the limit import sys for line in open(sys.argv[1]): if "#" == line[0]: print line.strip() continue if ";FRQ=" in line: info=line.split("\t")[7] frequency=info.split("FRQ=")[-1].split(";")[0] if f...
13882b14f0e6f63fe445c66556133e200482e780
jfm44/TestsPython
/Exercices/exo12_Objet.py
1,113
3.71875
4
class Temperature: def __init__(self,value,unit='C'): self._value = float(value) self._unit = unit def __float__(self): if self._unit == 'C': return self._value if self._unit == 'K': return self._value - 273.15 if self._unit == 'F': ...
3939a8ff67023fd1230b34e4a468340f712a2be7
makarandmandolkar/Unscented-Kalman-Filter
/measure.py
1,471
3.796875
4
""" This file contains the sensor model that estimates the range and bearing of landmarks and other robots """ from params import* import numpy as np def sensor(landmark, pose, noise=False): """ computes the expected range and bearing given a landmark and the robot pose with the option to add noise Args...