blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
098d81a88ddbdb4a02f1ef16b405c847d7f3f4c9
nicolette88/python_alapok
/08_mutability.py
351
3.609375
4
a = [] b = a print(id(a)) print(id(b)) a.append(34) print(b) # ha tényleges másolat kell a listáról, akkor a .copy() metódust használd b = a.copy() print(id(a)) print(id(b)) a = 1995 b = 1995 print(id(a)) print(id(b)) b = 2342 print(id(a)) print(id(b)) # immutable: bool, int, float, tuple, string, frozenset #...
7f2ce9eedeb3c777598a272601cc5200ccff8a9f
sammienjihia/data_science
/week2_pandas.py
3,124
4.65625
5
import pandas as pd import os # creating a pandas dataframe METHOD 1 pandas_dataframe1 = pd.DataFrame( { "column1":[1,2,3,4,5], "column2":['a','b','c','d','e'] }) print(pandas_dataframe1) # creating pandas dataframe METHOD 2 # NB This method can only be followed when you are passing data to one single column ...
b0af809203dee3441e1331bd58e1a986f08ea46d
dimnikolos/algebPy
/py/tiposeMikto.py
157
3.671875
4
from fractions import Fraction def tiposeMikto(k): m = k.numerator // k. denominator if m == 0: print(k) else: print(str(m) + " " + str(k-m))
650424207ab71fe5fd9eb77d6fd5d4e2847ff1ff
ShresthaSrijana13/Homework2
/Zylab9.10frequency.py
335
3.53125
4
# Srijana Shrestha # 1918305 import csv csv_file = input() my_dict = {} with open(csv_file) as file: csv_reader = csv.reader(file) for i in csv_reader: for j in i: if j in my_dict: my_dict[j] = my_dict[j]+1 else: my_dict[j] = 1 for k, v in my_dict...
2c0559cfe8003049c161febd5ea11098f41b0429
Kant-LJF/STUDY
/canfor/AI_海龟.py
1,404
3.8125
4
#!/user/bin/env python # _*_coding=utf-8_*_ # Turtle Trading System # Initialize the short and long moving averages short_ma = 20 long_ma = 55 # Initialize the stop-loss and profit-taking levels stop_loss = 10 profit_taking = 10 # Initialize a flag to indicate when a position is open position_open = False # Initiali...
5755a5f513607cbcf02fed29f4eb3b5a4a118bc6
oarcanjomiguel/python_samples
/W7/exercicios/exercicioExtra1.py
781
3.53125
4
#Exercício 1 - Primos #Escreva a função n_primos que recebe como argumento um número inteiro maior ou #igual a 2 como parâmetro e devolve a quantidade de números primos que existem entre 2 e n (incluindo 2 e, se for o caso, n). #Exemplo: #>>>n_primos(2) #1 #>>>n_primos(4) #2 #>>>n_primos(121) #30 def ePrimo(n): fa...
722ae46a27f367356c13009f1fdca54986aeeae3
DryRun03/OOPS-in-Python
/Inheritance in Python.py
681
3.671875
4
"""Child Node/Parent Node""" class A: #Parent Class of B and a Grandparent of C def feature1(self): print("Feature 1 Working") def feature2(self): print("Feature 2 Working") class B(A): #Child Class of A and a...
e85f24b7fd808632302ed7fcf317d08584f4807f
avatargu/AID1908
/1_PYTHON/grenade_exploded.py
1,542
3.53125
4
class Grenade: def __init__(self,attack): self.attack = attack def explode(self,demage_target): if not isinstance(demage_target,Demageable): raise ValueError("如果不是子类,则报错") print("**********爆炸**********") demage_target.demage(self.attack) class Demageable: def __...
07c83d112d31e20412184c6c01e762bb876bea30
AJAortiz39/MLB-PlayerStats
/Main.py
2,508
3.6875
4
# MAIN from MLB_Player_Object import MLB_Player def main(): file_name = input(" Please enter name of the file\n ") #asking user to choose their file(player file) #print(in_player) player = MLB_Player(file_name) player.read_in_data() player.years_in_mlb() #prompts user to select 1 of th...
3ea250a43167425464687f953ea247a30a37a4ad
ranisharma20/list
/project_function.py
1,734
3.828125
4
def atm_hindi(): global pin global banking print("apka swagtat hai") print("ab apna card dale ") print("apni banking darg kare:\n1.nikalna\n2.jma kre\n3.jach kre:") banking=input("vikalp chuniy=") pin=int(input("apna pin number lickhe =")) atm=50000 if pin==9625: if banking==...
f62de2e0ac517ac0e4391632de7a5c68253e5450
CRHS-Winter-2021/first-simple-program-etma3
/main.py
336
4.09375
4
##Simple Program #Name: ____ ## Create a Simple Program that does the following. #1. Asks the user a skill question and compares their guess to the answer. Use a loop to get the user to guess until correct. #2. Write a function that takes a word and a number 'n'. Print the word out 'n' times. #ex. "Hello" 3 = "...
18dee3bed76fa3c63d00f0adfc337ae59215dc67
HarikrishnaRayam/Data-Structure-and-algorithm-python
/Binary Tree/Lectures/Node with largest data.py
1,135
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 25 21:39:08 2020 @author: cheerag.verma """ class BinaryTree: def __init__(self,data): self.data = data self.left = None self.right = None def takeInput(): root = int(input()) if root ==-1:...
eab80816080e3652e69dde0ec2ec1edecef1c6f7
nimra/module_gen
/nodes/VanderPlas17Python/C_Chapter2/A_UnderstandingData/B_APython/index.py
4,301
3.546875
4
# Lawrence McAfee # ~~~~~~~~ import ~~~~~~~~ from modules.node.HierNode import HierNode from modules.node.LeafNode import LeafNode from modules.node.Stage import Stage from modules.node.block.CodeBlock import CodeBlock as cbk from modules.node.block.HierBlock import HierBlock as hbk from modules.node.block.ImageBlock ...
396eb64f074e07b3cf6e2bc659832e4ac150a294
big-roc/Python3Projects
/leetcode/algorithms/104_max_depth.py
419
3.765625
4
# coding:utf8 class Solution: def max_depth(self, root): """ :param root: TreeNode :return: int """ if root is None: return 0 elif root.left is None and root.right is None: return 1 else: return 1 + max(self.max_depth(root...
8fcdfe46b417550c7980ff609ff9ef9babacdb1a
syeddabeer/hackerrank
/merge sort using linked list.py
2,928
4.34375
4
# merge sort using linked list # create Node using class Node. class LinkedNode: def __init__(self, value, tail=None): self.value = value self.next = tail class LinkedList: def __init__(self, *start): """define none head and then call prepend for all arguments. linked lists in Python."...
94a77faf34041208426b075f293ce886d565a226
julius01a/Python-Challenge
/PyPoll_script/main_PyPoll.py
3,623
3.609375
4
# import modules import os import csv # declare variables totalVote = 0 khanVote = 0 CorreyVote = 0 liVote = 0 oTooleyVote = 0 ratePoll = {} winnerPoll = [] csvPath = os.path.join("..", "Resources", "02-Homework_03-Python_PyPoll_Resources_election_data.csv") with open(csvPath, 'r') as csvfile: # Split the data o...
f0c56fa4f156ed858ce41ea3dd0f17a1de96012f
ksu-is/Hang-Guess
/Hang-Guess-Game.py
7,280
3.90625
4
import time import random score = 0 def difficultyEASY(): diff = input("Do you want to change the difficulty?. Or quit the game? ") if diff in ["yes", "y"]: difficulty() elif diff in ["no", "n"]: easy() else: quit() #whether they want to try a diffirent difficulty or stay o...
34ba61341f0fa1d6c4e4034f84656ee1c465c39e
PeaEnthusiastMendel/BeginnerProjects
/rearange-v0.2.py
772
4.09375
4
##imports & test import numpy as np print("Hello World!") print("This program makes an array given two numbers.") print("First, input the number of columns you want.") print("Then, input the number of elements you need") print("Restart the array by typing 'y'. Anything else will end the program.") ##variables restart ...
6b6f91c90dfcf08ade64ac59bd1cfabb55183b18
ChangxingJiang/Python-DM-Homework-W1-W3
/Day-07/Test-01-郭正一/登陆问题.py
298
3.734375
4
n = 0 while n<3: a = int(input('请输入密码')) correct = 865 if a == correct: print('登陆成功') else: print('用户名或密码错误,若连续3次错误则自动锁死账号') n+=1 print('因连续3次输入用户名或密码错误,账号已锁死')
882d2a45d215a68067efbfbe3aa296bcfb2625e0
gt6989b/Test
/CheckIO/Home.04.MostWantedLetter.py
1,050
3.875
4
from collections import defaultdict def checkio(text): letterCount = defaultdict(lambda : 0) for letter in text.lower(): if letter.islower(): letterCount[letter] += 1 maxCount = 0 for letter, freq in letterCount.iteritems(): if freq > maxCount: maxCount = freq ...
a9a3d089611d4ccbf5ed53a5583f65b61c9394f3
Meetali002/python
/unique_numbers.py
561
4.34375
4
#Write a program to input 8 numbers from the user and display all the unique numbers (once). # By - Meetali Jain # Date of Creation - 28-09-2021 # Last Modified - 28-09-2021 numbers = [] while(len(numbers)<8): numbers.append(input("Enter Number : ")) print(set(numbers)) # OUTPUT:-Enter Number ...
e341faea8356148dc302eff37aade5ab6412b6d7
akiraboy/python_20191010
/collections_pgg/zad_5.py
333
4.125
4
""" Napisz program wypisujący na konsolę tabliczkę mnożenia dla liczb od 0 do 9 w postaci tabelki. """ print(" "*3, end="") for i in range(10): print(f"{i:2}", end=" ") print() print() for i in range(10): print(f"{i:<3}", end="") for j in range(10): print(f"{i*j:2}", end=" ") # format specifier ...
2420fd6ac69239a72ac23c728efafde4917f0fe1
twozero88/SunteHo
/vol.py
579
3.53125
4
from pynput.keyboard import Key,Controller import time keyboard = Controller() def soundChange(percentChange): if abs(percentChange)>0.2: print(abs(int(percentChange*10))) for i in range(abs(int(percentChange*5))): if percentChange > 0 : print("Increasing vol.........") keyboard.press(Key.med...
29283a3f1419c3c060e7e7848691e9f905c31238
vadimsh73/algorithms
/cyclic shift.py
631
3.953125
4
# -*-coding:UTF-8-*- def cyclic_shift_left(a): # Циклический сдвиг влево """ Циклический сдвиг :param a: Массив :return: Массив со сдвинутыми значениями """ tmp = a[0] for i in range(len(a)-1): a[i] = a[i+1] a[len(a) - 1] = tmp return a def cyclic_shift_right(a): # Цикл...
8e162399a64a560dd5b90cb9a3c9ae29b8f2f445
lawlessaidan/codewars
/boiledeggs.py
650
4.09375
4
#Implement a function, which takes a non-negative integer, representing the number of eggs to boil. #It must return the time in minutes (integer), which it takes to have all the eggs boiled. #Rules #you can put at most 8 eggs into the pot at once #it takes 5 minutes to boil an egg #we assume, that the water is boilin...
5c9ed699d7f8bb55126e2fcf473c9daefe40540c
0305Chao/Py3_note
/w4.交换变量.py
453
4.09375
4
#_*_ coding: UTF-8 _*_ x = input('请输入 x 值:') y = input('请输入 y 值:') #创建临时变量并交换 temp = x x = y y = temp print ('交换后的x的值为:{}'.format(x)) print ('交换后的y的值为: {}'.format(y)) #创建固定变量 x = input('请输入 x 值: ') y = input('请输入 y 值:') #不适用临时变量 x,y = y,x print ('交换后的x的值为: {}'.format(x)) print ('交换后的y的值为:{}'.format(y))
f483afff8be684f7075e759ce0224a6a414ac21b
nclairesays/intro-python-hackforla
/class_two/03_functions.py
1,657
4.5625
5
# FUNCTIONS # how to you know the block is associated with the function with throu # indentation -- use 4 spaces NOT tab # A function is like a mini-program within a program. def hello(): print('Howdy!') print('Howdy!!!') print('Hello there.') # Can you run the function hello()? hello() # FUNCTION PA...
0df618faa5b1eafa49b4452121486daf622ced90
EkanshBhatnagar/judgement-python
/classes.py
1,235
3.5625
4
from enum import Enum from itertools import product from random import shuffle class ranks(Enum): TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE = range(2, 15) class suits(Enum): CLUBS,DIAMONDS,HEARTS,SPADES = range(1,5) class Card(object): def __init__(self,suit,rank,in_dec...
a663b84160d5d980c594287ac57f980577f77788
gupta-shantanu/dumpcode
/Spoj_Solutions/guesthe.py
559
3.734375
4
def gcd(a,b): if b==0: return a return gcd(b,a%b) while(True): a=input() if a=='*': break num=1 right=True for i,j in enumerate(a): if i==0: if j=='N': print(0) right=False continue if num%(i+1): if j=='...
b667f533ec59e640442118542bc01bd98401a542
kingds/project-euler
/python/in_progress/Problem_191.py
168
3.625
4
import itertools base_string = "" base_string += "L" * 30 base_string += "O" * 30 base_string += "A" * 30 for p in itertools.permutations(base_string, 30): print p
efc8744d093863dda7eedac096464bc18a217751
xiaodongzi/pytohon_teach_material
/03/exec03-fromkeys.py
337
3.71875
4
# coding:utf-8 # function dict.fromkeys ''' fromkeys(...) dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. ''' keys_list = ['name', 'age'] value = '' value = None # value = ['aa', 'bb'] # '' or None 是不同的 dict1 = {} for k in keys_list: dict1[k] = value pr...
ed38f9d2db623e0f32870fa884fda1975acafea9
Geo-Python-2020/exercise-1-StellaWava
/exer1.py
880
4.21875
4
#!/usr/bin/env python # coding: utf-8 # ice_cream = 4 # sleeping_rating = 9 # first_name = input('First Name') # print (first_name, 'it is.') # last_name = input('Last Name') # print (last_name, 'it is.') # my_name = first_name + last_name ##not certain of how to embed the spacing. # print(my_name, 'is my name') ...
04f9a25634cd17be4f36badb800ca63e18d38080
Insper/design-de-software-exercicios
/pages/input/raw/input/soma2.py
147
3.5
4
# Função que soma dois números. def soma(x, y): z = x + y return z # Testando nossa função resultado = soma(14, 28) print(resultado)
47e38389933877c2be35aaa6d948ab8db568ef90
prativadas/python-basics
/7. Chapter 7/04_print_list_for.py
186
4.15625
4
fruits = ['Banana', 'Watermelon', 'Grapes', 'Mangoes'] for item in fruits: # print elements using loop print(item) print(fruits[0:]) # print the elements in list
77395578ee8c4ff12fbebe36c4baee9e5b5ca853
Thirupathi1036/ScalaSparkDemo2
/src/main/scala/python/basic/Str.py
567
4
4
s = " ABcB WelCome to " print s print "Lower: ", s.lower() print "Upper: ", s.upper() print "Len: ", len(s) print "Add: ", s + " Hello " print "Count of key: b ", s.count("b") print "count of Key: B ", s.count("B") print s.center(20) print "Len: ",len(" ABcB ") print s.capitalize() print s...
2ea0eaa6a02a1f79624a60572c830a921614cab6
huningfei/python
/复习/内置函数和匿名函数.py
2,056
3.78125
4
# 一 内置函数 # # 1 输出 print # print(1,2,3,4,5,sep=';',end='| ') ##sep是以;分开每个数字,end是以|结尾的 #绝对值 # print(abs(-9)) #divmod返回商和余数 # print(divmod(9,4)) # print(pow(2,3,5)) #(2**3) 就是2的三次方,对5取余 8%5 #min最小值 # print(min(-1,0,3,4)) # # print(min(-1,0,3,4,key=abs)) ##算完绝对值之后,在返回最小值 #eval和exec # eval('print(123)') # exec('print(1...
ee0fcb9e25636a9deb19d12ba576da909e331e83
wangcaicai-666/PythonDemo
/selenium_20190727/test_day_01/mewDay_01/day_01_if_for.py
521
3.765625
4
#__author: yaomingxi #__date: 2019-08-02 #判断 if ''' a = input(str("请输入一个数字 :")) b = input(str("请输入一个数字 :")) if a<b: print(a,"小于",b) elif a>b: print(a,"大于",b) else: print(a,"等于",b) ''' for i in 'hello': print(i) hello = ['danan','laomao',123456] for j in hello: print(j) t = 10 for k ...
21254ae45a8f6c0d01948db58a91a4f54631c8ee
ARWA-ALraddadi/python-tutorial-for-beginners
/06-How to Create User Interfaces Demos/03-simple_button.py
826
4.53125
5
#--------------------------------------------------------------------# # # Simple Button # # As an example of a button which does something (but not very much!), # this program creates a GUI which writes to the shell window each # time a button is pressed. # # Import the Tkinter API from tkinter import * # Create a w...
77adafb7d50c5afde60ce3d07440d2578364bb0d
lohitbadiger/basics-python-code
/yuri/42.py
498
4.28125
4
# #the argument name is the required argument to the function func # def func(name): # message = "Hi "+name; # return message # name = input("Enter the name?") # print(func(name)) # scope variable def print_message(): message = "hello !! I am going to print a message." # the variable mes...
2c97d57d09727b7d991f6c952a39ae124e9bbbad
windhaunting/Coding_practices
/LeetCodeSummary/BFSTree.py
2,148
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 24 08:39:46 2018 @author: fubao """ # tree BFS or DFS traversal; # level traversal ''' e.g. Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 3 Output: 1 Example 2: Input: ...
0cef7f5bd8a9c66a879dbae1a96285ede3e278e6
AlterFritz88/pybits
/bite123.py
1,009
3.703125
4
names = 'bob julian tim martin rod sara joyce nick beverly kevin'.split() ids = range(len(names)) users = dict(zip(ids, names)) # 0: bob, 1: julian, etc friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5, 6), (5, 7), (5, 9), (6, 8), (7, 8), (8, 9)] def get_friend...
bbd224d5765888664fedc255124f8429e3bc0d5f
IanBuceta/Programacion2
/unidad_4/ejercicio_3b.py
254
3.6875
4
with open("holamundo_binario.txt", "ab+") as file: file.write((input("Ingrese algo para anotar: ") + "\n").encode()) print("Cosas escritas en {}:".format(file.name)) file.seek(0) for line in file.readlines(): print(line.decode())
fee914752faf214ab5e43d9e53cd579ab2cbce7b
xyzhangaa/ltsolution
/BTLevelOrder.py
388
3.796875
4
###Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). #O(n), O(n) def preorder(root,level,res): if root: if len(res) < level +1: res.append([]) res[level].append(root.val) preorder(root.left,level+1,res) preorder(root.right,level+1,res) ...
176d178be4c398313ade3a9af3c1452723e2e8e3
Jacob-Roessler/tech-ready-python
/Full Snake Game.py
6,927
3.796875
4
import pygame import time import random pygame.init() #Color definition RGB white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) #Screen, Clock, and Caption Definition screen_width = 800 screen_height = 600 gameDisplay = pygame.display.set_mode((screen_widt...
efdea8e735c06a4fcf88078eb948f9457a4b6b75
maq-622674/python
/廖Py教程/py/3.python基础/使用list和tuple.py
4,869
4.5
4
''' list Python内置的一种数据类型是列表:list。 list是一种有序的集合,可以随时添加和删除其中的元素。 比如,列出班里所有同学的名字,就可以用一个list表示: ''' classmates = ['Michael', 'Bob', 'Tracy'] print(classmates) #变量classmates就是一个list。用len()函数可以获得list元素的个数: print(len(classmates)) #用索引来访问list中每一个位置的元素,记得索引是从0开始的: print(classmates[0]) print(classmates[1]) print(classmates[2])...
067c117c02ab21c8c56217308226b3caf2003d7c
ignaciocassi/ComplejTempProgIII
/AlgoritmoOrdenadosDyC.py
756
3.765625
4
def Ordenado(S): L=len(S) if L==0: #Caso Base 2: S está ordenado porque tiene 1 elem. return True if L==1: #Caso Base 2: S está ordenado porque tiene 1 elem. return True if L==2: #Caso Base 3: S está ordenado porque S[0] < ...
232743c3164f85cb821f04fc4781a1b6dbb1cb4a
bharat-kadchha/tutorials
/core-python/Core_Python/extraknowledge/Conditions.py
373
4.15625
4
a, b, c = 2, 3, 4 print("a<b is t but b == c false so whole false : ", a < b == c) a, b, c = 2, 3, 3 print("a<b is t but b == c true so whole true : ", a < b == c) a, b, c = 4, 3, 3 print("a<b is false but b == c true so whole false : ", a < b == c) a, b, c, d = 3, True, 5, 5 print("a<b is t but b == c false so whol...
da1c0999d53ac3ef5921f9b3560107d3d80a7044
loggar/py
/py-core/class-object/class.7.public_var.py
147
3.609375
4
class Person: first_name = 'TK' tk = Person() print(tk.first_name) # => TK tk.first_name = 'Kaio' print(tk.first_name) # => Kaio
03e55c4102430f2643d5e0d9bcbd9b105f63270f
fisherra/python_book_exercises
/lpthw/ex_39.py
1,623
4.5625
5
# dictionaries # basically a look-up table in R # here's how a list works a_list = ['this', 'is', 1, 'list', True, False, None, 123.2] print(a_list[0]) print(a_list[1]) print(a_list[-1]) # here's how a dictionary works a_dictionary = {'first entry': 123.321, 'x': 'Walmart', 'name of entry 3': 'entry 3 content'}...
cc1aa0b829a83a0e180791634991d26c70a183d8
kyo2bay/my-python-codes
/arg.py
414
3.6875
4
import sys def are_valid_args(args): if len(args) != 3: return False for i in range(1, 3): if not args[i].isdigit(): return False return True def main(args): if not are_valid_args(args): print("invalid args") sys.exit(1) a, b = args[1], args[2] ...
a4aaa768e4aba6b20e818552075aa5c110c2d500
albertogcatalan/daw1
/python/Busquedas/tests/test_alumnos.py
390
3.5625
4
# -*- coding: utf-8 -*- ''' Created on 15/02/2012 @author: Alberto ''' from EjerciciosAlumnos import * lista = [] lista.append(Alumno('Luis')) lista.append(Alumno('Pepe')) lista.append(Alumno('Ana')) lista.append(Alumno('Eva')) def test_encuentra(): assert buscar('Luis', lista) == 0 ass...
6cb69fdb96f2c8ce4ebb93e6304cbb329be2267c
lucasarieiv/Projetos
/Exercicios de guarana/Exercicio34().py
215
3.609375
4
sal = float(input('Qual o salario do fucionario? ')) if sal <= 1200: novo = sal + (sal * 15 / 100) else: novo = sal + (sal * 10 / 100) print('Quem ganhava R${} passa a ganhar R${} agora.'.format(sal, novo))
5fb144d4b276e9e1c6319937547ee26c7214ad8d
GZHOUW/Algorithm
/LeetCode Problems/Linked List/Reverse Linked List.py
879
4.03125
4
''' Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head): # recursion if not head or not ...
f1b19112048d99ee153e93028d7799e92b154a20
a0id/encoding
/app/encoder.py
567
3.546875
4
import binascii class Encoder: def __init__(self, zero, one): self.zero = zero self.one = one def encode(self, text): binary = bin(int(binascii.hexlify(bytes(text, 'utf8')), 16)) encoded_array = [ ] for i in range(len(binary)): if binary[i] == '...
e9871b8eaec26d84afbed4012831cf8c4e52856e
VladyslavHnatchenko/async-p
/worker.py
1,115
3.640625
4
# ThreadPoolExecutor VERSION from concurrent.futures import ThreadPoolExecutor from time import sleep def return_after_5_secs(message): sleep(5) return message pool = ThreadPoolExecutor(3) future = pool.submit(return_after_5_secs, "hello") print(future.done()) sleep(5) print(future.done()) print(future.res...
f0335e05cd79814c757823630c22217bec205fc7
reb33/pythonLeaning
/project 1/shad/iterators/generator2.py
239
3.734375
4
def my_range_gen(begin, end, step): current = begin while current<end: yield current current += step def main(): for x in my_range_gen(0, 5, 1): print(x,end=" ") if __name__ == "__main__": main()
5b74b31fb55612e95e885d6f60084d4f9b217342
geekhub-python/cycles-vborshchov
/task5.py
152
3.9375
4
#!/usr/bin/env python3 print('ABC\n') for i in range(ord('a'), ord('z')+1): if (i-2) % 5 == 0: print('\n') print(chr(i), end="") print('\n')
672f1abc92d276266e45173d5035ffb1e9b6a167
Shubhamshandily/Python
/6.2for_in_while.py
382
4.15625
4
#Nested For loop in while loop travelling=input('yes or no:') while travelling=='yes': num=int(input("Number of people Travelling:")) for num in range(1, num+1): name=input("Name:") age=int(input("Age:")) sex=input("M/F:") print(name) print(age) ...
f52e652250af277b8dfbc39d07240c2da69c768b
ljnoyola/curso
/eje2.py
361
3.953125
4
variable=0 while True: entrada=raw_input('que deseas hacer ') if entrada =='salir': break valor=raw_input('que valor ') if entrada=='*': variable=variable * int(valor) elif entrada=='/': variable=variable / int(valor) elif entrada=='+': variable=variable + int(valor) elif entrada=='-': variab...
9de2dc0fd397c5d118d01067182934e535aa4570
dm36/interview-practice
/daily_practice/july_5th_2019/reverse_words.py
3,321
3.609375
4
# [ 'c', 'a', 'k', 'e', ' ', # 'p', 'o', 'u', 'n', 'd', ' ', # 's', 't', 'e', 'a', 'l' ] -> # [ 's', 't', 'e', 'a', 'l ', # 'p', 'o', 'u', 'n', 'd', ' ', # 'c', 'a', 'k', 'e'] # import unittest # first reverse the input # then go through it- identifying individual wor...
5574f1652f384cb9fda356bf535e8835c6535a6e
samedhaa/Problem-Solving
/Random Questions from books/LinkedLists & Arrays/(1.1).py
986
3.953125
4
''' 1.1 : Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? ''' # this function uses N^2 solution with no data structure # O(1) Space complexity def isUnique(array): for i in range(len(array)): for j in range(i+1,len(array)): if arra...
4d7fb9ab74da8caa972ddd934f9c1772821bf2f6
AdamMartinCote/AlgorithmDesign
/tp1/algorithms/bruteforce.py
807
3.640625
4
import time from typing import List from .common import MAX_DIST, distance def brute_force(points: List[List[int]]) -> float: """ Si le nombre de points est suffisamment petit, on préfère utiliser cet algorithme. """ dist_min = MAX_DIST for pos, pt1 in enumerate(points): for pt2 in points[(po...
fdc636aeaf06edc6b3fe4d92d105ba7616fb9e61
jrobertorma/python-playground
/basics/basic-strings.py
2,110
4.40625
4
# A string is a sequence of characters, we use "" to define them # Strings have indexes starting at 0, we can't access unexistent indexes # the len() function returns the lenght of a string fruit = '¡Plátanooooo!' index = 0 while index < len(fruit) : letter = fruit[index] print("Index:",index,"Letter:",letter...
baaf9c7333d07552ce1ecd65a550bbcc56d9d2a1
Qinpeng96/FindJob
/编程/leetcode_Q/28.实现 strStr().py
3,046
3.953125
4
# -*- coding: utf-8 -*- """ 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。 示例 1: 输入: haystack = "hello", needle = "ll" 输出: 2 示例 2: 输入: haystack = "aaaaa", needle = "bba" 输出: -1 说明: 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 对于本题而言,当 need...
662a8901aa380a16fccbc5c926999f8d4217a9ac
txkxyx/PythonLearning
/読書会/ch03/nyuralunetwork.py
596
3.5
4
import numpy as np import matplotlib.pylab as plt def step_function(x): return np.array(x > 0, dtype = np.int) # x = np.arange(-5.0,5.0,0.1) # y = step_function(x) # plt.plot(x,y) # plt.ylim(-0.1,1.1) # plt.show() def sigmoid(x): return 1 / (1 + np.exp(-x)) # x = np.arange(-5.0,5.0,0.1) # y = sigmoid(x) # ...
a0a4b7c7c13af5570b2eb49d5a744780ee8c4630
phuycke/Project-Euler
/Code/problem_14.py
1,559
4.28125
4
#!/usr/bin/env python3 # Problem setting """ The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequ...
6a3d260d3936c18a97b364ced2289521035f8c10
Ruban-chris/Interview-Prep-in-Python
/cracking_the_coding_interview/10/10-2.py
1,570
3.984375
4
# Write a method to sort an array of strings so that all the anagrams # are next to each other. mystrings = ['iceman', 'what', 'rat', 'cares', 'acres', 'tar', 'races', 'scare', 'cinema', 'thaw'] def groupAnagramsTogether(strings): # guard case if len(strings) is 0: return strings result = [] whil...
4ff70f561d8a7b82030b4c440a6345274cf0a009
prabodhprakash/problemsolving
/spoj/samer08f.py
182
3.671875
4
while True: n = int(raw_input()) if n != 0: count = 0 for i in range(1, n +1): count += pow(i, 2) print (count) else: break;
ae99927c7ed2f606f2ee90857beab8205f547784
en9apr/sphinx
/_hpsc/homework3/newton.py
2,043
4.625
5
""" Module to compute the square root of a number using Newton's method: f(x) = x**2 - n = 0 Parameters: max_iter :- maximum number of iterations for iterative method tol :- relative residual tolerance for iterative method """ import numpy as np max_iter = 20 tol = 1.0e-14 def solve(x0, debug=False): """ Compute ...
1acf2ca509c3dc747e70786db49464152facab96
malaggang2/project_euler
/problem_01~40/problem_03.py
824
3.671875
4
# Problem_03 # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? n = 600851475143 i = 2 ans = 2 while n != 1: if n % i == 0: n = n // i if i > ans: ans = i else: i += 1 print(ans) # def get_max_prime_number(n): ...
1ee0af8ddf1b952824f681e9ff191e764c192df5
Karthikeyan-Ravi/python_code
/sample_questions.py
210
3.5
4
string = "orange is my favourite color " a = string[-7:-1] print a b = string[12:22] print b c = string[9:12] print c d = string[6:9] print d e = string[0:7] print e result =" ".join([a,b,c,d,e]) print result
13cba4094af880ab36164ae99597dca296f5aedb
thrama/coding-test
/python/compressString.py
638
4.34375
4
from itertools import groupby """ In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools. To read more about this function, check this out: https://docs.python.org/2/library/itertools.html#itertools.groupby You are given a string S. Suppose a character 'c' occurs co...
05a1026089d81226ea502bcd9bc12d7844adc36b
sachinyadav31/intro-to-programming
/week-4/examples/disappearanceAtTheRedWizard.py
4,128
3.859375
4
import sys # Please tag us if used! # We'd love to see what you make: # @ScienceOxford def start(): print(name + " wakes up in a strange place.") print("On their left is a desk with a note on it, ahead they can see a door.") print("To read the note, type READ. To exit through the door, type LEAVE") w...
f53ea30013e5ed67e9edd50b0a67e9ee0cfae478
vladimir-pakhomov20/Phyton-AI-
/3.2.py
405
3.875
4
name = input('enter name: ') surname = input('enter surname: ') year = int(input('enter year: ')) city = input('enter city: ') email = input('enter email: ') telephone = int(input('input telephone: ')) def my_func (name, surname, year, city, email, telephone): return ' '.join(str(x) for x in [name, surname, year, ...
4dbc1fd2755fc80a0a43b33c7468528cb2eb1443
x4nth055/pythoncode-tutorials
/ethical-hacking/steganography/steganography_advanced.py
6,586
3.65625
4
import cv2 import numpy as np import os def to_bin(data): """Convert `data` to binary format as string""" if isinstance(data, str): return ''.join([ format(ord(i), "08b") for i in data ]) elif isinstance(data, bytes): return ''.join([ format(i, "08b") for i in data ]) elif isinstance(da...
5bbdeaf5b6264b59b279a10bfc90bb64e7618625
Githubshambhavi/Python-Applied-Data-Mining
/Perceptron.py
11,759
4
4
# coding: utf-8 # # In[1]: # author : shambhavi srivastava import pandas as pd import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import random, itertools # # Vanilla Perceptron Implementation # In[1057]: class Perceptron: 'A simpl...
c6f979b976ebd18476c651b5ab0b31b08b1b8b89
atharvajhawar/ds
/task 1 spark foundation.py
3,688
4
4
#!/usr/bin/env python # coding: utf-8 # # Data Science and Business Analytic # # Name : ATHARVA JHAWAR # # Task 1 : Prediction using Supervised ML # # Objective :- # ### Predict the percentage of an student based on the no. of study hours.</b> # ### Importing all libraries required in this notebook # # In[1]: ...
6913eab4638014588bce42ef0033b42eddd79180
yiweiyihang/Coding-Interviews
/16_ReverseList.py
1,794
3.765625
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 2 09:22:40 2018 @author: FT """ """ 题目描述 输入一个链表,反转链表后,输出新链表的表头。 """ class ListNode: def __init__(self,x): self.val = x self.next = None class Solution: # 返回 ListNode def ReverseList(self,pHead): """ 利用堆栈后进先出的特性进行反转 ...
8960e0ddd7e6acb2ea57c73aac59b1402f081ac4
lhalstro/camping_scraper
/scrapers.py
3,035
3.59375
4
"""CAMPING SCRAPER OBJECTS """ class CampReservation """ Class definition for a specific desired camping reservation """ def __init__(self, name=None, date_start=None, length_stay=1, website=None, campground=None, ...
cc97ff109c3a381e8ac911f9550456daa63bc6d2
Nadiaghobadi/Machine-Learning-Projects
/Regression/assignment1.py
4,529
3.71875
4
"""Basic code for assignment 1.""" import numpy as np import pandas as pd import scipy.stats as stats import math def load_unicef_data(): """Loads Unicef data from CSV file. Retrieves a matrix of all rows and columns from Unicef child mortality dataset. Args: none Returns: Country nam...
e06c0b3e06a3d48b13612b6a28902f7dccabdb2f
samdarshihawk/python_code
/compressstring.py
725
4.25
4
''' In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this function, Check this out . You are given a string Suppose a character '' occurs consecutively times in the string. Replace these consecutive occurrences of the character in the string. ...
faf2cfd9f3347af3d8afbd6cec0aaa49698643cc
matthew-maya-17/CSCI-1100-Computer-Science-1
/RPI-CS1100-HW/hw05_files/hw5_part1.py
1,731
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 31 17:31:08 2019 @author: matth """ """The objective of this program is to set up the functions move_trainer() and throw_pokeball(num_false, num_true) for part 2 and 3. In this program you will use randomness to pick a direction, a value, and a boolean statement"""...
5d9a62b02ceab1d13d71e4d2ff3924c6f9d4e03e
leahogorman/pythonClass
/Class3/Class3.py
1,074
4.15625
4
# a = input("what is your name?") # if len(a) > 6: # if len(a) < 10: # print("Your name is greater than 6 characters, but less than than 10 characters. Your name is {} characters".format(len(a))) # else: # print("Your name is greater than than 10 characters. Your name is {} characters".format(le...
7dca17a106cb05f663ca7c40debb6fc81fb6d698
chrishaining/python_natural_language_processing
/word_cloud.py
1,034
3.53125
4
import matplotlib.pyplot as pPlot from wordcloud import WordCloud, STOPWORDS import numpy as np from PIL import Image text1 = open("iliad.txt", "r").read().lower() title1 = "The Iliad" text2 = open("odyssey.txt", "r").read().lower() title2 = "The Odyssey" text3 = "ten, ten, ten, ten, ten, ten, ten, ten, ten, ten, ...
67a9fd07293d90ea98d196a3f97173595ba7b94d
offbynull/offbynull.github.io
/docs/data/learn/Bioinformatics/output/ch7_code/src/Stepik.7.3.ExerciseBreak.DeviseLinearAlgorithm.py
4,930
4.09375
4
# EXERCISE BREAK # # The algorithm proposed on the previous step computes LimbLength(j) in O(n^2) time (for an n x n distance matrix). # Design an algorithm that computes LimbLength(j) in O(n) time. # UPDATE: I figured this out, but it required a couple of days of futzing around and understanding the limb length # al...
6bcda527394c7ba59e6cacc55f9a3aeb1feada8e
TuringMachinegun/Turing_Neural_Networks
/tnnpy/symdyn.py
31,467
4
4
__author__ = "Giovanni Sirio Carmantini" __version__ = 0.1 """ """ import itertools as itt from collections import Counter from copy import copy from typing import List, Union, Tuple import numpy as np def as_list(arg): """Convenience function used to make sure that a sequence is always represented by a l...
4bf9dfccde5cda9a0223bdeb96ff8b2dad1f6e67
Dcooper15/python_algorithms1
/problem_2.py
747
3.5625
4
a = [1,2,3,4] b = [1,4,9,16] c = [1,4,5,6] d = [1,4,4,2] e = [1,16,9,4] f = [1,2,3,4,5] def some_function(a, b): dict_a = {} dict_b = {} boolean_stop = False if len(a) == len(b): for i in a: dict_a[i] = i for k in b: dict_b[k] = k for x in dict_a: ...
71c5f851c207922db76cc57fbcd955e5ef6422b1
delaMorena/4ga-deberes-python
/run.py
575
3.59375
4
class Student: def __init__(self, name, previous_studies, tech_skills = None, age=0, gender = None): self.name = name self.previous_studies = previous_studies self.tech_skills = tech_skills self.age = age self.gender = gender student1 = Student('Marta', 'Biology', 'HTML, CS...
3acd6e77d85ae940a814b630ac7e2da127e0e64a
AndrewVorotyntsev/tik-tak-toe
/algorithm(2 players).py
1,982
3.6875
4
# Создаем двумерный массив matrix = [["*", "*", "*"], ["*", "*", "*"], ["*", "*", "*"]] global flag_win flag_win = 0 # Функция, отображающая поле def show_field(m): for i in [0, 1, 2]: print(m[i][0], m[i][1], m[i][2]) # Функция , позволяющая сделать ход def make_move(x, y, m, team): if te...
f876c55acff8aa569d756c4b405ba0442f6ec7fb
Alvin2580du/alvin_py
/business/stepTwo/lights 2.py
2,306
3.921875
4
"""Question 2 Part e List is collection of numbers while String is sets of characters. List is able to be motified after we created it. String is only able to change by operators. If we want to put a String to a List, we need to conver this String to a number by using the split() method. """ import random def genBoa...
f9681827561e4716809d8699e0749bac190d4871
pascalweiss/codequiz
/quiz_20_06_21.py
1,188
4.0625
4
""" Given a non-empty array where each element represents a digit of a non-negative integer, add one to the integer. The most significant digit is at the front of the array and each element in the array contains only one digit. Furthermore, the integer does not have leading zeros, except in the case of the number '0'. ...
c51fe448bea86f607ba2c4de2d3b7870957c366f
TusharDimri/Python
/COROUTINES in Python.py
661
3.5
4
def searcher(): import time time.sleep(4) #Assume this to be any time consuming task fil = "This is where you will search. Assume this to be a file" while True: #line 6-7 make this function a coroutine word = (yield) if word in fil: print("Found") else: p...
33469cee24107f63f392e8ffba64e5c35cb9ebd1
vsdrun/lc_public
/depth-first-search/39_Combination_Sum.py
1,506
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode.com/problems/combination-sum/ Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be cho...
44899b4bcdff4675d842a6a82d06f3d4347389b9
kenzzuli/hm_15
/05_python高级/13_python提高-2/07_传统的私有属性的setter和getter方法.py
416
3.796875
4
class Money(object): def __init__(self): self.__money = 0 def get_money(self): return self.__money def set_money(self, value): if isinstance(value, int): self.__money = value else: print("money必须是int类型,设置失败") m = Money() print(m.get_money()) m.set_...
58d58555668d568d3cf3529162cd01e94680b78c
sujith1919/TCS-Python
/2.py
3,188
4.25
4
#let's play with numbers >>> 2+2 4 >>> # This is a comment ... 2+2 4 >>> 2+2 # and a comment on the same line as code 4 >>> (50-5*6)/4 5 >>> # Integer division returns the floor: ... 7/3 2 >>> 7/-3 -3 #The equal sign ('=') is used to assign a value to a variable. #Afterwards, no result is displayed...
c51b68d77d7659a8935151ae6ba0ae8da8cdee62
alandao/acmpractice
/tree_sum.py
3,136
3.546875
4
import itertools class Tree(object): def __init__(self, data, left, right): self.left = left self.right = right self.data = data # String -> (Int, String) def splitSumTree(xs): head, *tail = xs if head.isdigit(): return head + splitSumTree(tail) else: retur...
274d090fe6e7b7ca39b64163dae2e58f20f055f8
jfriend08/LeetCode
/BinaryTreeZigzagLevelOrderTraversal.py
1,567
4
4
''' Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], ...
76c66efc4f265f8d8cfb55f3d33e4e0b640e926c
Raj-Bisen/python
/ReverseNumber.py
571
4.03125
4
# Accept number from user and return its Reverse number . # input : 1425 # output : 5241 def ReverseNumber(no): iDigit = 0 iRev = 0 while (no > 0): iDigit = int(no % 10) iRev = (iRev * 10)+iDigit no = int(no / 10) return iRev def main(): print("En...
0052022182f0dd811fe30b61f944d32ac38f2e8d
dragoonbeaga/tlg_learning_first
/Nerdom_Quiz.py
6,786
4.21875
4
#!/usr/bin/env python """Author: James Peterson || This program to run a quiz""" class Question: #this is a Class. allows me to point to questions inside of list def __init__(self, prompt, answer): #this initiates the class. (sets what the Class can be called, self.prompt = prompt ...
8e46cddebe5aff082f41b8d275ed942de282129d
thatmattbone/lab
/stats_fun/mean_median_mode.py
1,075
3.5625
4
from __future__ import print_function import numpy #import pandas as pd #import pprint # map from values to frequency data1 = {1: 4, 2: 6, 3: 4, 4: 4, 5: 3, 6: 2, 7: 1, 8: 1} data2 = {1: 1, 4: 1, 6: 2, 8: 3, 9: 4, ...