blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
15fba47f232916f6bc1df9a720e5484cbe12c659
pegurnee/2016-01-667
/homework/2_hw/src/5.py
789
3.53125
4
records = [ (3, 2 , 10, 2), (2, 1 , 2 , 1), (5, 18, 9 , 2), (2, 5 , 4 , 1), (4, 3 , 2 , 1), (4, 17, 12, 2) ] def distances(rec1, records, dis): _ds = [] for r in records: _ds.append(dis(rec1, r)) return _ds def euclid(rec1, rec2): _dist = 0 for u,v in zip(rec1, ...
90a9511580892809267c7f30a50ed11ab1d09509
momentum-morehouse/house-hunting-with-python-SunriseTechie
/house_hunting.py
467
4.1875
4
# Write your code here # Exercise 1 total_cost = input("What is the cost of your dream home? ") portion_down_payment = total_cost / 4 print(portion_down_payment) current_savings = input("How much have you saved? ") r = 0.04 / 12 each_month_savings = current_savings * r annual_salary = input("What is your annual salary...
496e840d48a684894493bd801a8999e81f0553dd
Gadhy/trabajo
/boleta 7.py
1,212
3.8125
4
#INPUT cliente=input("cliente:") cajero=input("cajero:") kg_de_manzanas=int(input("ingresar los kg de manzana=")) precio_por_cada_kg_de_manzana=float(input("ingresar el precio por cada kg de manzana =")) #PROCESSING pago_total=(kg_de_manzanas*precio_por_cada_kg_de_manzana) #OUTPUT print("############################...
dedba6d17bedfd43c086419a03afd24a0c47312b
wolfstriker134/RockPaperScissors
/rockpaperscissors.py
1,886
4.25
4
print("Credit for code and program: https://www.youtube.com/channel/UCYfSGNQSzCKp-QLL4pFKqvA") print() import random while True: print('Game Starting..') choices = ['Rock', 'Paper', 'Scissors'] # bot choices bot = random.choice(choices) player = input('Rock, Paper or Scissors:') pla...
8f9f73532ddbf6387174e0b8e637467e35c66179
codingstudy-pushup/python
/top/Sort_Searching/MeetingRoom.py
638
3.5
4
from typing import List class Solution: def solve_1(self, intervals: List[List[int]]) -> bool: intervals.sort() for i in range(len(intervals) - 1): if intervals[i][1] > intervals[i + 1][0]: return False return True def solve_2(self, intervals: List[List[in...
c2d83fbd0eb7eb8edf44dd5301883fb3553dc4a1
imranali18/RPA4
/source/class_code/lec13_parse_legos.py
553
3.90625
4
""" Building the list of legos from a file. Each line of this file contains the name of a lego and the number of copies of that lego, separated by a comma. For example, 2x1, 3 2x2, 2 """ lego_name = input('Enter the name of the legos file: ').strip() lego_list = [] for line in open(lego_name): line = line.spli...
f0b226626c86a66be2f9723cc200bd56f8fbc0ee
lc-rodrigues/Intro-Python-2019.1
/exercicios/aula6/exercicio6.py
2,248
4.25
4
import turtle # nos permite usar as tartarugas (turtles) cor_fundo = input("Que cor gostaria que que fosse sua janela? ") cor_linha = input("Que cor gostaria que fossem suas linhaa? ") largura = input("Considerando 1 o mais fino possível, quão largas gostaria que fossem suas linhas? ") jn = turtl...
3477f677f591fda9efc7fccfec641b0c5afe9a77
ryandavis3/leetcode
/frog_jump/frog_jump2.py
1,064
3.65625
4
import sys from functools import lru_cache from typing import List sys.setrecursionlimit(2500) def canCross(stones: List[int]) -> bool: # Cannot make first jump if stones[1] - stones[0] != 1: return False # Set of stones stones_set = set(stones) L = len(stones) # Dynamic programming wi...
e5e75a1c2cb0c7f4ce2975a6dfbb5c95c838618d
ahmadraad97/py
/numpy4.py
2,654
3.796875
4
from numpy import * # ممكن حساب الارقام التي ليست صفر a=random.randint(0,10,(3,3)) b=count_nonzero(a) print(a) # [[2 4 2] # [6 3 7] # [3 2 2]] print(b) # 9 # او تحديد عدد الارقام اكبر او اصغر من كذا a=random.randint(0,10,(3,3)) b=count_nonzero(a>5) c=count_nonzero(a<5) print(a) # [[0 4 1] # [4 9 4]...
6b0d985ac417982931eda6955c6e1081bd5b600d
BizShuk/code_sandbox
/python/test_sort.py
365
3.75
4
from functools import cmp_to_key def s(c,d): print(c,d) print(c['a'],d['a']) if c['a'] > d['a'] or (c['a'] == d['a'] and c['b'] < d['b']): return 1 if c['a'] < d['a'] or (c['a']==d['a'] and c['b']>d['b']): return -1 return 1 a= [{'a':3,'b':4},{'a':4,'b':3},{'a':3,'b'...
adac6fb79f124e14675f9f1ffec1544180614193
AndersonBatalha/Programacao1
/Estrutura de Decisão/decisão-02.py
290
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 2. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. while True: numero = float(raw_input("Número: ")) if numero > 0: print "Positivo." elif numero < 0: print "Negativo." else: print "Zero."
58223e30daa64dbf4af72dd63fc6e0fc5fdca275
anastasiabya/python-tasks
/hometask4.py
3,821
3.921875
4
########################################## # TODO задание 1 ########################################## """Переделать приведенный for""" print("Результат задания 1 - списки должны совпасть!") l = [] for i in range(3, 23, 2): l.append(i) new_l=[] new_l = [i for i in range(3, 23, 2)] print(new_l) pr...
dfa4ab7e69d0d408c0f0edd821a340aebf34e474
jia3857/doubledrops
/MC/py/minecraft-cubes-and-towers.py
2,679
4.03125
4
""" Make cubes and towers in Minecraft, with Python. Really fun way to introduce a kid to Python (or yourself to Minecraft, as I've learned). Setup instructions for Minecraft + macOS + Python: https://gist.github.com/noahcoad/fc9d3984a5d4d61648269c0a9477c622 Additional setup: - Activate correct Java ve...
bbabc35363cda5d3dc0753bd1c175c6b8e6fd009
Pfeffer-Hu/numpytest
/np_clip.py
237
3.53125
4
""" Ҳ˵clipеԪa_min, a_max֮䣬a_maxľʹ a_maxСa_min,ľʹa_min """ import numpy as np x=np.array([1,2,3,5,6,7,8,9]) np.clip(x,3,8)
578ed6c95e2075f834eaa84053f064f8afaf42c1
ramkishorem/pythonic
/session4_while_dict/04.py
1,187
4.46875
4
""" Know the language enough to write my own dictionary. So far, we saw to 'iterable(loopable)' data structures, lists and tuples. They have one key thing in common. They have integer indices. eg: [2], [-1], [1:7]... Let us see the limitation of that in some use cases. """ # Say, we want to store info about players ...
ebe23c916d70d8411bb9e1b0855e4b4fe21da66d
YashwanthCS/individual-string-count
/Count.py
399
3.9375
4
import operator def most_frequent(string): res={} for letter in string.lower(): if not letter.isalpha(): continue elif letter in res: res[letter]+=1 else: res[letter]=1 return res string=str(input("Enter your string here : ")) op=most_frequent(s...
aa616db476041a19ffb08b1e76545de35fe63967
basilije/CIS104
/main2.py
375
3.765625
4
from calc import calculator first_text = "" operations = ["+", "-", "*", "/", "^"] while True: calculation_text = first_text + input("Enter your calculation: " + first_text) for o in operations: if len(calculation_text.split(o)) == 2: first_text = str(calculator(float(calculation_text...
c32748105950f61cf2b0d571eeafa1ea0654da9a
sqq0216/testLearn
/pythonLearn/python/test/hignfunc.py
232
3.5
4
# 返回函数 def count(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs if __name__ == "__main__": f1, f2, f3 = count() print(f1(),f2(),f3())
304ebebb813fd74d378828b007601f99971c82bd
Psingh12354/Python-practice
/MergeDict.py
145
3.859375
4
def merge(dict1,dict2): return(dict2.update(dict1)) dict1={1:'Pk',2:'FK'} dict2={3:'ds',4:'fr'} print(merge(dict1,dict2)) print(dict2)
5ba484b433727b7a8964ee20b0081d682aeca5c6
Devraj789/python-files
/a/Basic/server.py
1,875
3.859375
4
''' Definition: A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number. Every TCP co...
06765359e7c0fe14baa07e4869e3d324bbfe6c84
HarrisonMc555/adventofcode
/2020/day04a.py
828
3.921875
4
#!/usr/bin/env python3 INPUT_FILE = 'input04.txt' REQUIRED_KEYS = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] def main(): with open(INPUT_FILE) as f: text = f.read() passports = parse_passports(text) print(count_valid_passports(REQUIRED_KEYS, passports)) def parse_passports(text): passp...
dbe9514390279ed2e9eeb54b702913b1ac2b1c34
diego-vicente/machine-learning
/3/dogs.py
915
3.828125
4
import numpy as np import matplotlib.pyplot as plt import random # Create a population of 500 greyhounds and 500 labradours greyhounds = 500 labs = 500 # Greyhounds will be 4 inches taller in average, and the population will have # 4 inches of deviation. grey_height = 28 + 4 * np.random.randn(greyhounds) lab_height =...
bd8e0e2d4c89efd85052f34a8d3c1c846d69d3a6
seoyoungsoo/CodingTest-Python
/Programmers/Lv1/lv1_문자열내림차순으로배치하기.py
277
3.546875
4
# 문자열 내림차순으로 배치하기 def solution(s): str = "" s_s = sorted(s, reverse=True) for i in s_s: str += i return str # 다른 풀이 def sol(s): return ''.join(sorted(s, reverse=True)) # testcase 1 s = "Zbcdefg" print(sol(s))
24be7127abedf027c838125400e0147e0b99f480
herojelly/Functional-Programming
/Chapter 3/3.8.py
253
3.8125
4
def main(): import math print("This program finds the Gregorian epact.") year = eval(input("Enter the year: ")) C = year//100 epact = (8 + (C//4) - C + ((8 * C + 13)//25) + 11 * (year%19))%30 print("The epact is", epact) main()
a2e76490be937473c4419655eb21aefe26ec0ff9
lopz82/exercism-python
/anagram/anagram.py
306
3.78125
4
from collections import Counter from typing import List def find_anagrams(word: str, candidates: List[str]) -> List[str]: return [ candidate for candidate in candidates if Counter(candidate.lower()) == Counter(word.lower()) and candidate.lower() != word.lower() ]
e128b8028afd6212799ada48f547a51f23629a05
RenatoDeAquino/DSlayer
/char.py
462
3.765625
4
from os import stat import random name = input("Digite o nome do seu personagem\n>") status = { 'força': random.randint(1, 10), 'agilidade': random.randint(1, 10), 'destreza': random.randint(1, 10), 'respiração': 0, "vitalidade": random.randint(1, 10) } inventario = { "armas"...
dc1c5128f605d96b1824fa5f5f1cdf156d8de41a
Yobretaw/AlgorithmProblems
/EPI/Python/Searching/12_5_search_sorted_array_of_unknown_length.py
1,881
3.703125
4
import sys import os import math import imp import random """ Design an algorithm that takes a sorted array whose length is not known, and a key, and returns an index of an array element which is equal to the key. Assume that an out-of-bounds access throws an exception. """ class MyList(list): def at(s...
56467dd6088cf59718abab7dd0a092f79c72737d
RodrigoMSCruz/CursoEmVideo.com-Python
/Aulas/ex004.py
471
3.859375
4
algumtexto = input('Digite algo: ') print('{} é alfabético: {}.'.format(algumtexto, algumtexto.isalpha())) print('{} é numérico: {}.'.format(algumtexto, algumtexto.isnumeric())) print('{} é caixa alta: {}.'.format(algumtexto, algumtexto.isupper())) print('{} é caixa baixa: {}'.format(algumtexto, algumtexto.islower())) ...
d82ce7ed1d5d48b21a1a37400437b1c1add14db5
alvarogomezmu/dam
/SistemasGestion/Python/2ev/Actividad1/Ejercicio01.py
692
3.640625
4
#_*_coding:utf-8_*_ ''' Escribir los numeros pares comprendidos entre el 1 y el 100 en un fichero y luego lo muestras ''' import os def comprobarFichero(f) : if (f, os.W_OK) : print 'Fichero OK, Escritura OK' elif (f, os.R_OK) : print 'Fichero OK, Lectura OK' else : print 'Fichero no OK' def escribirPares(...
1ea73710202fc343b4494e0075bd7a5271c86dff
Sanfengzhu/Leetcode-Python
/2/addTwoNumbers.py
1,364
3.765625
4
#You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 0 -> 8 # Definition for singly-linked list. # class Li...
89830af8b279894342095a341c9fbb6a93108e77
CodecoolGlobal/lightweight-erp-python-cumpanasi
/store/store.py
5,354
3.5
4
""" Store module Data table structure: * id (string): Unique and random generated identifier at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters) * title (string): Title of the game * manufacturer (string) * price (number): Price in dollars * in_stock (nu...
04ffbb6a85d0f39e7a43926fd5a9c6621688257c
gddickinson/python_code
/geoPython_tutorial/geoPython_tutorial_2 2.py
4,100
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 29 13:20:20 2020 @author: g_dic https://automating-gis-processes.github.io/2016/Lesson2-geopandas-basics.html """ # Import necessary modules import geopandas as gpd # Set filepath (fix path relative to yours) fp = r"C:\Users\g_dic\Documents\geoPython_tutorial\Data\DAMSE...
348f881a06e1606fee4864c2822f4854b6a7c350
ramya42043/RAMYA_VT_WORK
/Knowledge/VTpython/PRacPy/1_A4.py
408
3.84375
4
#!/usr/bin/python mylist=[] num=input("Please enter the numbers or 0 to exit : ") while(num!=0): mylist.append(num) num=input("Please enter the numbers or 0 to exit : ") print mylist len1=len(mylist) index=0 num=0 print len1 while(num<len1): if(mylist[index]<0): ele=mylist.pop(index) print ele mylist.append(el...
1cbd798a0dd4aaf9b928edaa691f6735c3886498
lxyshuai/leetcode
/559. Maximum Depth of N-ary Tree.py
1,766
4.25
4
""" Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. For example, given a 3-ary tree: We should return its max depth, which is 3. Note: The depth of the tree is at most 1000. The total number of nod...
ea9df7d7b6e29216bea2c1f7124196332795be4d
SandhyaKamisetty/CSPP-1
/cspp1-practice/m3/iterate_even_reverse.py
207
4.59375
5
''' @author : SandhyaKamisetty The program prints even reverse using while loop ''' print('Hello!') i = 10 while i >= 2: print(i) i = i-2 print('Hello!') for A in range(10, 0, -2): print(A)
270c813029cfeb9f1f70a76a4d4ecae3ce3ecfac
woodsleaf/matrixpifagora
/matrix.py
11,874
3.53125
4
# -*- coding: utf-8 -*- import sys import os from tkinter import * import tkinter as tk import tkinter.ttk as ttk import tkinter.messagebox as messagebox from tkinter import Menu import re from functools import reduce import argparse parser = argparse.ArgumentParser(description='Enter birthday') parser.add_argument( ...
87d334dd48f6801396d8e9c5b4e249173585b35e
c2huc2hu/Isometric-Game
/map.py
1,346
3.796875
4
from tile import Tile class Map(): def __init__(self, map_width, map_height): self.tiles = [[Tile(x, y, Tile.PLAIN) for y in range (map_height)] for x in range (map_width)] self.width = map_width self.height = map_height #Overloading get, set, iter and next to allow its use as ...
6123de7078ed83df9616cee9923474e74fca327c
LinuxKernelDevelopment/algs_py
/ch4/DepthFirstPath/DepthFirstPaths.py
1,508
3.59375
4
#!/home/hmsjwzb/python/bin/python3.5 import sys from In import In from Graph import Graph class DepthFirstSearch: def __init__(self, G, s): self.s = s self.edgeTo = [None] * G.Vertex() self.marked = [None] * G.Vertex() self.count = 0 self.dfs(G, s) def dfs(self, G, v): ...
2c4bcc1f985b7eb61d2b4d996a7840bdb522922b
ghldbssla/Python
/프로그램 만들어보기/Quiz.py
554
3.875
4
#Quiz.py choice=0 while True: print("다음 중 프로그래밍 언어가 아닌것은?(종료하려면 0)") print("1.파이썬") print("2.Java") print("3.망둥어") print("4.C언어") choice=int(input("정답 입력 : ")) if(choice==3): result="정답입니다." elif(choice==1 or choice==2 or choice==4): result ="다시 한번 생각해보세요." elif(...
14c037c311f6b8344010579b06d71a99a3526b36
zeebraa00/python_practice
/실습_8_4_국가별_무역수지_정렬.py
901
3.9375
4
# 파이썬 8일차 db = [] def enter() : a=input("국가명(종료:0) : ") if a=="0" : return else : b=int(input("수입 : ")) c=int(input("수출 : ")) db.append([a,[b,c,c-b]]) enter() def func1() : db.sort(key=lambda x:x[0]) # print(db) print("%s %s %s"%("국가명","수입액","수출액")) print("-----------------------") ...
b05ee3f21cb0e4ce229e70208e3c5f1f8c3120a1
srengifo79/Tesis
/preguntas.py
8,314
3.625
4
# -*- coding: utf-8 -*- from random import randint import sys reload(sys) sys.setdefaultencoding('utf8') #Numero Antes def numeroAntes(minn, maxn): numero = randint(minn,maxn) pregunta = '¿Qué número está antes del ' + str(numero) + '?' respuesta = numero - 1 return [pregunta, respuesta, None] #Numer...
9e14d696b6e35463f99b204cfe27235df7c145d6
ericasu33/LHL-Fundamentals-to-Python
/Bill splitter.py
508
4.03125
4
subtotal = float(input("Bill Total: ")) tipPercentage = int(input("Tip Percentage: ")) contributors = int(input("Number of People: ")) tax_rate = 0.14 tax = round(subtotal*tax_rate,2) total = round(subtotal + tax,2) tips = total*tipPercentage/100 overall_total = round(total+tips,2) total_per_person = round(overall_...
2291a6767aa40757727ef9a9067b3b723b3c6917
vuongvx96/Linux
/BT_TrenLop_24-4/Mang.py
944
3.5
4
# Mang trong Python #-- Ham nhap mang def Nhapmang(arr,n): for i in range(n): arr.append(int(raw_input("Nhap vao phan tu thu %d = " %(i+1)))) #-- In mang vua nhap def Xuatmang(arr): for item in arr: print item, #-- Ham xuat cac phan tu chan def Inchan(arr): for item in arr: if (int(item) % 2 == 0): print ...
ba7c3ca5d6f0c53362e6eb79a790ab59b72d7f8f
jsw0402/python-practice
/py4-Q3.py
181
3.609375
4
input1=int(input("첫번째 숫자를 입력하세요:")) input2=int(input("두번째 숫자를 입력하세요:")) total=input1+input2 print("두수의 합은 %d입니다."%total)
c694f25bf9a2c693871f70c06967f8c5e2e82bc5
sagitta1969/lesson_6
/zadanie_2.py
647
3.90625
4
class Road: def __init__(self, _lenght, _width): self._lenght = _lenght self._width = _width def calc(self): print(f"масса асфальта дороги: {self._lenght * self._width * 5 * 0.025} тн") def main(): while True: try: new_road = Road(int(input("введите...
6c2aed7b1f1e11d1112f44dfaa786f79156a151f
raykstar/1st
/hello.py
48
3.640625
4
s= input("Your name: ") print("Hello "+s+" !")
a53c348e955cd46be9cad01fbd39c696ef63f34e
Oxtin/Python_homework
/3107.py
1,105
3.65625
4
class student: a = 0 def __init__ (self, Name, Gender): self.name = Name self.gender = Gender self.grades = [] self.avg = 0 self.FailNumber = 0 def add (self, Grade): self.grades.append(Grade) def compute(self): sum = 0 n = 0 for i in self.grades: if i < 60: n = n + 1 sum = sum + i se...
5b19110d7ad4811ed14d7d7c557ae7fef5caee04
kinqston34/python_program
/PycharmProjects/python_basic_language/e.py
133
3.671875
4
#f : f-string {} #r : 原樣(raw) #u :unicode w = {'a':1 ,'b':2} print(f"{w['a']} : {w['b']}") x = 1 print(f'{x+1}') print(f'{x+1=}')
3d8e00c6b5257d73b45a378030dba9f813183477
venanciomitidieri/Exercicios_Python
/053 - Detector de Palíndromo.py
610
4.09375
4
# Exercício Python 053 - Detector de Palíndromo # Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. frase = str(input('Digite um frase: ')).strip().upper() palavras = frase.split() junto = ''.join(palavras) inverso = '' for letra in range(len(junto) - 1,...
5753c0dcf089e8d831a75c897662155d88a3dc33
Babken/python-hometask
/homework.shahane_2.extra1.py
335
3.953125
4
while True: password = input ("Password Validator: ") cl = False cu = False for i in password: if i.isdigit(): cl = True elif i.isupper(): cu = True if cl == True and cu == True: break if cl == True and cu == True: print(password)...
c6daf21ed8d918977acea09990a85b60fa6c6ba7
ZerafCode/python21
/string/006.py
655
4.0625
4
message = 'welcome to python' name = 'lina' print(name, message) print(name + message) new_message = ", ".join((name, message)) print(new_message) print('%s %s' % (name, message)) print('%s, %s! ' % (name, message)) print('<< %s, %s! >>' % (name, message)) print("%s %s %s %s " % ("welcome", "to", "python", "Hub")) numb...
756a4aa89a249bebf39f702902b2579c65c6ed68
idealhang/Python
/class18-1.py
259
3.84375
4
def sxh(number): temp = (number % 10) ** 3 + (number // 10 % 10) ** 3 \ + (number // 100) ** 3 if temp == number: return True for number in range(100,1000): if sxh(number): print(number)
a97f074c559e5a091ac66053e99a1d7207cbe638
arkimede/pysynfig
/objects/tags/Vector.py
794
3.703125
4
class Vector: def __init__(self, x,y): self.x = x self.y = y self.node = None def __init__(self,x,y,node=None): #self.x = x #self.y = y self.node = node self.setX(x) self.setY(y) def setNode(self, node): self.node = node def getNode(self): return self.node def getX(self):...
c3082cd199a96057ace4d8a80578d45db7e0447d
ucarkadir/learning-python-from-zero-to-hero
/36_manage_private_variables_test.py
427
3.59375
4
class Person: def __init__ (self, first_name, email): self.first_name = first_name self._email = email def update_email(self, new_email): self._email = new_email def email(self): return self._email tk = Person('Tk', 'tk@mail.com') print(tk.email()) # => tk@mail.co...
d34c36c134e00365db671444b782bf6d77a51e9f
nickayresdemasi/adventofcode
/code/2017/day3.py
2,078
4.03125
4
''' @author: Nick DeMasi Code to complete Part 2 of Day 3 of 2017 Advent of Code using Python 3 ''' import sys class SpiralGraph(object): def __init__(self): self.grid = {} def build_graph(self, num): '''Constructs a sprial graph in counterclockwise direction. INPUT: ...
224d431cba64ce85b938bd08fe0242df31998276
greenfox-velox/danielliptak
/week3/day4/demo2v2.py
388
4.03125
4
def search_palindromes(in_put): palindrome_list = [] length = 3 end = i + length temporary = in_put[i:end] while length < len(in_put)-1: for i in range(len(in_put)-length+1): if temporary == temporary[::-1]: palindrome_list.append(temporary) length += 1 return palindrome_list output =...
fa601633904ab15137009c984347e13fbb69326a
timothyblack/qishialgo
/GoldmanSachesOA/medium/lint1611_smallestLength.py
2,568
3.703125
4
""" https://www.lintcode.com/problem/shortest-subarray/description Time O(N^2) brute force """ class Solution: """ @param nums: @param k: @return: return the length of shortest subarray """ def smallestLength(self, nums, k): start, presum = 0, 0 minlen = sys.maxsize ...
c0eb0a88d364d9b69c9d04a9c7634d404d637c1d
hongwenshen/Python_Study
/Python 100例/Python 练习实例33.py
267
3.5
4
#!/usr/bin/env python # coding=UTF-8 ''' @Description: About practicing python exercises @Author: Shenhongwen @LastEditors: Shenhongwen @Date: 2019-03-04 19:58:49 @LastEditTime: 2019-03-04 20:06:29 ''' L = [1, 2, 3, 4, 5] s1 = ','.join(str(n) for n in L) print(s1)
d595491513c1347e14477c2097c32ba3a0bf2897
andres-root/hackerrank.com
/Algorithms/MaximizingXOR/NonOptimalSolution.py
244
3.640625
4
#!/usr/bin/python3 if __name__ == '__main__': l = int(input()) r = int(input()) m = -1 for i in range(l, r + 1): for j in range(l, r + 1): c = i ^ j if m < c: m = c print(m)
0c026a5e80b4071bdd00609228bb4702b9309fa8
anzhihe/learning
/python/source_code/source_code_of_lp3thw/ex6old.py
1,481
4.34375
4
# 将“字符串”赋值给"变量x",该字符串中有个位置是用“%d”(包含格式)来代替的。%d这个符号看起来有两个作用:第一个作用是“占位符”——正名这个位置将来会有个东西放在这里;第二个作用是“这个东西的格式”,既然其使用了%d,我认为其应该是digital——数字的。 x= "There are %d types of people." %10 # 建立了给新的变量binary,将字符串“binary”赋值给了它。一般来说,变量会用简单的写法,竟然也可以直接使用单词。 binary="binary" do_not="don't" y="Those who know %s and those who %s."%(binar...
1143c5cd1155191a5c71396c82628326e15252f7
Jonathas-coder/Python
/ex 69.py
731
3.859375
4
women20=0 homem=0 maior=0 while True: print('-'*25) print('CADASTRE UMA PESSOA') print('-'*25) idade=int(input('Qual a idade: ')) if idade > 18: maior+=1 sexo=str(input('Qual o sexo [M/F]: ')).upper() if sexo == 'M': homem+=1 else: print('DIGITE UM SEXO VÁLIDO POR...
e2ad1caa304b1c42b08d2d6291f043f8d52be71d
Raeebikash/python_class1
/python_class/while_loop24.py
119
3.6875
4
#loops #while loop, for loop #print('ellow world')# 10 times i = 1 while i <= 10: print("hellow world") i +=1
49fcf2420137fdf4d0cc6f64bc257264cedf0b72
EmmanuellaAlbuquerque/Curso-Em-Video
/Python Mundo3 - Estruturas Compostas/desafio - 95.py
3,458
3.75
4
# APROVEITAMENTO DE UM JOGADOR DE FUTEBOL time = list() jogador = dict() partidas = list() # ENTRADA DE DADOS while True: jogador.clear() jogador['nome'] = str(input('Nome do jogador: ')) tot = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) partidas.clear() for c in range(0, t...
98ea61d9ec010b05df2a0c0abf3791b04b8b54e9
rippedpant/bioinformatics
/rosalind/mortal_fibonacci_rabbits.py
716
3.96875
4
""" Calculate the total number of pairs of rabits that will remain after n-th month if all rabits live for m month. """ def calc_mortal_rabbits(n, m): """ n (int): number of months to endure m (int): number of months after which rabbits die Return (int): total number of rabbits pairs """ pairs...
b678d5c16777c3a3770c8105c455c8a2f52d1056
chom125/Algorithms-UCSanDiego
/1_course/5_week/2_primitive_calculator/python/main.py
2,139
3.8125
4
# python3 ## # # Python3 implementation to find the minimum amount of operations on a primitive calculator to obtain N # The primitive calculator has 3 operations: multiply by 2, multiply by 3, and add by 1 # # (c) Copyright 2019 Clayton J. Wong ( http://www.claytonjwong.com ) # ## from typing import List, Dict Type...
cf4dfb4e4b16e0949cd917317dd8f5d1549e408d
psalc/ds4a
/encryption-decryption-scripts/decryption.py
1,189
3.828125
4
#!/usr/bin/env python # coding: utf-8 # In[7]: import random import math import ast # Setting up replacement dictionary constant letters = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ") values = list(range(1, 54)) replacement_dict = {} for letter, value in zip(letters, values): replacement_dict[l...
a0a8fd3e17f7f0a04a99cb8840720ab7592520a0
rodolfopardo/codigos
/Temperaturas.py
1,531
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 28 15:36:19 2019 @author: rodolfopardo """ # import import matplotlib.pyplot as plt %matplotlib inline # axis x, axis y y = [33,66,65,0,59,60,62,64,70,76,80,81,80,83,90,79,61,53,50,49,53,48,45,39] x = list(range(len(y))) # plot plt.plot(x, y) plt...
c54e976a32093a93011aa766912f2383260dbb9a
Kutukas/python-project-lvl1
/brain_games/games/gcd.py
699
3.625
4
import random from brain_games.engine import run_game def gcd(a, b): ''' find the greatest common divisor of integers a and b with the euclidean algorithm ''' rem = max(a, b) # rem is remainder next_rem = min(a, b) rest = rem % next_rem while rest != 0: rem, next_rem = next_re...
f97d5922e954d32563a603ed7464cadeba001e5b
MarkHofstetter/python-kurs
/kurs-20170410/zahlen_unterteilen.py
556
3.8125
4
""" + die zahlen von 1-10 sollen unterteilt werden + in gerade und ungerade + und nur wenn ungerade soll auch angezeigt werden, dass die Zahl groesser als 5 ist """ for i in range(1,11): u = i/2 larger_than_5 = '' if u == int(u): odd_or_even = 'gerade' else: ...
ca36d5e48aa46594bf790fafe8ab579a98861775
ZacharyWatanabe/SudokuSolver
/Example.py
1,114
4.0625
4
from SudokuConstraintSolver import SudokuConstraintSolver from SudokuBacktrackingSolver import SudokuBacktrackingSolver """ Example.py Zachary Watanabe-Gastel Iterate through the list of sudoku puzzles and print the solutions """ def sub_routine1(solver): #written for constraint solver success = solver.ac3...
0272a04ca5d54d92e047363d9f65f827767e1d81
JhordanRojas/Trabajo-05
/boletas/prog13.py
971
4.1875
4
#INPUT cantidad_de_productos=input("Ingrese la cantidad de productos:") precio_del_producto1=int(input("Ingrese el precio del producto1:")) precio_del_producto2=int(input("Ingrese el precio del producto2:")) precio_del_producto3=int(input("Ingrese el precio del producto3:")) #PROCESSING Total=(precio_del_produc...
839b8cef14e0161dc98ef25f15316685dcffd1d9
iptoninho/learnings
/python/EstruturaSequencial/ex10-convTempCelcToFar.py
134
3.65625
4
c = input("Entre com a temperatura em graus Celsius: ") f = (c * 1.8) + 32 print "%.2f graus Celsius sao %.2f Farenheit." % (c,f)
fd57f1dd8b1e714b0c60cca5cfb3b27521dd0a43
BoxBy/Python
/20200117/Practice10.py
1,701
3.734375
4
# https://github.com/BoxBy/Cpp/tree/master/20191128 : Cpp to Python class Wordlist : def __init__(self) : self.__dictonary = [] self.__wordlist = [] inFile = open("dict.txt", 'r') lines = inFile.readlines() for line in lines : self.__dictonary.append(line) ...
f81c058af9187eb2d7962e889aef51ccd9e0e1ce
keyPan-GitHub/MyPythonCode
/day3/深浅拷贝.py
398
3.984375
4
n1 = 123 n2 = n1 print(id(n1)) print(id(n2)) import copy n1 = 123 n2 = copy.copy(n1) print(id(n1)) print(id(n2)) n2 = copy.deepcopy(n1) print(id(n1)) print(id(n2)) n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} n2 = copy.copy(n1) # 浅拷贝第一层不一样, print(id(n1),id(n2)) # 浅拷贝第二层内存地址相同 print(id(n1["k1"]),id(n2["k1"]))...
501237f342c572001f7dd695894ddb21b4833271
ariji1/Competitive_Programming
/Day_6/queue_two_stacks.py
2,215
3.953125
4
import unittest # class QueueTwoStacks(object): # # Implement the enqueue and dequeue methods # def enqueue(self, item): # pass # def dequeue(self): # pass class Stack(): def __init__(self): self.stk = [] def pop(self): """raises IndexEr...
5e4645e0956833f49738d4740f0cdad8d4f5830c
fuzzyslippers/my-test-projects
/hangman.py
791
3.578125
4
#!/usr/bin/env python import random import urllib animals = urllib.urlopen('http://davidbau.com/data/animals').read().split() print 'time to play hangman' secret = random.choice(animals) guesses = 'aeiou' turns = 5 while turns > 0: missed = 0 for letter in secret: if letter in guesses: print letter, else: ...
eb1498cab2257304b70a23a80dd55d0ae14747f4
pritam1997/python-test-4
/q6.py
164
4.09375
4
for r in range(6): if r == 0 or r==3: for c in range(5): print("*",end="") print() else: for a in range(2): print("*",end=" ") print()
2677bf06bd507748a12bb10ff3884f046c0b785f
hrushigade/learnpython
/divisiblebygivennumber.py
194
3.875
4
lower=int(input("enter lower range limit")) upper=int(input("enter upper range limit")) n=int(input("enter the no to be divided")) for i in range(lower,upper+1): if(i%n==0): print(i)
6ecf0df7f715abb298aa5fa11f1f2c07a27d2171
Hamza122000/Python-projects
/hw10/hw10.py
3,767
3.84375
4
class Complex: def __init__(self,real,imag): self.real=real self.imag=imag def get_real(self): return self.real def get_imag(self): return self.imag def set_real(self,new_real): self.real=new_real def set_imag(self,new_imag): ...
fde1cef5e0f3283966c77d7075776443e6207b7a
hungphat/hackerrank-30days
/day_13/Abstract_Classes.py
1,110
3.859375
4
def run(input, output): from abc import ABCMeta, abstractmethod class Book(object, metaclass=ABCMeta): def __init__(self, title, author): self.title = title self.author = author @abstractmethod def display(): pass #Write MyBook class class my_book(Book):...
425f98f0cc8d814e7e7d76f7a45e827ef3630716
KoliosterNikolayIliev/Softuni_education
/Python advanced 2020/Exercise Comprehensions/2.Words Lengths.py
159
3.8125
4
strings = [x for x in input().split(", ")] dictionary = {name: len(name) for name in strings} print(', '.join([f"{k} -> {v}" for k, v in dictionary.items()]))
41ec27066d64ad15298bb06512935d3c99da7ce7
aulee888/LeetCode
/Climbing Stairs.py
739
3.65625
4
class Solution: def rec_climbStairs(self, n: int) -> int: """Recursive Solution""" if n <= 2: return n else: step1 = self.rec_climbStairs(n - 1) step2 = self.rec_climbStairs(n - 2) return step1 + step2 def dp_climbStairs(self, n: int) ->...
ea20c8e998240825c39354ad7856744e5976a6fa
Vixus/LeetCode
/PythonCode/Monthly_Coding_Challenge/Aug2020/Find_All_Duplicates_in_an_Array.py
1,129
3.953125
4
from typing import List class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: """ Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do i...
8cb5ab4f1ccbd2ce090e5aaa8be12b60b81e7ca5
nathanlct/cp
/project_euler/53.py
734
3.6875
4
""" There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 In combinatorics, we use the notation C(3, 5) = 10. In general, C(r, n) = n! / (r! (n - r)!) for r <= n. It is not until n >= 23, that a value exceeds one-million: C(10, 23) = 1144066 How many, not n...
9bc0819dfc68a94b14910e8c33751ca86869cbe8
jonfisik/ScriptsPython
/Scripts3/exercicio1.py
1,078
4.28125
4
print('-----'*10) frase1 = input(' Digite uma frase: ') print(' A frase >> {} << será "fatiada".'.format(frase1)) print(' ',frase1[3]) print(' ',frase1[6:]) print(' ',frase1[:6]) print(' ',frase1[4:10]) print(' ',frase1[::2]) print(' O tamanho da frase é {} '.format(len(frase1))) print('-----'*10) print(' O caracte...
da0047c0fd4264ed22474955e5d39bc0b5da708d
andylws/SNU_Lecture_Computing-for-Data-Science
/HW4/P8.py
1,890
4.0625
4
""" A sparse vector is a vector whose entries are almost all zero, like [1, 0, 0, 0, 0, 0, 3, 0, 0, 0]. Storing all those zeros in a list wastes memory, so programmers often use dictionaries instead to keep track of just the nonzero entries. For example, the vector shown earlier would be represented as {0:1, 6:3}, b...
e13d3e962f94204a2b6578722cfc279dd4089b2b
Donal-lynch/CMPU4060
/lab6.py
2,613
3.84375
4
# Exercise 1: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def counter(num): for i in range(1, num+1): print (i, end = ' ') print() counter(5) print('*--------------------*') # Exercise 2: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def even_checker(num): # Outp...
d325e095fe2042d2a26e6f152674f0489c71d1b8
SRIVARSHINEE/Guvi-task
/loopuntil.py
113
3.71875
4
a=input("please enter the name"); q=quit; if(a==q): print("quit"); else: print("please enter the name");
b2f3d16d1df7b4a01d950fae9d6962eb39bd4683
swapnil96/Data-Structures-and-Algorithms
/Maths/fibonacci_efficient.py
282
3.828125
4
past_fib = {} def fibonacci(n): '''Using recursion but storing value each time''' if n in past_fib: return past_fib[n] if n == 0 or n == 1: past_fib[n] = 1 return 1 total = fibonacci(n-1) + fibonacci(n - 2) past_fib[n] = total return total print fibonacci(999)
d3a7c66f84a07d16eddeb27604751172147c8997
aschmied/advent-of-code-2016
/day03/main.py
1,121
4
4
def main(): with open('input') as f: matrix = parse_input(f.read()) print count_triangles_in_horizontal_triples(matrix) print count_triangles_in_horizontal_triples(transpose(matrix)) def transpose(matrix): to_l = lambda t: list(t) return map(to_l, zip(*matrix)) def parse_input(input): out = [] for l...
b023bff4ca58a1bb9dd3abaafd236635bed4ab07
ilshadrin/lesson3
/date.py
522
3.875
4
''' Напечатайте в консоль даты: вчера, сегодня, месяц назад Превратите строку "01/01/17 12:10:03.234567" в объект datetime ''' from datetime import datetime, timedelta dt_now = datetime.now() print('today ',dt_now) delta = timedelta(days=1) print('yesterday ',dt_now-delta) delta2 = timedelta(days=30) print('mo...
e3737f53f5170387fc2ea3743fccfb6cf3ecf6f5
murilosleite/PycharmProjects
/pythonExercicios/ex013.py
205
3.6875
4
salario = float(input('Qual o salário do funcionário? ')) novosal = salario * (1 + 0.15) print('O Funcionário que ganhava R${}, com um aumento de 15%, passa a receber R${:.2f}'.format(salario, novosal))
e02c89231e0de77787cda6b2a37c87268bafda46
DatBiscuit/Projects_and_ChallengeProblems
/Projects/Roll_A_Dice/dice.py
802
3.5
4
import random import time def six_sided(): min = 1 max = 6 print("Rolling dice...") time.sleep(2) return random.randint(min,max) def four_sided(): min = 1 max = 4 print("Rolling dice...") time.sleep(2) return random.randint(min,max) def eight_sided(): min = 1 max = 8 ...
c432106c59437e3007183c69cd75e2684986fff6
junnnnn06/python
/06.単位変換.py
643
4
4
''' 単位変換プログラム  ''' def print_menu(): print('1.kmをmilesへ') print('2.milesをkmへ') def km_miles(): km = float(input('Kmを入力してください')) miles = km / 1.609 print('kmをmileに直すと...{0}になります'.format(miles)) def miles_km(): miles = float(input('マイルを入力してください')) km = miles * 1.609 print('mileをkmに直すと.....
52a320e22597a98261153957417137f2ecc4ac19
MussabTanveer/Python-Programming
/10-FilesAndExceptions/remember_me.py
1,417
4.21875
4
# Refactoring # improve the code by breaking it up into a series of functions is called refactoring # makes your code cleaner, easier to understand, and easier to extend import json """ def greet_user(): filename = "username.json" try: with open(filename) as f_obj: username = json.loa...
829bcd737d0ec6a2d55419bb09435d2b4ca76b23
inno-v/regexpgen
/src/regexpgen/__init__.py
12,328
4.1875
4
# -*- coding: utf-8 -*- ''' Set of functions to generate regular expressions from a pattern similar to printf function. ''' import builder import re def integer(frmt, minV = None, maxV = None): """ Generating regular expression for integer numbers (-2, -1, 0, 1, 2, 3...). :param frmt: format similar to ...
c804fd55ff64c867b0347babd94b307c5333dcfd
DSouzaM/java-nullness
/dacapo/analysis.py
3,620
3.609375
4
import csv import sys from collections import Counter def read_csv(filename: str): with open(filename, "r") as f: return list(csv.DictReader(f)) def print_stats(filename: str): rows = read_csv(filename) # Total events # events = Counter() # total = 0 # for row in rows: # count...
7c7763dff0b481bd8c20ed2877b1fcb54c7f384a
gabrielrps/MIT-6.00.1x
/Final Test/is_list_permutation.py
976
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 21 22:00:43 2020 @author: gabri """ L1 = [1, 'b', 1, 'c', 'c', 1] L2 = ['c', 1, 'b', 1, 1, 'c'] def isPermutation(list1,list2): if len(list1) != len(list2): return False; #two list does not have same length so impossible being permutation of e...
8694a6b72f0480ddf5fcf503f6293b7f54aea2ef
pBouillon/codesignal
/arcade/intro/3_Exploring_the_Waters/alternatingSums.py
926
3.96875
4
""" Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on. You are given an array of positive integers - the weights of the people. Return an array of two integ...
e0b94be27aa3950952fa34539b28a1e1f19ce998
RosemaryDavy/Python-Code-Samples
/Chapter2.py
2,033
4.21875
4
#Rosemary Davy import time import intro import Chapter1 def ch2choice1(): print("Your train has arrived at Union Station.") time.sleep(1) print("There are people asking for donations.") time.sleep(2) ch2choice1 = input("Will you give them money? Press 1 for yes or 2 for no.") ch2choice1 == " "...