blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b5596321ff90bda5b5e4907e2ac31c09d0ea84df
eth-sri/DeepT
/Robustness-Verification-for-Transformers/generate_random_indices.py
217
3.640625
4
import random lengths = [18, 22, 6, 14, 9, 13, 8, 13, 9, 13] # We don't want 0 #CLS and length -1 #SEP # print([random.randint(1, length - 2) for length in lengths]) # Result was: [10, 13, 4, 12, 7, 11, 3, 5, 1, 2]
9cbae6a36f0c43610a086ac74cd50b089ccadf90
dmsenter89/learningProgramming
/Python/lang/seconds2years.py
327
3.71875
4
#! /usr/bin/python3 v = (10**9) min = v*(1/60) hrs = min*(1/60) d = hrs*(1/60) yrs = d*(1/365) test= (yrs>= 81.30) print('''Can a Norwegian baby expect to live for {v:G} seconds? That's about {t:.2f} years. In Norway, the average life expectancy is 81.30 years. Hence, the answer is {test}.'''.format(v=v,t=yrs,test=...
e72f747812c68b4712a66fd64af055207b92151f
stephaniakyh/kyhrepository1
/20180730ex1.py
709
3.984375
4
# print("hello!") # print("내이름은 김연향") # print(10+100) # print("10+100") # name="김연향" # print (name) # print ('학생이름은' + name) # print ("학생이름은 김연향") # print ('학생이름은 김연향') # # # a="seoul" # b="seoul is big and beautiful city in KOREA" # print (a) # print (b) # a=12 # b=20 # print(a+b) # print(float(a+b)) # print(int(f...
a77e88524d571ad22b845ea8ed632eb2f87428ee
Silverdragon7/learnPythonHardWay
/test.py
2,663
3.765625
4
# # informacje o zmiennych dla kodu # counter = 1 # plik = "1.txt" # escape = 0 # # #skrypt czytający # def czyt(czytany): # return print(open(czytany).read()) # # # skrypt pytający o odpowiedź i czytający odpowiedni plik # def wybor(ans): # if ans == "Yes": # czyt(aktualnyt(counter)) # elif ans == ...
680a5ef170e9891d4c9616eb0b70424df12ab0df
ivan-shargin/Python_lessons
/Nash.py
813
3.65625
4
N = 2 # N strategies for both players def index(i, j): """ Returns the index of 1D array that corresponds to element (i, j) of 2D matrix. """ return i * N + j def is_nash(i, j): """ Checks if the set of strategies (i, j) is Nash equilibrium. If it is Nash equilibrium, returns True. El...
15fb00d0a083317d79e7bcbae7b69ced21f14355
Lischero/Atcoder
/codeFestival2017QualC/q1.py
155
3.734375
4
# -*- coding:utf-8 -*- import sys S = input() for tmp in range(len(S)-1): if S[tmp:tmp+2] == 'AC': print("Yes") sys.exit() print("No")
dc23c666fe852e8d2c8d7a0774ee3486f598887e
erivaldosilvamps/erivaldosilva
/phyton_basic/operedores-logicos.py
1,026
4.125
4
#aqui veremos os operadores aritimeticos n1 = float(input('Digite um numero: ')) n2 = float(input('Digite outro: ')) s = n1+n2 sub = n1-n2 mult = n1*n2 div = n1/n2 poten = n1**n2 div_int = n1//n2 resto_divi = n1%n2 print('A soma vale {}'.format(s)) print('-'*30) print('A subtração vale {}'.format(sub)) p...
73dbe3947d2e41049d1c140afea2a52229ba6c66
bopopescu/goat-python
/goat/chapter10/10.8/Counter_test3.py
1,402
3.65625
4
# coding: utf-8 from collections import Counter # 创建Counter对象 c = Counter(Python=4, Swift=2, Kotlin=3, Go=-2) # 统计Counter中所有出现次数的总和 print(sum(c.values())) # 7 # 将Counter转换为list,只保留各key print(list(c)) # ['Python', 'Swift', 'Kotlin', 'Go'] # 将Counter转换为set,只保留各key print(set(c)) # {'Go', 'Python', 'Swift', 'Kotlin'} # 将C...
dda110682ea859818e534dbb86dc6d439d6096ae
Sharanyakethineni/radius-ofcircle
/radius of a circle.py
142
4.34375
4
PI = 3.14159 radius= float(input("enter the radius of a circle: ")) area = PI* radius**2 print("area of a circle is",area)
b2e802f01889fc6dde31759b96e6ea8778a9f36c
jiceR/france-ioi
/python/charge.py
126
3.765625
4
charge1= int(input()); charge2= int(input()); chargeTotale= charge1 + charge2; if chargeTotale > 105: print("Surcharge !");
55ca4440bf22c67a4c4a22df219411947f56a1a6
smarulan613/fundamentos_prog_20211_sebasmc
/TALLERES/TAL1_cur/ej4_costoproduct.py
444
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 6 10:53:11 2021 @author: R005 """ #Realizar la carga del precio de un producto y la cantidad a llevar. #Mostrar cuanto se debe pagar (se ingresa un valor entero en el precio #del producto) precio=int(input("ingrese el precio del producto:")) cantidad=int(i...
3bd4922a2df1fde8c294f2452014907cc407f0c6
yosef8234/test
/spbau/unix/cp/task4.py
165
3.953125
4
#/usr/bin/python num = int(input()) cont = True while (num != 1) and cont: if num%2 == 0: num = num/2 else: print "NO" cont = False; if cont: print "YES"
5e308f0c3bd2bf965529a9624b0d8b2968410b14
mohits1005/DSAlgo
/sorting/minimum-absolute-difference.py
992
3.734375
4
''' Minimum Absolute Difference Problem Description Given an array of integers A, find and return the minimum value of | A [ i ] - A [ j ] | where i != j and |x| denotes the absolute value of x. Problem Constraints 1 <= length of the array <= 100000 -109 <= A[i] <= 109 Input Format The only argument given is th...
560e64a61e8bf567b39a18b96ee249a155105384
yasukei/junk
/ex/ppl/p1_6_2.py
3,487
3.8125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """and, or, shift などのビットレベルの論理演算子を使って、ビット列を実装する""" import sys import math import unittest class Nbits: """任意のビット列を表現する。かなり遅い。python組み込みのリストの方が速い""" def __init__(self, nbits=32): self.nbits = nbits bitof_elem = int(math.log(sys.maxint + 1, 2)) + 1 self.bit_mask_d...
985a4e746f76d833e30d338c1559ff47cd2e2228
Pauloa90/Python
/ex027.py
160
4.1875
4
nome = str(input('Digite o seu nome:')).upper().strip().split() print('O primeiro nome é {}'.format(nome[0])) print('O seu ultimo nome é {}'.format(nome[-1]))
1c3962a36f156d2c495a85544050eaecc277757b
Aasthaengg/IBMdataset
/Python_codes/p03556/s647568872.py
123
3.578125
4
import math n=int(input()) sum=n for i in range(1,n): if n >= i*i: sum = i*i else: break print(sum)
3e6c3133150c1d37bdf378787424a02a3bb609f4
zhiymatt/Leetcode
/Python/206.reverse-linked-list.134948582.ac.py
798
3.953125
4
# # [206] Reverse Linked List # # https://leetcode.com/problems/reverse-linked-list/description/ # # algorithms # Easy (46.74%) # Total Accepted: 338.1K # Total Submissions: 723.4K # Testcase Example: '[]' # # Reverse a singly linked list. # # click to show more hints. # # Hint: # A linked list can be reversed ei...
22dd1e39e2c69cf72a4fd8475435183cc4e5f0a7
Grifo89/Algorithms
/mutations/mutations.py
360
3.671875
4
from typing import List def mutation(arr: List[str]) -> bool: checker = [x for x in arr[1].lower() if list(arr[0].lower()).count(x) == 0] if len(checker): return False return True print(mutation(["hello", "hey"])) print(mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])) print(mutation(["Mary", "Ar...
48c5dd8f603063cc1c4abe3d75db89affac7e90a
pithecuse527/python-practice
/Ch.10/fibiter.py
616
3.640625
4
class FibIterator: def __init__(self, a=1, b=0, maxValue=50): self.a = a self.b = b self.maxValue = maxValue def __iter__(self): return self def __next__(self): n = self.a + self.b if n > self.maxValue: raise StopIteration() s...
de3b06414469c15e65ee55252c77d8ce75fa8e34
LucasEvo/Estudos-Python
/ex034.py
562
3.890625
4
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor de seu aumento. # Para salários superiores a R$ 1250,00, calcule um aumento de 10%. # Para salários inferiores ou iguais, o aumento é de 15%. sal = float(input('Qual seu salário? R$ ')) aumento1 = sal * (10 / 100) salsuperior = sal ...
6864bb7516f0c24b32c95191218dee4ad74ba102
anthonynguyen/kattis
/alphabetspam.py
309
3.9375
4
#!/usr/bin/env python3 s = input() white = lower = upper = symbo = 0 for c in s: if c == "_": white += 1 elif c.isalpha(): if c.islower(): lower += 1 else: upper += 1 else: symbo += 1 ss = white + lower + upper + symbo print(white / ss) print(lower / ss) print(upper / ss) print(symbo / ss)
f5729fa0c98379679fc504aba6971758c5738e33
Yasin-4030/Lists-and-Loops-Tutorial--CS
/Lists and Loops Tutorial/list_loops.py
817
3.8125
4
songs = ["ROCKSTAR", "Do It", "For The Night"] print(songs[0]) print(songs[-1]) print(songs[1:3]) # ............................................................. songs[-1] = "Despacito" print(songs) #............................................................... songs.extend(["Hotline Bling", "God's Plan", "Caribb...
d53ed1e8049ea63c70ef71fe17c7fd1534a6db8a
mihirkelkar/EPI
/Tricky/Deck_Shuffling/deck.py
209
3.515625
4
import random def deck(array): for ii in range(0, len(array)): temp = random.randint(ii, len(array)-1) array[ii], array[temp] = array[temp], array[ii] return array print deck([1, 2, 3, 4, 5])
27af2a5aa1652ae60188967272c7d55dde3f5033
krokhalev/GeekBrains
/Lesson6/Number4.py
2,226
4.0625
4
class Car: def __init__(self, speed, color, name, is_police): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): return f"{self.name} поехала." def stop(self): return f"{self.name} остановилась." def turn_rig...
34478082b08da72dbc15b07328e745c79416c307
AbdullahAlsalihi/python-projects
/maximum_value_of_two_numbers.py
965
4.4375
4
# Maximum Of Two Values Program # This program will allow the user to enter two values, then the program will # identify which of of the two values are the greatest than the other. # for example: If the user enter 7 for the first value # And 8 for the second value. # . Then the program will display a ...
8ef00238bc4d0d97c34719165c61a6a2916aeef9
olegpolivin/AlgorithmsSpecializationStanford
/01_Divide_and_Conquer/Week01/karatsuba.py
1,357
4.28125
4
from math import ceil print('Welcome to exercise 2: Stanford Algorithms') print('Input: two n-digit positive integers x and y') print('Output: the product x*y calculated recursively') print('Assumption: n is a power of 2') x = input('Enter first integer: ') y = input('Enter second integer: ') n = max(len(x), len(y))...
2517a18e2a9bab52d973920c78f97bbb7032fcb3
masud99r/AutoCode
/models/bidirectional_lstm_train.py
2,419
3.78125
4
'''Example script to generate text from Nietzsche's writings. At least 20 epochs are required before the generated text starts sounding coherent. It is recommended to run this script on GPU, as recurrent networks are quite computationally intensive. If you try this script on new data, make sure your corpus has at le...
e6b8c4741af8c2d9e799c014f3ad5be5803bfe64
phani1995/k_nearest_neighbors
/docs/k_nearest_neighbors_for_newbies.py
851
3.5625
4
# -*- coding: utf-8 -*- #Imports import pandas as pd #import matplotlib.pyplot as plt # Iris Dataset # Importing the dataset dataset = pd.read_csv('iris.csv') # Extracting Features and Labels dataset_feature = dataset.drop(labels = ['iris'],axis = 1) dataset_labels = dataset['iris'] # Test Train Split from sklear...
05e37d4612435beeffea3775373b9e85fb73077e
NikhilReddyPurumandla/Pyhton-Basics
/evenOrOdd.py
227
4.21875
4
#even or odd num = int(input("Enter a number: ")) def func(a): if(a%2 == 0): res = str(a)+" is a even number" return res else: res = str(a)+" is odd number" return res print(func(num))
70d807d4b156251f84cac8b13a4df18345347136
MaxLouis/Iteration
/Denary to Binary.py
1,587
3.9375
4
#Max Louis #S&C Task 2 #23/10/14 import time denary = int(input("Please enter a number from 0, up to 255")) loop = True while loop == True: if (denary > 0 and denary < 256) != True: print("Please enter a value within the boundary.") time.sleep(1) loop = False break ...
9f60992005bb56a82140b2c901ba7b38f261182a
PeilingChen/python
/2021.03.10_hw2(印出巴斯卡三角形).py
960
3.59375
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 17 00:29:10 2021 @author: user 作業二: 印出巴斯卡三角形 """ # 將各行以串列方式產生(方便用和計算新的一行) def pt(i): if i == 1: data = [0,1,0] return data else: data = [0] for a in range(i,0,-1): data.insert(1,pt(i-1)[a-1]+pt(i-1)[a]...
b44a697d77d600709ac4ffe77eab059b3d5423a5
Shreyasghodake/Ch.05_Looping
/5.2_Roshambo.py
512
3.859375
4
''' ROSHAMBO PROGRAM ---------------- Create a program that randomly prints 1, 2, or 3. Expand the program so it randomly prints rock, paper, or scissors using if statements. Don't select from a list. Add to the program so it first asks the user their choice as well as if they want to quit. (It will be easier if you h...
764065a979ef1a494f0fa403aeff174c912d8c35
kdbmeditations/simple-python-blockchain
/blockchain.py
1,110
4
4
from block import Block class Blockchain: """ The Blockchain which is made up of block data structures. Attributes: difficulty: The mining difficulty of the blockchain. max_nonce: The maximum number we can store in a 32-bit int. target: Hash target which determines if a block is ...
635675d039c7826cbcd9adbfcac1bfcf3a1d9b3f
ThamMK/BadmintonProject
/Badminton.py
1,982
3.671875
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 28 01:16:24 2017 @author: Shiangyoung """ import sys if sys.version_info.major == 2: import Tkinter as tk else: import tkinter as tk class Badminton(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) ...
ca1a032ef63f9cb66428900b6d89d4d1116f1f68
Alm3ida/resolucaoPythonCursoEmVideo
/desafio60.py
312
4.03125
4
num = int(input('Digite o número desejado: ')) # O Fatorial é definido pela operação !. n! = n(n-1)(n-2)(n-3) ... 2 x 1 c = num f = 1 print('Calculando o Fatorial de {} ...' .format(num)) while c > 0: print(f'{c}', end='') print(' x ' if c > 1 else ' = ', end='') f *= c c -= 1 print(f'{f}')
e550dc414a14bd1dd79e2964092426ba5001231f
iamliming/LeetCode
/phython/MinStack.py
1,585
3.75
4
__author__ = 'tony' # # Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. # # push(x) -- Push element x onto stack. # pop() -- Removes the element on top of the stack. # top() -- Get the top element. # getMin() -- Retrieve the minimum element in the stack. #*min: # ------...
02de3590c1de2cd59d223fdad2ef2fbaddffb946
HRahman1777/Python3_LearingAndSmallProjectsPyCharm
/OOP/Abstraction.py
587
4.28125
4
from abc import ABC, abstractmethod class Shape(ABC): #it became abstract class def __init__(self, base, height): self.base = base self.height = height @abstractmethod def calculate(self): #now this is abstract method pass class Triangle(Shape): ...
27a4bca33bac718973753ece09c3c7e1cdbfb2ca
senseyluiz/estudopython
/exercicios/ex022.py
413
4.28125
4
# Crie um programa que leia o nome completo de uma pessoa e mostre: # - O nome com todas as letras maiúsculas e minúsculas. # - Quantas letras ao todo (sem considerar espaços). nome = str(input("Digite o nome completo: ")).strip() print(f"Seu nome com todas as letras maíusculas: {nome.upper()}") print(f"Seu nome com...
20c17d127ae3515d30a00cc336d17004c222c0f5
isgla/pythonProteco
/Básico/Clases/Clase4/Ejercicios/encapsulamiento.py
710
3.65625
4
class Persona: planeta = "Tierra" def __init__(self, nombre, apellido, edad): self.nombre = nombre self.apellido = apellido self.edad = edad self.habilidades = [] self.__telefono = "55555555" def get_telefono(self): return self.__telefono def set_telefono(self, nuevo_numero): self.__telefono = nuev...
0695aa8b2083a8780d0ce73e149a4a992c8782a2
lkloh/kalman_filter_phil_kim
/recursive_filter/moving_average_filter/moving_average_filter_recursive.py
1,498
3.90625
4
#!/usr/bin/env python3 """ Chapter 2.3: Recursive moving average filter There aren't many benefits of doing it this way. as the number of data points to get the moving average is always WINDOW_DIZE, so the computation overhead doesn't increase even when a new data point is received. We need to store WINDOW_SIZE num...
673813754b3106257eb1703988ca1cfc9de426ec
Aasthaengg/IBMdataset
/Python_codes/p03359/s883924043.py
76
3.5625
4
a,b=input().split() a=int(a) b=int(b) if a<=b: print(a) else: print(a-1)
ba9728ee92aa927595e385a1fa327c160eba9f18
johnharakas/filesystem_tree
/fs_tree/tree.py
8,271
3.546875
4
""" Create a file directory and represent it as a tree. Currently only creates folders and txt files """ import collections import os import random from typing import Optional, Union import utils class Tree: def __init__(self, root): self.root = root self._nodes = {} self._nodes.update({ro...
1d5f2308e6f85022822a90878866c9d5b7c2fae2
usamah13/Python-games-
/All CMPUT 175 and CMPUT 174 code/CMPIT 174/pokev2.py
8,630
3.8125
4
# Poke the Dots - Version 2 # # Poke the dots is a game where two dots move around # in a window, bouncing off sides. If the two dots ever # collide, then the game is over. The player earns 1 # point per second before the dots have collided. # Player can tap the screen to move dots to new, # random locations. # # Versi...
8d77c88f1f89b3184153196afa4121e14256ac9e
Ryanrenqian/600x
/recurPower.py
436
3.90625
4
def recurPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' # Your code here ''' if exp==0: return 1 else: ans=base*recurPower(base,exp-1) return ans ''' if exp==0: return 1 elif exp>0 and exp%2==0: ...
ba9972dd632e760a20f460574a6b3e1728ddba32
keepTheFlowerOfTime/Study_Of_NN_Robust
/helper/viewer.py
1,001
3.515625
4
import matplotlib.pyplot as plt def image_view(*kargs): """ pic: a picture which has shape (width,height,channel) where channel always equal 1 or 3 """ number=0 images=list(kargs) for d in images: if len(d.shape)==3: number+=1 else: number+=d....
ea9936ce0fc23f9b34707b3c8da848dee8711e97
mohitsudhakar/coding
/daily_coding_problem/40_three_unique_element.py
675
4
4
""" This problem was asked by Google. Given an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer. For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19. Do this in O(N) time and O(1) spac...
f754a5d853a9e40cf788a95e40d2ad44bc14732f
ThinkAbout1t/kolokwium2
/34.py
602
3.96875
4
'''Дано два лінійних масиву однакової розмірності. Скласти третій масив з добутку елементів перших двох масивів, що стоять на місцях з однаковим індексом. виконал Пахомов Олександр''' import numpy as np import random a=np.zeros(10, dtype= int) b=np.zeros(10, dtype= int) c=np.zeros(10, dtype= int) dobutok=1 for...
c528e5108b24b0eb5cf65cf96647a9ff1fe244e9
zhiwilliam/geekcoding
/src/1-500/057/InsertInterval.py
1,207
3.609375
4
from typing import List class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: if len(intervals) == 0: return [newInterval] i = 0 # Find the right location, insert a new interval, regardless of the overlap problem while i < le...
52e4322a3057bf49d3d01e162f8ed03aabf0719e
erauner12/python-for-professionals
/Chapter 5 Date and time/5_13_Iterate_over_dates.py
295
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 26 17:13:57 2020 @author: Harry """ import datetime day_delta = datetime.timedelta(days=1) start_date = datetime.date.today() end_date = start_date + 7*day_delta for i in range((end_date - start_date).days): print(start_date + i*day_delta)
fffe2cb26bfbdd71653cf8d974287d5398d23b9e
da-ferreira/uri-online-judge
/uri/1042.py
230
3.921875
4
temporaria = input().split(' ') valores = [] for i in range(3): valores.insert(i, int(temporaria[i])) temporaria = valores[:] valores.sort() for i in valores: print(i) print() for i in temporaria: print(i)
d6fc9f943204f0599cd8ecfade9ad8df6db2680b
python20180319howmework/homework
/zhangliqiang/20180402/h3.py
297
4.09375
4
#3利用map()函数将用户输入的不规范的英文名字,变为首字母大写,其他字符小写的形式 #1) 假定用户输入的是["lambDA", “LILY”, “aliCe”]y def daxiao(l): return l[0].upper() + l[1:].lower() r = ["lambDA", "LILY", "aliCe"] s = list(map(daxiao,r)) print(s)
55d65f31339445ea064dc6682c3ddeee3bda06ed
LS-io/statistics_python
/chapter2_pythonforstatistics/datavisualisation/seabornandpandas.py
1,848
4.28125
4
## Visualisation with Seaborn and Pandas ## Similarly to how we explored visualisation with the matplotlib library, we can also use other python packages for visualising our data, seaborn being one of them. ## Let's explore how we can utilise seaborn import numpy as np import pandas as pd import matplotlib.pyplot as ...
9d6f8156b63271d5baf555125d721fbf928a404b
brayanarroyo/Automatas2
/circunferencia.py
1,038
4.03125
4
#Nombre: circunferencia.py #Objetivo: calcula el área y diametro de una circunferencia e import math #Autor: Arroyo Chávez Brayan Alberto #Fecha: 01/07/2019 import math as mat #---------------------------------------- #Función para calcular area #---------------------------------------- def calcularArea(r): area ...
c93aaa553848423e03bcfade95098db818b2fb0a
bharat-kadchha/tutorials
/core-python/Core_Python/datatstructure/IterateOverDictionaryEx1.py
622
3.765625
4
if __name__ == "__main__": file_counts = {"csv":14, "cef":15, "json":20} print("Only keys with default iteration : ") for ext in file_counts: ''' it gives the keys ''' print(ext) print("items() to use iterating over key and value both : ") for ext , count in file_counts.items(): ...
1f207c836b00f9d9ea70252d30bffcf2a21a8116
ehoppenstedt/basic_python_scripts
/juego_del_ahorcado.py
1,574
3.84375
4
import os import random def welcome(): os.system("clear") def read(): word = [] with open("./archivos/data.txt", "r", encoding="utf-8") as f: for line in f: word.append(line.strip().upper()) return(word) # def select_word(data): #selecciona aleatoriamente una palabra de la lista...
8177419dfe3e75a1984dd6daa9a4d162e97221b9
amiged/tmachine
/commit.py
16,668
3.515625
4
#!/usr/bin/env python2.7 # -*- coding:utf-8 -*- import os import logging as LG import random import commands # create logger logger = LG.getLogger(os.path.basename(__file__)) logger.setLevel(LG.DEBUG) # create console handler and set level to debug ch = LG.StreamHandler() ch.setLevel(LG.DEBUG) # create formatter for...
f7530238d1abbc2c911f4e20bfa8dccf4d15dfc3
PrachiPatki/ActivityRecognition_Project
/src/t.py
271
3.546875
4
import threading import time def temp(t): time.sleep(1) print(t) time.sleep(1) tis =[] for i in range(0,5): t = threading.Thread(target = temp, args= (i,)) tis.append(t) t.start() for t in tis: t.join(); print('is here')
514c45d39003ef5ac5cbf5b19bbb78011d5c1210
673449157/Project
/11.列表常见操作.py
1,303
4.25
4
# #添加元素 # #append的使用 # list01 = [1,2] # list02 = [3,4] # list01.append(list02) # print(list01) # #extend的使用 # list01 = [1,2] # list02 = [3,4] # list01.extend(list02) # print(list01) # #insert的使用 # list01 = [0,1,2,3,4] # list01.insert(3,'i') # print(list01) # #修改元素 # A = ['xiaoHu','xiaoMing','uzi'] # for name in A: # ...
6f981be746841ca0b1d22883ed53761480a8cc6d
RomanPutsilouski/M-PT1-37-21
/Tasks/Lebedev_Tasks/WH/Task7H/characters.py
817
3.578125
4
from random import randint class Creature: def __init__(self, health, attack, level): self.health = health self.attack = attack self.level = level class Hero(Creature): def __init__(self): Creature.__init__(self, randint(170, 280), randint(20, 40),23) class Villian(Creatur...
fd2c14688f3e4d6044af3ca81cbfcccf6ef11497
Chainyinghao/tingyunxuan
/25.py
862
3.640625
4
# -*- coding: utf-8 -*- # date:2018/10/29 #comment:socket #server import socket s = socket.socket() #实例一个socket s.bind(('127.0.0.1', 8889)) #绑定IP和端口 s.listen() conn, add = s.accept() #接收到一个连接以及这个连接的地址 print(add) while True: ret = conn.recv(1024).decode('utf-8') if ret == 'bye': break print(ret...
d4d89a6a559b11c8231845d103369e5b784f9938
mohd-kasif/bst
/binary_tree.py
3,941
4.03125
4
class Node: def __init__(self,data): self.left=None self.right=None self.data=data class BST: def __init__(self): self.root=None def insert(self,data): if self.root is None: self.root=Node(data) else: self._insert(data,self.root) def _insert(self,data,cur_node): if data<cur_node....
6651b2f0b21f0f46cdee445c927f248c4e181c95
Aring8510/dentaku
/calculator.py
5,660
4
4
#-------------------------------(メソッド)---------------------------------------------# def calc(arg_list):#逆ポーランド記法を受け取り,計算結果を返すメソッド if len(arg_list)==1: return arg_list[0] while len(arg_list)>1:#リストがただ一つの数値となった場合計算を終了する for i in range(len(arg_list)):#リストの個数分 if isinstance(arg_list[i],...
6189de13109b24d271530d28971729f32a6bbae7
binghe2402/learnPython
/刷题/Leetcode/p23_Merge_k_Sorted_Lists.py
617
3.890625
4
# Definition for singly-linked list. from typing import List class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: lists = [ln for ln in lists if ln] new_ln = ListNode(None) cur =...
668ffed9fa0f086a0a7c39fd4dbce932b0632741
JMComstock/BankAccounts
/BankAccount.py
905
3.8125
4
class BankAccount: def __init__(self, int_rate, balance = 0): self.rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): self.balance -= amount if self.balance < amount: print("Insufficient funds: Charging a $5 f...
db8b7d39588d9d737f2010d1d728ba4ae8f0f488
LeonMarqs/Curso-Em-Video-Python3
/MUNDO 3/Exercícios MUNDO 3/ex095 (Aprimorando dicionários).py
1,513
3.734375
4
jogador = {} totgols = [] galera = [] while True: jogador.clear() nome = str((input('Nome do jogador: '))) jogador['nome'] = nome partidas = int(input(f'Quantas partidas {nome} jogou? ')) totgols.clear() print('=='*20) for c in range (0, partidas): gols = int(input(f'Q...
584cb6e066dfad2ec839dbc9c202ba5e2067df9b
2dvodcast/Data-Science-1
/PythonEuler/sq_root_convergent.py
710
3.75
4
'''Project Euler Problem 57 sqrt(2) = 1 + 1/((2 + 1/(2 + 1/(2 + ... ))) = 1.414213... In the first one-thousand expansions, find how many fractions contain a numerator with more digits than denominator''' def numOfDigits(num): return len(str(num)) def main(): fraction=[1, 2] # fraction[0] = numerator, frac...
9bc07008fb331d6ccf3c395220792cccbf5201c7
kranthikumar27/demo
/cspp1-practice/m6/p2/special_char.py
589
4.8125
5
''' Replace all the special characters(!, @, #, $, %, ^, &, *) in a given string with a space. example : ab!@#cd is the input, the output is ab cd Output has three spaces, which are to be replaced with these special characters ''' def main(): ''' this program is used to print the special caracters with " ". ...
93e9beab23cbd49857168b65bbb836f7c369c38e
bfaure/DynamicMediaQualifier
/imdb.py
3,210
3.53125
4
#Python3 ''' provided a title, fetches results from IMDb, can be narrowed down by 'Movie','TV','TV Episode', or 'Video Game' ''' from urllib.request import urlopen # for downloading HTML from bs4 import BeautifulSoup # for more easily parsing HTML # returns the url for searching imdb results for the provided title. #...
c39f830e5170bf30c78896c79219e8d775f6793d
gogn-in/polls
/althingi/scripts/thjodarpuls.py
2,300
3.546875
4
#!/usr/bin/env python3 """ Script to collect polling data from Gallup (né Capacent) and output it as CSV to a file-like object (stdout by default). Gallup store their polling data in a `dataset on DataMarket`_. Using the `DataMarket API`_ we can download a CSV containing every poll since March 1994. The script is wri...
3ebcc92a5b35e716d63e69c0ae742e0f6290f4dd
mrkimkim/Google_Interview
/1_Graphs/4_GraphCycle.py
3,495
3.546875
4
#-*- coding: utf-8 -*- # 구글 면접 대비 4 - Graph Cycle """ 기본 출처 : https://www.geeksforgeeks.org/union-find/ 여기에서는 유향 그래프와 무향 그래프 둘 다에서 Cycle를 찾아 내는 방법에 대하여 다룬다 """ # 유향 그래프 O(V) class DirectedGraph: def __init__(self): self.Graph = {} self.Size = 0 self.isCycle = False def addNode(self, ...
76853f49d85fd9d01476fa7a70bac7e6577a4189
gvrajesh07/Assignment_1.11438
/User FirstName Last.py
139
4.125
4
firstname=input("What is your first name ?") lastname=input("Enter your last Name ") print(" Hey, are you " + lastname + " " + firstname)
508245032f20e789d104f290a969403ff28e38bd
qqmadeinchina/myhomeocde
/homework_zero_class/lesson5/homework/判断质数v2.0.py
1,264
3.984375
4
#!D:\Program Files\Anaconda3 # -*- coding: utf-8 -*- # @Time : 2020/7/12 0:26 # @Author : 老萝卜 # @File : 判断质数v1.0.py # @Software: PyCharm Community Edition while True: # 循环输入,直到不想测试时,输入 str_num = input("请输入您想要判断的数,q表示退出): ").strip() if str_num == "q" or str_num == "Q": break elif not str_num.isnum...
bc9f514670cebfd31495ed6b063227dd3d705d9f
999Hans/SWE-Academy
/3. 자료구조/6. 제곱 딕셔너리.py
275
3.640625
4
# 다음과 같이 정수 N을 입력받아서 1부터 N까지의 정수를 키로 하고, # 그 정수의 제곱을 값으로 하는 딕셔너리 객체를 만드는 코드를 작성하십시오. a = int(input()) b = range(1, a+1) dict1 = {i:i**2 for i in b} print(dict1)
79392e59b3eb61137c0cd0c9e5115c1c9811df64
sparkle6596/python-base
/advance python part2/exam/3Create a Book class with instance Library_name, book_name, author, pages.py
413
3.921875
4
#Create a Book class with instance Library_name, book_name, author, pages class Book: def about(self,Library_name, book_name, author, pages): self.Library_name=Library_name self.book_name=book_name self.author=author self.pages=pages print(self.Library_name,"\n",self.book_na...
a09ada86dc0347ea1c311dd2b6c212bb2aa0f903
durstido/Data-Structures-Practice
/DFS.py
574
3.78125
4
class DFS: def __init__(self): self.graph = {} self.visited = {} def addEdge(self,u,v): if u in self.graph: tmp = self.graph[u] tmp.append(v) self.graph[u] = tmp else: self.graph[u] = [v] def DFS(self, s): #s is starting vertex self.visited[s] = 1 print(s) if s in self.graph: for ...
409413b183149e30c188448658addc9545b593dc
SianCulligan/python-data-structures-and-algorithms
/python/code_challenges/ll_zip/ll_zip/ll_zip/ll_zip.py
5,808
3.96875
4
class Node: def __init__(self, nodeVal=None, nextVal=None): self.nodeVal = nodeVal self.nextVal = nextVal class LinkedList: def __init__(self, headVal=None): self.headVal = headVal def insert(self, val): strVal = str(val) insertNode = Node(strVal) if self.he...
b19ba23960030b31cdffef30fa05883268013058
fidgetlol/advent2020
/day4/4-1.py
320
3.828125
4
#!/bin/python def check_for(substrs, string): for substr in substrs: if substr not in string: return False return True with open('input') as f: input = f.read().split('\n\n') fields = ['byr','iyr','eyr','hgt','hcl','ecl','pid'] print(len([pp for pp in input if check_for(fields, pp)]))
a25b5184319ed27981953ff7a06419913c3d855c
fpgmaas/poems
/src/meter.py
8,243
4
4
import numpy as np import re import pronouncing from string import punctuation def get_word_scansion(word): """ Get the scansion per word, as a string of 0's and 1's. Example: > get_word_scansion('television') > '1010' """ word = word.strip(punctuation) if word == "": return ...
6a53ae73f3b7de1dc452cb6b48015323f2f18932
morales-gregorio/pinturillo
/maspalabras.py
959
3.65625
4
#!/usr/bin/python import sys import utils if __name__ == '__main__': argumentos = sys.argv if len(argumentos) == 1: print("Por favor, dame una lista de palabras a añadir") sys.exit(0) elif len(argumentos) > 2: print("Por favor, dame las listas de palabras de una en una") sy...
8cb5540984549d3dfc5627ee8943c994b76aa16c
lishulongVI/leetcode
/python/503.Next Greater Element II(下一个更大元素 II).py
2,388
4.03125
4
""" <p> Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next ...
657d4a724a64587b197c5aeee0414fca6bd725d0
felipegrabowsky/Knn-Classifier-on-Iris-Data
/calculate_error_rate.py
1,185
4.09375
4
######### #Name; Felipe Marujo Grabowsky #UNI: fm2579 # This program contains a function that calculate the error rates between the predicted labels my function returns # and the actual labels ####### import numpy as np def calculate_error_rate(predicted_labels, test_data): ''' function that calculates the err...
e2ef6b312bf6a4b32c887fe2e306f741e49d7d24
robotenique/mlAlgorithms
/supervised/modelEvaluation/learningCurve.py
1,093
3.671875
4
import numpy as np from trainLinearReg import trainLinearReg from linearRegCostFunction import linearRegCostFunction def learningCurve(X, y, Xval, yval, Lambda): """returns the train and cross validation set errors for a learning curve. In particular, it returns two vectors of the same length - error_tra...
196be006ac14c12af56dc4784a1d525c3387c98e
Xuxiaoyu05/Introduction_to_Algorithms
/Chapter 12 二叉搜索树/12.2 BinaryTree_Query.py
4,931
3.921875
4
# 查询:查找一个存储在二叉搜索树中的关键字。 # 查询操作:(1)Search;(2)Minimum;(3)Maximum;(4)Successor;(5)Predecessor。时间复杂度均为 O(n)。 # 定理:在一棵高度为 h 的二叉搜索树上,动态集合上的操作 Search、Minimum、Maximum、Successor、Predecessor 可以在 O(h) 时间内完成。 class Tree: def __init__(self, x): self.val = x self.left = None self.right = None self.parent = None ...
e959d2c62d626eb82226e63527a66fce31750e0a
rjcpc/stuff
/algo/mergesort.py
796
3.921875
4
# this doesn't work # but was used in class # so here it stays def MergeSort(mylist): print("dividing", mylist) if(len(mylist) > 1): me = len(mylist)//2 lefthalve = mylist[:me] righthalve = mylist[:me] MergeSort(lefthalve) MergeSort(righthalve) i = ...
f4ca4694b4d9ca917d43b582266813164f7744d8
crusaderkarthik/q-and-a
/Leapyear.py
394
4.34375
4
##Question: Write a program to find given year is leap or not ##Model 1 year = int(input('Enter year: ')) if (year%400==0) or (year%4==0 and year%100!=0): print('LEAP YEAR') else: print('NOT LEAP YEAR') ##Model 2 import calendar year = int(input('Enter year: ') is_leapyear = calendar.isleap(year) if is...
18705d2fe2ac9a4d624eac47bff9501764089d50
tuankhaitran/Pythonpractices
/UnitTest/circles.py
247
4.25
4
#Calculate circle area from math import pi def circle_area(r): if type(r) not in [int,float]: raise TypeError("The radius should be integer") if r<0: raise ValueError("The radius should be positive") return pi*(r**2)
d148e09e0e365ae046f13a760b464ac74d5427d6
luizmariz/cripto
/AL09.1/AL9.1.py
1,344
3.640625
4
#atividade de lab 9.1 n = input() for x in range(n): lista_congru,lista_mod = input() for y in range(len(lista_mod)): #inicio do AEE if y == 1: continue if y == 0: mn = lista_mod[0]*lista_mod[1] a = lista_mod[0] b = lista_mod[1] ...
ccd6bb16d09e325cbd014b246176e441497ab8b9
zbcstudy/python
/tests/test.py
948
3.515625
4
# coding:utf-8 import json from tests import commonFunction print("hello world") if 43 > 42: print("zhaobicheng") cast = ["abc", "def", "qwe"] print(cast[1]) cast.extend(["asd"]) print(cast) # for for_cast in cast: # print for_cast # isinstance 内置方法,判断数据类型 cast = ["abc", "def", "qwe", ["zxc", "ddd", ["zha", "...
75040a570db88217140a0c283d5381c80d4972e5
bbrneto/qs
/calculadora.py
633
4
4
operacao = input(''' 1 para adicao 2 para subtracao 3 para multiplicacao 4 para divisao ''') numero_1 = int(input('Primeiro numero: ')) numero_2 = int(input('Segundo numero: ')) if operacao == '1': print('{} + {} = '.format(numero_1, numero_2)) print(numero_1 + numero_2) elif operacao == '2': print('{} ...
b880d6103caf4d89c0281332afe8e6ea7d78ed7b
KondrotM/TextGame
/main.py
20,504
3.53125
4
import rooms import items import pickle import enemies import random import time cavern = [[rooms.wall,rooms.spawn,rooms.wall,rooms.wall],[rooms.sword,rooms.enemyC,rooms.wall,rooms.wall],[rooms.wall,rooms.enemyC,rooms.enemyC,rooms.potion],[rooms.enemyC,rooms.switch,rooms.passage,rooms.wall]] level = cavern class Pla...
d6f2186c055ac650cc891706b3d5d80d86085461
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_117/1226.py
831
3.640625
4
#!/usr/bin/python cases = raw_input() for case in range(int(cases)): line = raw_input().split(" ") l = int(line[0]) c = int(line[1]) strfield = [] for x in range(l): strfield.append(raw_input()) field = [] for line in strfield: fieldline = [] for height in line.split(" "): fieldline....
631e666794aa3e922082b50d9cef8e1a7987ad01
Ankeeprojects/Miles-to-Kilometers-GUI
/main.py
827
3.8125
4
from tkinter import * FONTE = ("Courier", 18, "bold") CONSTANTE = 1.609344 window = Tk() window.title("Miles to kilometers converter") window.minsize(300,200) window.config(padx=30, pady=30) label1 = Label(text="Miles", font=FONTE) label1.grid(column=2, row=0) label1.config(padx=30) label2 = Label(tex...
a355918f72e11c43ce8102e6601e036c61fc6b8d
shankar7791/MI-10-DevOps
/Personel/Rajkumar/Python/3march/p3_4.py
69
3.90625
4
n=str(input("Enter a string :")) for i in range(len(n)): print(i)
8a6d29412010be61ca8d4e8ac5645e1ab71e5f99
BlokhinMV/py_basics
/homework1_task4.py
296
4.03125
4
number = int(input('Введите целое положительное число: ')) max_num = 0 while number > 0: num = number % 10 number = number // 10 if num > max_num: max_num = num print(f'Самая большая цифра в Вашем числе: {max_num}')
78870f1ec9328eb33e3574f5ffbc9a0eafb4b559
ashendes/SudokuPyCSF
/mrv_degree_backtracking.py
1,517
3.78125
4
""" SudokuPyCSF - Solve sudoku with Python using CSF approach Version : 1.0.0 Author : Hamidreza Mahdavipanah Repository: http://github.com/mahdavipanah/SudokuPyCSF License : MIT License """ import math from mrv_backtracking import mrv_domains from backtracking import backtracking_search def var_selector(sudoku): ...
fd9de507a449005f6df4d263a87eb79d3f10e04c
2Gken1029/JSAI
/xlsxDictionary.py
1,067
3.578125
4
#!python3 import xlrd import pprint # Excelシートから単語と共起値を辞書型として取得 def exel_to_dic(sheet_name, excel_sheet): wb = xlrd.open_workbook(excel_sheet) sheet = wb.sheet_by_name(sheet_name) col_word = sheet.col_values(1) col_values = sheet.col_values(5) word_and_value = {} for word, value in zip(col...
34134c4408fffc4e926160545b87ac51ea1ac41f
cafenoctua/100knock2019
/Naoto/chapter04/knock33.py
607
3.578125
4
''' 33. サ変名詞 サ変接続の名詞をすべて抽出せよ. ''' from knock30 import morphines_read def extract_sahen_noun(): '''サ変接続の名詞を抽出''' morphines, sentences = morphines_read() sahen_noun = [] with open("sahen_noun_33.txt", "w") as fp: for line in morphines: if line["pos"] == "名詞" and line["pos1"] == "sa...
6990d6fa026608e6f68ead3799eb65b88b9392de
shjustinbaek/how_to_code_together
/exercise/remainOddOrEven.py
498
4.03125
4
def remainOddOrEven(int_list): """Delete odd or even int by length of list Arguments: int_list {[list of int]} -- [outlier deleted list] Returns: [list of int] -- [only odd or even ints] """ even=[] odd=[] for i in int_list: if i%2==0: even.appen...
27119bffe576e2b9f63797a68800895b0a6d6db2
oniaom/Projects
/Project Song Numbering/Completed Program/library.py
955
3.875
4
def isInt(string): string = string[:2] # Get the first character of the string try: # if it's an int, return true int(string) return True except ValueError: # if not, return false return False def calculateNumber(name): numberTest = 0 while True: try: ...
307115d7b0334613cd3e0f774b4d8d8105746e3d
yashhR/competitive
/Edyst/isPalindrome.py
246
3.859375
4
def isPalindrome(A): main = '' for i in A: if i.isalnum(): main += i.lower() print(main) if main[::-1] == main: return 1 else: return 0 print(isPalindrome("A man, a plan, a canal: Panama"))