blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
72c689962dad9a51ba5a33f73fe7040a216bdc6f
44652499/embedded
/python/python2/py1.py
256
3.90625
4
#!/usr/bin/python2 #if True: # print ('true') # print ('true1') #else: # print('false') # print('false1') #print ('hello') #input("\n\nplease input any key:") #import sys #x='hello' #sys.stdout.write(x+'abc\n') a,b,c=1,2,"hello" print a print b print c
27c3046a265df402ede5070208be4bf0093240f0
prem0023/Python
/bubble_sort.py
337
3.90625
4
def sort(list): for i in range(len(list)-1,0,-1): for j in range(i): if list[j] > list[j+1]: #swapping a = list[j] list[j] = list[j+1] list[j+1] = a list = [22,25,9, 10, 11,29,1, 3, 5, 7, 8,42,48,52,59,66, 15,35,36,39] sort(l...
ec201d673ea1a4681921d20bbe95a7def0af04ee
albertsuwandhi/Python-for-NE
/Week4/Exceptions.py
960
3.859375
4
#!/usr/bin/env python3 my_dict = {'brand':'cisco'} ''' print("BEFORE") print(my_dict['model']) ''' try: print("BEFORE") print(my_dict['model']) print("AFTER") except KeyError: print("--- Caught Exception -----") #raise print("--After Exception--") print("-"*40) try: print(my_dict['model']) ex...
b28859e565f2f5c8c157886f7eaaa0a20d585628
sreedevik29/python-practice
/mad-libs/mad-libs.py
963
4.03125
4
from random import * def main(): name = raw_input("Write a name: ") favourite_activity = raw_input("Write what your favourite activity is: ") emotion = raw_input("Name an emotion: ") pet = raw_input("What is your favourite animal? ") second_name = raw_input("What would you name a pet: ") celebration = raw_input(...
51dacbf11f0019756f196129447330a8f0f222ba
lolaguer/Python210-W19
/students/lolaguerrero/session02/series.py
1,757
4.1875
4
## Fibonacci ## def fibonacci(n): """ Return the nth value in the fibonacci series. Fibonnacci series: 0, 1, 1, 2, 3, 5, 8, 13, ... """ if n == 0: return 0 elif n == 1: return 1 else: ans = fibonacci(n-2) + fibonacci(n-1) return ans # Testing Fibonacci series pri...
1bbba29e144b409efbb73943bcd248b3909899f7
sonyacao/Country-Classes
/processUpdates.py
4,572
3.90625
4
""" Sonya Cao COMPSCI 1026 BAUER 12/04/19 Process Updates program: uses the information from an update file to change the information of specified countries in the country catalogue """ from CountryCatalogue import CountryCatalogue from Country import Country def processUpdates(cntryFileName, updateFileName): cEx...
1547b7767ae25e5888bd5c9980896d3c1c6f8ff7
albac/python-scripts
/numbers.py
749
4.09375
4
# Test code to input a N number and return a sequence from 1 to N, and print Fizz if multiple of 3, Buzz multiple of 5 and FizzBuzz if both # Enter your code here. Read input from STDIN. Print output to STDOUT def multiple_three(i): number = int(i) if number%3 == 0: return True return False de...
804a580734e04cc26fa5e49d14b142ba988a6e12
NaiNew/yzu
/lesson05/def Demo7.py
186
3.734375
4
def add(x): return x + 1 def sub(x): return x - 1 x = 10 x = add(x) print(x) x = sub(x) print(x) def operate(func, x): return func(x) x = 10 x = operate(sub, x) print(x)
e491161a8306395b0810c0838e33f8fa902892e3
flashfinisher7/ML_Fellowship
/Week2/Dictionary/Program6.py
138
3.671875
4
dict_key = {1: 10, 2: 20, 3: 50} print("Original Dictionary=", dict_key) del dict_key[2] print("remove key from dictionary :", dict_key)
17ce24c03d0f07509f76e425bb62ace83ed08533
SDasman/Python_Learning
/DataStructuresNAlgorithms/Fibonacci_Bonanza.py
1,956
4.3125
4
# Print Fibonacci 1 1 2 3 5 8 13 import time import sys from functools import lru_cache def fibonacci_recursive(number): if number < 2: return 1 return fibonacci_recursive(number - 1) + fibonacci_recursive(number - 2) @lru_cache(maxsize=None) def fibonacci_recursive_cached(number): if number < 2: ...
914a5c4b39310cb756fe54fff1ff2b2d35b94294
ProemPhearomDev/Python-Course
/Learn Python/4.If Else IF Else ControlFlow/IF.py
343
4.25
4
# Python supports the usual logical conditions from mathematics: # Equals: a == b # Not Equals: a != b # Less than: a < b # Less than or equal to: a <= b # Greater than: a > b # Greater than or equal to: a >= b a = 40 b = 40 if a < b : print("a is less than b") elif a > b: print("a is greater than b") else...
8eae8f58478a5e374fb38ca6f8a2c51869cf8d18
justinuzoije/python-dictionary-exercises
/phonebook.py
2,184
4.0625
4
import pickle phone_book = {} userChoice = 0 def look_up_entry(): targetName = raw_input("Name: ") if targetName in phone_book: print "Found entry for %s: %s" % (targetName, phone_book[targetName]) else: print "Entry not found" def set_entry(): targetName = raw_input("Name: ") tar...
7d33deb56e172a417379dc629f35b798946e55f2
yysherlock/Problems
/jiaBook/1-7.4_backtrack_8queens_quicker.py
848
3.84375
4
n = 8 def print_sol(sol): for i in range(len(sol)): print '('+str(i)+','+str(sol[i])+')', print '' # vis list of list 3 x n vis = [] for i in range(3): vis.append([]) for j in range(2*n): vis[-1].append(0) def search(sol,row): """ use a simple data structure to quickly check whether curre...
d22ddd682c2fde1ff8e224e8bd1c1071c4bbbd5a
tub212/PythonCodeStudy
/Python_Study/LAB/LAB_1n1.py
560
3.671875
4
"""1TO1 """ ###comment def ntoone(number): """ int -> int(a lot) This function print number 1 to 1 """ if number == 0: print "1" "\n" "0" "\n" "1" elif number >= 1: for i in xrange(1, number+1): print i for j in reversed(xrange(1, number)): print j...
c9a6e34442fcb5fb72494d64b9ca27feee6bb741
RyanLongRoad/variables
/assignment_improvement_exercise_complete.py
392
4.28125
4
#john bain #variable improvement exercise #05-09-12 import math radius = int(input("please enter the radius of the circle: ")) circumference = float(2* math.pi * radius) circumference = round(circumference,2) area = float(math.pi * radius**2) area = round(area,2) print("The circumference of this circle is {0}.".fo...
49a68731cf48e435c86b03f895cef3f1baf661d2
schaul/resistance
/game.py
6,759
3.875
4
import itertools import random from player import Player class State: """Simple game state data-structure that's passed to bots to help reduce the amount of book-keeping required. Your bots can access this via the self.game member variable. This data-structure is available in all the bot API functi...
8410a08bf61470a670b3decf20cdc51dfc64138a
pastorcmentarny/denva
/src/common/loggy.py
681
3.546875
4
import logging logger = logging.getLogger('app') def log_error_count(errors): number_of_errors = len(errors) if number_of_errors >= 2: logger.error('Found {} errors. Errors: {}'.format(len(errors), str(errors))) elif number_of_errors > 0: logger.warning('Found {} error. Errors: {}'.format...
4300cd659315d825b1f0d9f9e738421784c22e24
SpyrosDellas/design-of-computer-programs
/src/WaterPouring.py
4,136
4.21875
4
import heapq import doctest def pour_problem(first_capacity: int, second_capacity: int, goal: int, start=(0, 0)) -> list: """Solve the water pour problem for two glasses. We have two glasses with specified capacities, a start state and a goal state. The goal state is specified as a volume of water that c...
68b523eb572b5c64c5bb8981aedde1aad4d2bd42
chyfnuonuo/Algorithms_Fourth_Edition_study
/Chapter1_Fundamentals/bagqueuestack/bag.py
1,101
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/19 20:45 # @Author : leo cheng # @Email : chengyoufu@163.com # @File : bag.py # @Software: PyCharm from Chapter1_Fundamentals.bagqueuestack.link_list import LinkList, Node class Bag(object): def __init__(self): self.__data_list = [] ...
7aca7aa1c69c2395e32464e05854d225c4b86cd0
simzou/robots
/Server/V2s/determineRobotMovement.py
2,026
3.859375
4
import math import operator def determineRobotMovement(startX, startY, theta, endX, endY): """ Function takes in the robot's starting position and heading and the ending location and returns the angle to turn (between -pi to pi) and the distance between the two points (i.e. the distance for the robot to tra...
2517d8a431d002c737ca79ccc86fb4b1338e5462
flogothetis/Technical-Coding-Interviews-Algorithms-LeetCode
/Must-Do-Coding-Questions-GeeksForGeeks/Arrays/trappingWater.py
956
3.796875
4
''' Trapping Rain Water Medium Accuracy: 42.45% Submissions: 100k+ Points: 4 Given an array arr[] of N non-negative integers representing height of blocks at index i as Ai where the width of each block is 1. Compute how much water can be trapped in between blocks after raining. Structure is like below: | | |_| We can ...
b6c3f60bb0568359fe2d2ff9ba14bf0412e80588
leigh90/zero-to-hero-python-Udemy
/Section13:AdvancedModules/regexe.py
3,968
4.375
4
text = "The agent's phone number is is 408-55-1234" print("phone" in text) # import regex library, then pass in the search term to re.search() # re.search takes in a number of parameters the pattern you are searching for, where to search for it and others # it returns the start and end index (span) of the search term a...
b77c745496c8f56327f19bc1c2285ff040fbab3b
smileshy777/practice
/sword/KthNode.py
607
3.640625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.list_ = [] def KthNode(self, pRoot, k): if k == 0: return None self.helper(pRoot) if k > len(self.list_): ...
06a1d60d9ca18c63ffa489fdd08bff32be6f8ff3
pBouillon/codesignal
/arcade/python/2_Lurking_in_Lists/Lists_Concatenation.py
838
4.0625
4
""" Given two lists lst1 and lst2, your task is to return a list formed by the elements of lst1 followed by the elements of lst2. Note: this is a bugfix task, which means that the function is already implemented but there is a bug in one of its lines. Your task is to find and fix it. Example For lst1 = [2, 2, 1]...
c45dc8060dfadd8022ef491348935194dfca1647
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/grnguy001/question2.py
1,820
4.15625
4
#Done By Guy Green #Dot Product, adding vectors and working out magnitude of vectors #For assignment 6 import math #Getting vector from user VectorA=input("Enter vector A:\n") VectorB=input("Enter vector B:\n") #Seperating the numbers of the vectors VectorA=VectorA.split(" ") VectorB=VectorB.split(" ") ...
ffc113f08dd28517400d9cbf6a978704e96bce7f
ViRaL95/HackerRank
/Queues/queues_using_two_stacks.py
765
3.59375
4
input_value = input() enqueue = [] dequeue = [] for index in range(0, int(input_value)): input_value = input() if (len(input_value.split(" ")) == 2): [operation, element] = input_value.split(" ") else: operation = input_value.split(" ")[0] if operation == '1': enqueue.append(elem...
2ecdce790c294b2c463871e3240f3b144e0a2437
2014mchidamb/Standalone-Algos
/Data_Structures/skip_list.py
4,274
3.734375
4
''' Simple skip list implementation; see Wikipedia for details. ''' from time import time import math import random class ListNode: # Skip list node class that has links to levels below. def __init__(self, val, num_levels=1): self.val = val self.next = None self.prev = None sel...
20a4ae7189d0541a2cb0ff510c0409250ad41e5c
xuehaushu/Project_data
/jsonsp.py
545
3.84375
4
#!/usr/bin/python3 import json #将字典类型转换成jason类型对象 data = { 'no':1, 'name':'Runoob', 'url':'http://www.runoob.com'} json_str = json.dumps(data) print("Python原数据:",repr(data)) print("JASON对象:",json_str) #将json对象转换为字典 data2 = json.loads(json_str) print("data2['name']",data2['name']) print("data2['url...
a751bd0a529fa3526908f623fd609c3d51b20524
lev2cu/python_test
/pandas/test5.py
354
3.671875
4
from pandas import Series, DataFrame import pandas as pd left = DataFrame({'k1': ['sd','we', 'er'], 'k2': ['df','iu','ew'], 'lval': [1,2,3]}) right = DataFrame({'k1':['rt','sd'], 'k2': ['iu', 'iu'], 'rval':[4,5]}) #multiple keys: pass a list of column names -> on=['key1', 'key2'], data = pd.merge(left,right,on=['k1'...
b6f323c1b563af7c9eb5ab3507b6512e7e045ba8
jermainejk/ultra-savers
/JUsers.py
1,677
3.515625
4
class JUsers(): def __init__(self, username, account, password): self.__username = username self.__account = account self.__password = password def get_username(self): return self.__username def get_account(self): return self.__account def get_password(self): ...
dc5362cbd5ffd557083452b35498d0e00b1f5727
HarshaSudhakaran/excercise
/divisible_five.py
119
3.859375
4
list=[1101,102,103,104,105,106,107,108,109,110] for i in list: if i%5==0: print(i,'is divisible by 5')
27b07b393844838fb2c5d710a337e0dae9f50f0d
c-boe/Reinforcement-learning
/4 Dynamic programming/Jacks car rental/policy_iteration.py
8,768
3.703125
4
""" Implementation of Exercise 4.7 in Chapter 4 of Sutton and Barto's "Reinforcement Learning" """ import numpy as np from jackscarrental import JacksCarRental import time import matplotlib.pyplot as plt #%% def init_val_fun(max_cars_per_loc): ''' Initialize state value function for iterative policy improv...
1b9adfa35407e8cde6022f0177b01f8c0b18b9de
williamd4112/market-oriented-multi-agent-system
/simulator/time_sys.py
1,217
3.65625
4
import numpy as np import math class TimeSystem(object): ''' A time system use hour as atomic unit. ''' PERIOD = 24 HALF_PERIOD = PERIOD / 2 PERIOD_REPRS = ['AM', 'PM'] def __init__(self, initial_hour, initial_day=0): self.current_sim_hour = initial_hour * initial_day + initial...
5bff6f695dfe6f165edb5e5ca915688bdb9725d8
7286065491/python.py
/78.py
65
3.734375
4
rs=int(input()) if (rs%13==0): print("yes") else:print("no")
3dc84c5b2ae089b9a2932a77b14ed5c9655619d3
BedaSBa6koi/Homework-16.04.2020
/task20.py
546
3.90625
4
# Функция которая высчитывает являются ли введённые числа чётными или нет. Выводится в двух разных списках def counting(): digits = list(map(int, input('Enter the numbers ').split())) # digits = int odd = [] even = [] for i in digits: if i % 2 == 0: even.append(i) else: ...
b19b5c40f851553995e1f053ae58392678a6c199
Saighi/2i013
/Othello/Joueurs/joueur_humain.py
489
3.625
4
import sys sys.path.append("../..") import game def saisieCoup(jeu): """ jeu -> coup Retourne un coup a jouer """ listc = jeu[2] n = 0 print(" Coup possible :"+str(jeu[2])+"\n") for coup in listc: print("coup "+ str(n) + " x = " + str(coup[0]) + " y = " + str(coup[1]) + "\n") n += 1 ...
003af52274e4a38856d85d618bb578da353c3594
LysanderGG/Advent-of-code-2019
/day03.py
1,280
3.65625
4
from typing import Generator, Iterable, List, Tuple def read_input(filepath) -> Generator[List[Tuple[str, int]], None, None]: with open(filepath) as f: for l in f.readlines(): yield [(x[0], int(x[1:])) for x in l.strip().split(',')] def compute_wire(coordinates: List[Tuple[str, int]]) -> Gen...
de749a5d1d617842d8cc83e743fa301c9fa3cdfe
ronaldomatias/ExerciciosPython
/20.py
459
3.9375
4
soma_pares = 0 soma_impares = 0 valor = 0 while valor <= 1000: print("Para cancelar, insira um valor acima de 1000.") valor = int(input("Digite um valor do tipo inteiro: ")) if (valor%2 == 0) and (valor < 1000): soma_pares = valor + soma_pares if (valor%2 == 1) and (valor < 1000): ...
4da3aa40c5595846c8171a4d1b8f57ce0c5c2f38
Yosha2707/data_structure_algorithm
/asigments_files/recurssion1/power_of_number.py
667
4.125
4
# Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to print the answer. # Note : For this question, you can assume that 0 raised to the power of 0 is 1 # Input format : # Two integers x and n (separated by space) # Output Format : # x^n (i.e. x raise to the power n) # Constrai...
b7d6c2e28d7f4eee9db8673b5c82191e54d1fea1
SECCON/SECCON2019_online_CTF
/crypto/coffee_break/files/encrypt.py
514
3.515625
4
import sys from Crypto.Cipher import AES import base64 def encrypt(key, text): s = '' for i in range(len(text)): s += chr((((ord(text[i]) - 0x20) + (ord(key[i % len(key)]) - 0x20)) % (0x7e - 0x20 + 1)) + 0x20) return s key1 = "SECCON" key2 = "seccon2019" text = sys.argv[1] enc1 = encrypt(key1, ...
1aee58b910fd18d8f69fe59880ce801a4c898870
AndreBuchanan92/COSC_1336_Python
/Andre_Buchanan_Lab3a.py
1,706
4.1875
4
#Part A print('Hello, cousin. I cannot understand your measurments! I created this program to help you in the US.') km = int(input('\nPlease input your kilometers: ')) miles = km / 1.6 if km < 0 : print ("Error: please re-enter a positive number.") else : print ('You have gone ', miles ,' miles') ...
75554766e10e2ebd6273f52abf5513d6987e6807
jnhasard/IIC2233-Programacion_Avanzada
/Tareas/T02/Enfermedad.py
2,589
3.53125
4
from random import randint from Listasjh import jhlist class Infeccion: def __init__(self, tipo): self.tipo = tipo if tipo == "Virus": self.contagiosidad = 1.5 self.mortalidad = 1.2 self.resistencia = 1.5 self.visibilidad = 0.5 elif tipo == "B...
fcd8722695c5ae66f5216b82eef65af10d2097b5
embatbr/whatever
/less-than-1-hour/problem2.py
289
4.03125
4
# assuming list are of the same length # not using iteration either def combine_lists(A, B): length = len(A) ret = list() for i in range(length): ret.append(A[i]) ret.append(B[i]) return ret A = ['a', 'b', 'c'] B = [1, 2, 3] print(combine_lists(A, B))
b6247c2673d9dadf3a5f99ded54be0fee7da1ab4
lixuanhong/LeetCode
/PermutationSequence.py
2,512
3.53125
4
""" The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. Given k wi...
a19952a15eb8c4de58017efdbaeafc1ba32d66a0
dinosaurz/ProjectEuler
/id035.py
1,242
3.734375
4
from time import clock BADDIG = ['0', '2', '4', '5', '6', '8'] def is_circular(num): '''Return whether the number is a circular prime''' def _rotate(num): '''Return a tuple of numbers with rotated digits''' numlist = [i for i in str(num)] rotate = [] for i, _ in enumerate(numl...
62bbc55d11172cef6812ffd809e71a2ad2d8fd80
jpike/PythonProgrammingForKids
/BasicConcepts/Functions/FunctionWithSingleParameterFromUserInput.py
296
4.34375
4
# This is the definition for our function. def PrintGreeting(name): print("Hello " + name + "!") # We can get the values we pass for parameters from anywhere. # In this case, we're getting the value for the name parameter # from the user. name = input("Enter a name: ") PrintGreeting(name)
eb0d41a5fce8ed0aed4bfa83ee50f70db169a3b8
nologon/P4E
/P4I/Chapter7/exc7.1-shout.py
350
4.5625
5
#!/usr/bin/env python #~ Exercise 7.1 Write a program to read through a file and print the contents of the #~ file (line by line) all in upper case. Executing the program will look as follows: file = 'mbox-short.txt' #~ file = raw_input('what is the filename?: ') file_opened = open(file) for line in file_opened: line...
ac073677ad57d3072260cd27c44d659e4dd37ead
Twicer/Homeworks
/Homework8-13.03/Task2.py
1,224
3.953125
4
"""Задача 2 В текстовый файл построчно записаны фамилия и имя учащихся класса и его оценка за контрольную. Вывести на экран всех учащихся, чья оценка меньше 3 баллов и посчитать средний балл по классу. """ # Создание файла + запись в него with open("students.txt","w") as f: data = ["Mark Avr 8", "Andrew Shvedov 2...
f16e37c4205d2374078774c23c82c1a00713324b
gagandeepsinghbrar/codeSignal
/easyAssignmentProblem.py
1,039
3.8125
4
def easyAssignmentProblem(skills): # special case where employee TWO does both jobs equally if skills[1][0]==skills[1][1]: # worry about how employee ONE would do if skills[0][0]>skills[0][1]: first = 1 second = 2 else: first =2 ...
15067f681da822f6a78882b6d4f64d079aef1213
chlos/exercises_in_futility
/leetcode/merge_sorted_array.py
1,723
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution_my_ugly(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. ...
b2f801b14bf2da06f11b64bc379522fda9cbb561
19sProgrammersStudy/Byeongjun
/Programmers_Lv1/Programmers_lv1_정수 제곱근 판별.py
255
3.609375
4
#레벨1.정수 제곱근 판별 #https://programmers.co.kr/learn/courses/30/lessons/12934?language=python3 import math def solution(n): x=int(math.sqrt(n)) if x**2== n: answer=(x+1)*(x+1) else : answer = -1 return answer
3c046d3b284118dbad8e115779893f373be3227b
Roagen7/phy
/src/classes/Ball.py
3,353
3.59375
4
class Ball: def __init__(self,x, y, r, m, color, FPS): self.x = x; self.y = y; self.r = r; self.m = m; #self.surface = surface self.color = color self.forces = [] self.FPS = FPS deflect = False @property def ax(self): return...
8daa95d79b09bb218418d14cb92897e5c5b8ac11
vamsigontla7/MyLearningRepo
/Python_Practice/draw_square_customize.py
504
3.734375
4
import turtle def draw_square() : window = turtle.Screen() window.bgcolor("pink") turtle.shape('turtle') turtle.color('red') turtle.speed(0) brad = turtle.Turtle() brad.forward(100) brad.right(90) brad.forward(100) brad.right(90) brad.forward(100) brad.right(90) ...
dac68410a033ef191747ed887ae29d2a0e4fd792
zanzydnd/yandex-algorithm-training
/div B/hw2/bench.py
454
3.578125
4
def popping_blocks(middle, blocks, k): i = 0 while i < k: if blocks[i] < middle < blocks[i] + 1: return blocks[i] if blocks[i] <= middle <= blocks[i + 1]: return "" + str(blocks[i]) + " " + str(blocks[i + 1]) i += 1 if __name__ == '__main__': l, k = list(ma...
cc5b5d5355b15860d97f5d38cb95180497c59116
llzxo/python_practice
/3.4.py
80
3.6875
4
a = input("input a:") b = input("input b:") sum = a + b print("a + b = %d"%sum)
34c8d073fbe1e5f9ac2f6f3a004ad5788cdd6838
hvl5451/HW4_New
/account.py
1,551
4.125
4
""" Accounts are accessible by customers and every employee. Account information can be modified only by customers and managers. Accounts can only be closed/deleted by managers. """ import datetime class Account: """ Implementation of a customer's bank account. Can hold and update a balance. Can proces...
9dcf0cabba53ab03c2ffac9d0b206ee273a1fde3
lixiang2017/leetcode
/leetcode-cn/0628.1_Maximum_Product_of_Three_Numbers.py
589
3.609375
4
''' approach: Sort Time: O(NlogN) # Space: O(N) O(logN) 执行结果: 通过 显示详情 执行用时:56 ms, 在所有 Python 提交中击败了76.51% 的用户 内存消耗:14.2 MB, 在所有 Python 提交中击败了11.11% 的用户 ''' class Solution(object): def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() ...
4788ad871ae36f41ad954990c11baa03952c223e
EruDev/Python-Practice
/菜鸟教程Python3实例/18.py
509
3.953125
4
# 斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, # 特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。 def fibo(n): if n == 0: return 0 elif n == 1: return 1 else: return fibo(n-1) + fibo(n-2) def print_fibo(scope): for i in range(scope): print('%d,' % fibo(i), end='') if __name__ == '__main__': while True: number = i...
44154f15022ab974065241f5bab6a3ac741e33cd
SuleimanMS/topshiriqlar
/masala 24.06.21/3) juft son rostlik.py
204
3.859375
4
while True : n = int(input('\nSon kiriting:\n---> ')) if n == 0 : print('Juft son emas!') elif n%2 != 0 : print('Juft son emas!') else : print('Juft son')
e9b1275ec8f5e52acb23c5c855a889a18149f0b9
mjsterckx/CS5245
/p01/p01_lorentz.py
185
4.125
4
s = float(input('Enter the velocity (m/s): ')) c = 3 * (10 ** 8) lorentz = 1 / ((1 - (s ** 2 / c ** 2)) ** (1 / 2)) print('The Lorentz factor at', str(s), 'm/s is', str(lorentz) + '.')
5052a2104f60ed8b2af5158cc7e6fc3533d5af17
bdebut01/projects
/ecosym/code/seablock.py
2,556
3.578125
4
# Seablock module # Stores the unit of location used by the simulation # which stores aspects of the ocean at the given location # and coordinates the many creatures that can be resident therein # Part of the EcoSym Project from sets import Set from helper_functions import with_lock from threading import Lock class S...
2d4c5f6a076bbb96ad01854d8245e9c900cd9f91
darkcoders321/fahim
/Learn and Practice PyThOn/chepter-7 (String)/example1.py
182
3.75
4
str1=input("Upper:") str1=str1.upper() str2=input("lower:") str2=str2.lower() str3=int(input("integer:")) str4=input("No conditon:") print(str1,str2,str3,str4)
4c9698dbd8811ae8d31c8ecd926c3d20b392ba7d
coolhass-offical/how-to-python
/Python-Indentation-and-comments.py
644
4.09375
4
# A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented line. # The amount of indentation is up to you, but it must be consistent throughout that block. if True: print('Hello') a = 5 # The enforcement of indentation in Python makes the code look neat and clean...
2b55d0c415444ccd19eb75f8054480e7ddb52f0e
hakubishin3/nlp_100_knocks_2020
/ch01/03.py
467
3.8125
4
""" 03. 円周率 “Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”という文を単語に分解し, 各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ. """ text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics." answer = [len(w) for w in text.replace(",", "").rep...
62492b76f85cbd3b8e41cbd01a82e8f8c93f22fc
bhandari-nitin/Python-Code
/Python-Codes/Graph.py
1,062
3.828125
4
################### ##### Graphs ###### ################### class Node(object): def __init__(self, value): self.value = value self.edges = [] class Edges(object): def __init__(self, value, node_from, node_to): self.value = value self.node_from = node_from self.node_to = node_to class Graph(object): def ...
1d8d7e4d21bb15a966086fbd32eeac0b3369d3b8
matheusforlan/TST-P1
/ex088.py
509
3.734375
4
#coding:utf-8 from random import randint print "----------- JOGO DA MEGA SENA ------------ " quantidade = int(raw_input("Quantos jogos serão feitos? ")) controlador = 1 jogos = [] lista = [] while controlador <= quantidade: cont = 1 lista = [] while True: numero = randint(1,61) if numero not in lista: lis...
f9ec6d7be34c9e81ffe1090e9a4f2f4fcf9e369a
phuongsover1/nenvbvagamma
/src/Spimi/compressed_spimi_vbencode.py
14,403
3.515625
4
""" This script index documents by using SPIMI indexing technique """ from nltk.corpus import stopwords from collections import defaultdict from src.Compress.VariableByteCode import VariableByteCode from bitstring import BitArray from os import listdir import sys import os import string import re def rename_file(path...
35fb92389ed08510ccf2cd0e495f147220be50c5
bssrdf/pyleet
/M/MinimumDeletionstoMakeArrayDivisible.py
1,549
3.796875
4
''' -Hard- *Sorting* *GCD* You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums. Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1. Note that an integer x d...
3c87c343db6cacabc092850d02948547d7d0bc73
DocentSzachista/messenger-stats
/src/file_parser.py
1,666
3.71875
4
import json #otworz plik JSON aby potem uzyskac slownik zawierajacy informacje o autorach i caly kontent wiadomosci class FileParser: """class to process messenger JSON files""" def __init__(self, filename) -> None: self.jsonData=self.__parse_json(filename) def __parse_json(self, filename)->dic...
94e2377769d2f1051b78358df852784f0e12d553
mitchell-johnstone/PythonWork
/PE/P074.py
1,548
3.8125
4
# The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: # 1! + 4! + 5! = 1 + 24 + 120 = 145 # Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: #...
10cca1331c624f8f0699d1494bf034c482ba921d
harshitpoddar09/InterviewBit-Solutions
/Programming/Tree Data Structure/Simple Tree Ops/Balanced Binary Tree.py
637
3.84375
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : root node of tree # @return an integer def isBalanced(self, A): def height(root): if no...
5f0b428d7047defd81f2e7b993ae87fa32bb8577
IanCBrown/practice_questions
/avg_of_levels_in_binary_tree.py
1,074
3.8125
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ ...
b6df4bc02d51444363bebce2bf1619fe051ed733
uwasejeannine/showAndTell
/ShowAndTell.py
3,124
3.609375
4
Python 3.8.6 (default, Jan 27 2021, 15:42:20) [GCC 10.2.0] on linux Type "help", "copyright", "credits" or "license()" for more information. >>> #python Valiables(INt,Float and Boolean) >>> studentNumber=2 # variable number is 2 >>> print(studentNumber) 2 >>> #Oparetors(Arthemetic) >>> x=2 >>> y=3 >>> y+x 5 >>> # Assi...
87abf83bae46e78c695bede4c830554952898c1b
S-Downes/CI-Challenges
/Stream-3/01_python_challenges/solutions/challenge_3.py
915
3.53125
4
# Function(s) def test_are_equal(actual, expected): assert expected == actual, "Expected {0}, got {1}".format(expected, actual) def test_not_equal(a, b): assert a != b, "Did not expect {0}, but got {1}".format(a, b) def test_is_in(collection, item): assert item in collection, "{0} does not contain {1}"...
d21c4ada70f67aab45dc2ae3278c5289f2a5dda8
ngalin/weather
/get_weather.py
1,442
3.546875
4
# make some api calls - and log weather hourly values in Sydney, AU # on the hour make call to get current temperature in Sydney, and # make call and record the 5 day 3hr forecast for Sydney. # after get 24 x 5 x (24/3) values, import requests import schedule import json import datetime import api_secret CITY = 'Sydn...
6a12a390f4c68aebc4a6b1163085e628037138e4
dekopossas/trybe-exercicios
/exercises/37_1/aula.py
554
3.859375
4
numeros = [1, 2, 2, 6, 6, 6, 6, 7, 10] print(len(numeros)) def numero_que_aparece_um_quarto(numeros): contador = dict() for numero in numeros: contador[numero] = contador.get(numero, 0) + 1 print(contador) numero_mais_frequente = None maior_contagem = 0 for numero, contagem in conta...
765aad363331dbf66ab32af8ac2b68a3ecccd809
aravindbhaskar41/codejam
/invariant/plaban_nayak/invariant_main.py
945
3.53125
4
from invariant_algorithm import dynamic_prog , lookup_sorted from invariant_print_table import print_table def main_method(number_list): #checking if all numbers are 4 digit numbers if max(number_list) > 9999 or min(number_list) < 1000: raise ValueError, "all numbers are not 4 digit numbers" ...
5180716bff9ac2d84e4453ecbd2121123a8c1610
tsartsaris/TSP
/tsp_distance.py
1,445
3.984375
4
# ! /usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Tsartsaris Sotiris" __copyright__ = "Copyright 2014, The TSP Project" __credits__ = ["Tsartsaris Sotiris"] __license__ = "APACHE 2.0" __version__ = "1.0.1" __maintainer__ = "Tsartsaris Sotiris" __email__ = "info@tsartsaris.gr" __status__ = "Development" ""...
3ce5eaabbb7eab6f33b5528445f62f17adf58efd
rwakulszowa/Skater_pygame
/skater/image.py
2,240
3.5
4
import random import numpy as np import pygame from .rendering.point import Point from .rendering import shape class Image: """ A wrapper around a pygame image class. It provides a common interface for drawable elements. The code outside of this class should not use any other image-related APIs. ...
43792737c78effd38b7513744d84dee366bc0e15
MeParas324/Python-programs
/pythontuts/tut16.py
868
3.765625
4
# list1=["Paras","Elsa","Murti","Ramdev"] # for item in list1: # print(item) # list1=[["Paras",2],["Elsa",4],["Murti",8],["Ramdev",16]] # for item in list1: # print(item) # list1=[["Paras",2],["Elsa",4],["Murti",8],["Ramdev",16]] # for item,lollypop in list1: # print(item,lollypop) # list1=[["Paras",2],[...
10b4970e6d20d3e513ea2c266fc604bcf69a49bc
Funsom/leetcodes
/946.验证栈序列.py
1,055
3.609375
4
# # @lc app=leetcode.cn id=946 lang=python3 # # [946] 验证栈序列 # # @lc code=start class Solution: def validateStackSequences(self, pushed, popped) -> bool: #if pushed == popped: return True # 至多有一个逆序 dic = {} n = len(popped) nin = len(pushed) if n != nin: return False ...
f166ce761de68cb484969af0477ec82a057291be
AkankshaKaple/Python_Data_Structures
/removeFirstOccurance.py
688
4.0625
4
#This program deletes the first occurrence of a perticular # element in an array from array import * UserArray = array('i' , []) #Array given by user size = int(input("Enter size of array : ")) print("Enter elements in array : ") for i in range(size) : item = int(input()) UserArray.append(item) element =int(...
4672b0fccfa4167d81d99c110a7a3352a7c9aad8
code4tots/c4
/c4/parser.py
12,843
3.625
4
"""parser.py This module has two components: 1. the Parse function, and 2. the Parser class. Parse is a convenience function around Parser. For most intents and purposes, I don't think you will need to use the Parser class directly. The Parser class is enormous, but is divided into six logical parts. -- cont...
7cff7f6452b6f56411308bb48d4626286be87936
vitaliivolodin/codewars
/pig_latin.py
243
3.921875
4
# http://www.codewars.com/kata/520b9d2ad5c005041100000f/train/python def pig_it(text): return ' '.join([x[1:] + x[0] + 'ay' if x.isalpha() else x for x in text.split()]) if __name__ == '__main__': print(pig_it('Pig latin is cool'))
f08435310c61ac0f16e352fe6a5bad34d915b784
sureshmelvinsigera/linkedlist
/reverse.py
594
4.25
4
''' Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes. Input : Head of following linked list 1->2->3->4->NULL Output : Linked list should be changed to, 4->3->2->1->NULL ''' from linkedlist import LinkedList...
c4650ed36f4500d3a4e603a85525093b4e6574ca
tapumar/Competitive-Programming
/Uri_Online_Judge/1168.py
424
3.796875
4
casos = int(input()) for i in range(casos): led=0 num = input() for j in num: if j=="1": led=led+2 elif j=="2" or j == "3" or j =="5": led = led+5 elif j=="4": led = led+4 elif j=="0" or j=="9" or j=="6": led = led+6 eli...
73887921856a87ad1df80163fd2df0094f28bcfb
Aasthaengg/IBMdataset
/Python_codes/p03633/s897890218.py
156
3.75
4
import math def lcm(a,b): return a*b//math.gcd(a,b) N=int(input()) T=[int(input()) for _ in range(N)] ans=1 for t in T: ans=lcm(ans,t) print(ans)
537213fcc15464b6c3ed67ef4fbda9247dac895d
Zhaoput1/Python
/Leetcode/highfre/66_59generateMatrix.py
682
3.75
4
# -*- coding: utf-8 -*- """ # @Time : 5/26/21 # @Author : Zhaopu Teng """ from typing import List def generateMatrix(n: int) -> List[List[int]]: res = [[0 for _ in range(n)] for _ in range(n)] count, i, j, temp = 1, 0, 0, 0 while n > 0: for i in range(temp,n): res[j][i] = count ...
24bd8bf13c09063b6a4e8e179738ea13f1799b7c
ArneVogel/aoc18
/day6/coordinates.py
2,915
3.5
4
import sys def print_grid(grid, minX, maxX, minY, maxY): for x in range(minX, maxX): for y in range(minY, maxY): if len(grid[(x,y)]) == 1: print(grid[(x,y)][0][0], end="") else: print(".", end="") print() def get_areas(lines, overlap=1): ...
e6324fde5386e368117232251a22a18d7834174f
t0futac0/ICTPRG-Python
/Assingment 1.py
1,152
4.28125
4
#a. Read the specified details from the user (First Name, Last Name, Age) # This will mean that your application must accept ANY name and age combination not just the ones from the examples. #b. Process their age depending on your Student ID #c. Generate and output a pipe (‘|’) separated email and password combo. #i. T...
fd840cb9982235178d0f64216446ebd967ad13d2
jamesmcgill/project-euler
/problem4/problem4.py
800
3.921875
4
def is_palindrome(x): number_string = str(x) num_digits = len(number_string) for i in range(num_digits // 2): if number_string[i] != number_string[-i-1]: return False return True def main() : left = 999 right = 999 max_product = 1 while True: #print("Test {...
10a68a58571ff37a2524021efa79edba49f8789c
guozhoahui/4-1
/乘法表.py
421
3.578125
4
def chengfabiao(rows): start = 1; for row in range(start, rows): str1 = "" space = " " for col in range(1, row + 1): if (row == 3 and col == 2) or (row == 4 and col == 2): space = " " else: space = " " str...
fcd99c694cf6bb7089a2e4c22918ef55651ff27f
SoundlessPython/BlackPython
/Python/new.py
109
3.765625
4
a = 5 b = 4 if a < b: print("a is smaler than b") print("I think so") print("a is not smaller than b")
4cb74dc4c39c685de462c23997c4929a9c9673b8
luzzyzhang/my-python-cookbook
/01-data-structures-and-algorithms/calculate_with_dict.py
892
3.96875
4
# -*- coding: utf-8 -*- # Perform calculations on dictionary data prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } min_price = min(zip(prices.values(), prices.keys())) max_price = max(zip(prices.values(), prices.keys())) prices_sorted = sorted(zip(prices.values(),...
a45bdaba001d089b9e4799f46ba9a1eeb03db2a2
BHill96/TXSTproblemSolvers
/shuffleProblem.py
3,608
4.0625
4
import copy import csv import time # Inserts every number between 1 and maxNumber into myList in reverse order # i.e. 5, 4, 3, 2, 1 def populateList(myList, maxNumber): for number in range(1, maxNumber + 1): myList.append(number) # Removes every other number and appends it to the bottom starting with the ...
b127984662a1786d2c7cc19966b566d4ab299b48
FaouziDakir/PythonTraining
/ex1.py
117
4.0625
4
val = input("Hey what is your name ? : ") if val != "" : print("hello " + val) else : print("Hello, World!")
b4268372bf68424aa0745f94c64f91bdce45a8a6
AbhineetD/cryptopals-challenge
/set1/challenge2.py
540
3.5625
4
#Cryptopals Challenge Set 1 Challenge 2 import codecs ''' This function gives XOR of 2 hex strings @Input: 2 Hex strings of equal length @Output: XOR output of 2 strings ''' def xor_2_strings(hex_string_1, hex_string_2): if (len(hex_string_1) == len(hex_string_2)): return hex(int(hex_string_1, 16) ^ int(hex_stri...
1fbeeed8f3135e44e3532ba046d0bbc994227d8e
marcosvnl/exerciciosPythom3
/ex082.py
804
3.8125
4
# Crie um progrma que vai ler vários números e colocar em uma lista. depois disso, crie duas listas extras # que vão conter apenas os valores pares e os valores impares digitados, respectivamente. # Ao final, mostre o conteúdo das listas geradas. principal = list() listapar = list() listaimpar = list() while True: ...
57489adbba2a55b2fdb92d46ad5c6eb046a686fb
metshein/python
/h6.4a.py
266
3.75
4
def tervitus(x): print("Võõrustaja: \"Tere!\"") print("täna "+str(x)+". kord tervitada, mõtiskleb võõrustaja.") print("Külaline: \"Tere, suur tänu kutse eest!\"") x = int(input("Sisestage külaliste arv: ")) for i in range(1,x+1): tervitus(i)
33a82f8cc608c1779d01a291a665139ff253282b
MarcosAllysson/python-basico-fundamento-da-linguagem
/prova-mundo-1.py
2,104
4.71875
5
""" Qual é o resultado calculado pelo Python para as expressões simples 19 // 2 e 19%2, respectivamente? """ primeiro_resultado = 19 // 2 segundo_resultado = 19 % 2 #print('Primeiro resultado \033[1;36m{}\033[m, segundo resultado \033[4;39m{} \033[m.'.format(primeiro_resultado, segundo_resultado)) """ Se o nosso prog...