blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
35efedd7c042fae42156fe88503c8d35aff1357f
RodionLe/homework
/5/5.10.py
125
3.671875
4
x = int(input("Введите курс доллара: ")) for i in range(1,21): print(str(i)+"$ =", str(i * x) + "р.")
a0f4b3fb4f1b56f21cb3c03d4e4536919d05ceb6
bkalcho/python-crash-course
/sum_million.py
418
3.765625
4
# Author: Bojan G. Kalicanin # Date: 28-Sep-2016 # Sum first million of numbers. Also determine min and max of the list of the # first million numbers, to make sure that list begins with one and ends # with one million numbers = list(range(1, 1000001)) print("Minimum element of the list is: " + str(min(numbers))) pri...
0edbf83fbee4fe16e45cd0e6555f6b8fce45c25f
EndriwMichel/estudoPython
/PythonDsa/cap14/web_to_pandas.py
572
3.59375
4
# Convertendo páginas web para pandas import pandas as pd import requests from bs4 import BeautifulSoup from tabulate import tabulate res = requests.get('http://www.nationmaster.com/country-info/stats/Media/Internet-users') soup = BeautifulSoup(res.content, 'lxml') table = soup.find_all('table')[0] # Convertendo pa...
d35bdeed9138c9643ad21e44717eb995dadde5a2
oprk/project-euler
/p048_self_powers/self_powers.py
341
3.53125
4
# Self powers # Problem 48 # The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. # Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. import time t0 = time.time() result = str(sum(i**i for i in xrange(1000 + 1)))[-10:] t1 = time.time() print(result) print('time %f' % (t1 - t0)) # 911084...
d39aaaf9e99039598d6ac89587d699f9edb0b72e
xuguoliang1995/leetCodePython
/python_know/normal/demo9_9.py
620
4.375
4
# 布尔测试__bool__ __len__ """ python3首次尝试__bool__来获取一个直接的布尔值,没有的话再使用__len__类 根据对象的长度确定一个真值, """ class Truth: def __bool__(self): return True def __len__(self): return 0 X = Truth() if X: print("yes") # 对象的析构函数 __del__ """ 每当实例空间回收的时候(垃圾收集时),析构函数就会自动执行。 """ class Life: def __init__(self, name="ukown...
968be3dc66f378c644314b9648b7ea6c1bd81ab4
Rex-Arnab/compititive-challenges
/CodeWars/ip-validation.py
1,204
3.546875
4
# Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between 0 and 255, inclusive. # Input to the function is guaranteed to be a single string. #! Examples #* Valid inputs: #* 1.2.3.4 #* 123.45.67.89 #* Invalid...
9ac87d1079a2ee219424ef640ca506fae2e1239f
RomanEngeler1805/Data-Structures-Algorithms
/V5-Sorting/HeapSort.py
738
3.78125
4
import numpy as np from copy import deepcopy def SiftDown(arr, i, m): while 2*i < m: # XXX j = 2*i if j< m and arr[j] < arr[j+1]: j+= 1 if arr[i] < arr[j]: temp = arr[i] arr[i] = arr[j] arr[j] = temp i = j else: i = m return arr def HeapSort(arr, n): for i in range(int(n/2)-1, 0, -1): ...
ccb3b388bb011dbf0566444921536fe16f6ca30a
Iftakharpy/Data-Structures-Algorithms
/section 14 implementaion_of_Breath_First_Search(BFS).py
1,243
3.75
4
def breath_first_search(binary_tree,vertex): visited_vertex = [] #list to keep track of visited vertesies queue = [] #queue to keep track of all the sub trees/child nodes of the tree. queue.append(binary_tree) while queue: #adding sub tree to the queue binary_tree = queue.pop(0) ...
e9558534c29d55bdbdde56196c87fa5cec796003
schiob/TestingSistemas
/ago-dic-2018/Ernesto Vela/Practica1/contar.py
779
3.609375
4
pos = 0 neg = 0 par = 0 imp = 0 list = [] import sys tot = int(input('¿Con cuántos números vamos a trabajar? ')) num = input('Escribe los números separados por un espacio: ') list=[int(tot) for tot in num.split(" ")] for i in range(0,tot): n = list[i] if len(list) > tot: print('Escribiste números de ma...
2f2fe636142d1859b49195d440d60e6641a45bc9
inwk6312fall2018/programmingtask2-hanishreddy999
/crime.py
685
3.515625
4
from tabulate import tabulate #to print the output in table format def crime_list(a): #function definition file=open(a,"r") #open csv file in read mode c1=dict() c2=dict() lst1=[] lst2=[] for line in file: line.strip() for lines in line.split(','): lst1.append(lines[-1]) lst2.append(l...
f0fa4676e033a5fabb1d4ae89dbdeeeb72b83a8a
MarcosBan/IMPACTA-PROGRAMACAO
/Atividade-Aula-25-03.py
389
3.65625
4
def exibe_status(n_aluno, f_aluno): if n_aluno >= 5.0 and f_aluno <= 25: if n_aluno >= 7.0: print('Aluno aprovado!') else: print('Aluno em recuperação!') else: print('Aluno reprovado!') return nota = float(input('Insira a sua nota: ')) presenca = int(input('I...
866fb7e08a7651867e885d7db4be1b2d48789c3a
mayank888k/Python
/Multilevel_Inheritence.py
593
3.84375
4
class Grandfather(): A=1 #In Multilevel inheritence Father can access GrandFather def __init__(self): #son can access father so {both Grandfather and father} self.gfname="Late Roopram" class Father(Grandfather): B=2 def __init__(self): ...
ab2cc4eafb8aea847f2079a66bf1e6702981853e
ottoguz/My-studies-in-Python
/ex009.py
581
4.09375
4
#MULTIPLICATION TABLE OF AN ENTIRE NUMBER n = int(input('Type a number')) mt1 = '{}x1 = {}'.format(n, n*1) mt2 = '{}x2 = {}'.format(n, n*2) mt3 = '{}x3 = {}' .format(n, n*3) mt4 = '{}x4 = {}' .format(n, n*4) mt5 = '{}x5 = {}' .format(n,n*5) mt6 = '{}x6 = {}' .format(n, n*6) mt7 = '{}x7 = {}' .format(n, n*7) mt...
ecb61affd34a60e8a0ee3f3ee68c82dae39ce417
hidrokit/hidrokit
/hidrokit/contrib/taruma/hk79.py
2,721
3.65625
4
"""manual: https://gist.github.com/taruma/05dab67fac8313a94134ac02d0398897 """ import pandas as pd import numpy as np from calendar import monthrange from hidrokit.contrib.taruma import hk43 # ref: https://www.reddit.com/r/learnpython/comments/485h1p/ from collections.abc import Sequence def _index_hourly(year, fr...
8c4f7e9914ac031acf427e6f7cc56d6352626300
Starfloat/Practice-Python-Solutions
/01-character-input.py
785
4.25
4
# https://www.practicepython.org/exercise/2014/01/29/01-character-input.html """ Exercise 1 (and Solution) Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. Extras: 1. Add on to the previous program ...
2ace15c4aec7b09fe56898f6a69a077759aa551b
phibzy/InterviewQPractice
/Solutions/MergeTwoLists/mergeTwoLists.py
2,035
4.03125
4
#!/usr/bin/python3 """ Given two sorted singly linked lists, merge them into one ordered list Return head of sorted list """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: # Two approaches: ...
de9d99d5e3e4d1ce17d9190eeb4a2c687305b9b9
Raeebikash/python_class1
/python_class/for_loop_practice30.py
338
4.0625
4
#practice for loop # ask user a number like 1235 # calculate sum of digits ---->1+2+3+4 #l#"1256"---->logic #num = "!@56", length = 4 #int (num[0])--->1 #int(num[1])---->2 #int(num[2])---->3 #(num[3])---->6 #i--->o to 3 total = 0 num = input("enter the number:") for i in range(0, len(num)): total += int(num[i]...
9c018be438320dad66c1cda5bd2c46312225402b
NUsav77/Python-Exercises
/Crash Course/Chapter 6 - Dictionaries/6.2_favorite_number.py
556
4.28125
4
'''Use a dictionary to store people's favorite numbers. Think of five names, and use them as keys in oyur dictionary. Think of a favorite number for each person, and store each as value in your dictionary. Print each person's name and their favorite number. For even more fun, poll a few friends and get some actual data...
a96c376d2eca98dab4979f1f60251bdd5f697bc8
tddontje/wordsearch
/WordSearch.py
16,805
4.09375
4
""" WordSearch - This program searches a given grid of letters for words contained in a given dictionary file. * The grid of letters will be randomly generated. * The search for words have the following constraints: * Words will be search forwards, backwards, up, down and diaganol * Words will not be tested for wr...
47fc4f4b36fcc11ea1942cf15de878673f462ca0
LONEZAD/Flappy-Bird
/src/game/game_objects/rigid_body.py
537
3.5625
4
from abc import ABC, abstractmethod from src.game.game_objects.move_able_game_object import MoveAbleGameObject class RectangleRigidBody(MoveAbleGameObject, ABC): @property @abstractmethod def size(self) -> [float, float]: """Should return the width, height""" class CircularRigidBody(MoveAbleGame...
9de1cd2891e67cd9b0fd7d2c52b6f04f8542b943
dkruchinin/problems
/projecteuler/problem26/problem26.py
620
3.796875
4
#!/usr/bin/env python3 def find_cycle(num): rems = [] div = 1 rem = 0 while True: rem = div % num if rem == 0: return 0 if rem in rems: return len(rems) - rems.index(rem) rems.append(rem) div *= 10 def main(): longest_cycle = 0 ...
aefe702bc325381855e4040ec69fc6195b2dd69d
slavo3dev/python_100_exercises
/88.py
364
3.875
4
''' Create a script that uses the attached countries_by_area.txt file as data source and prints out the top 5 most densely populated countries. ''' import pandas as pd f = pd.read_csv('88.txt') f["density"] = f["population_2013"] / f["area_sqkm"] f = f.sort_values(by='density',ascending=False ) for index, row in...
7136b1cd615f1a661b630d11c6e93c44b6c6f76d
iftrush/CLRS
/CH10/SimplifiedQueue.py
1,620
3.921875
4
# ERROR class Empty(Exception): pass class Full(Exception): pass # QUEUE class Queue: # CONSTRUCTOR def __init__(self, capacity = 100, head = -1, tail = 0): self.head = head self.tail = tail self.capacity = capacity self.Q = [None] * capacity self.size = ...
932667d5ef371b19f86103b5361f66b177926140
bsarden/461l-final-project
/backend/flask/src/application/models/UserModel.py
1,135
3.5625
4
from google.appengine.api import users from google.appengine.ext import ndb """ The UserModel serves as a the database representation for what we want a User object to be able to store. We have built this User object off of the google user login so that a user can log in with their google account. The User object will...
c7ad9302e6889a3ac917dcdc443c812eb159ad57
weverson23/ifpi-ads-algoritmos2020
/Atividade_Semana_08_e_09/uri_1175.py
320
3.875
4
def main(): vet1 = [] vet2 = [] i = 0 # entrada dos valores for i in range(20): vet1.append(int(input())) # armazena os valores de vet1 em vet2 de forma inversa vet2 = vet1[::-1] # saída for i in range(20): print('N[{}] = {}'.format(i,vet2[i])) main()
7dc6dbcaa857e311abcbaa042c80ad855a8ab073
shuvro-baset/Assignment
/assignment_4/task13.py
178
3.84375
4
dict = {'A': [1,2,3], 'b': ['1', '2'], "c": [4, 5, 6, 7]} total = 0 for value in dict: value_list = dict[value] count = len(value_list) total += count print(total)
532eea4a81fa3151ea92a0f3f00d9b0dc71bccb4
PedroSantana2/curso-python-canal-curso-em-video
/mundo-1/ex008.py
379
4.15625
4
''' Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. ''' #Recebendo valores: metros = float(input('Digite o valor em metros: ')) #Declarando variaveis centimetros = metros * 100 milimetros = metros * 1000 #Informando resultado: print('{} metros é: \n{} centímetros\n{}...
33bfb3ee57406338e323555da6474fc826c6eaee
bhishan/LinuxPasswordCracker
/linux_pwd_cracker.py
1,537
3.625
4
import crypt import sys def crack_pwd(user, pwd_dictionary, shadow_file): """Tries to authenticate a user. Returns True if the authentication succeeds, else the reason (string) is returned.""" is_user_available = False encrypted_pwd = '' with open(shadow_file, 'rb') as f: for each_line...
49ade560335982f3655e76e33a6e13c634aee710
daniel-reich/turbo-robot
/Mm8SK7DCvzissCF2s_23.py
724
4.09375
4
""" Create a function that takes a string and returns `True` if the sum of the position of every letter in the alphabet is even and `False` if the sum is odd. ### Examples is_alpha("i'am king") ➞ True # 9 + 1 + 13 + 11 + 9 + 14 + 7 = 64 (even) is_alpha("True") ➞ True # 20 + 18 + 21 + 5= 64 (e...
c75f52f2bfb1ef9d4a73618a1ee0b0e2e383b3f9
HusanYariyev/Python_darslari
/51-masala.py
537
3.578125
4
# SyntaxError # print("Hello Word" #IndentationError #for i in range(10): #print(i) #NameError #try: # ism = "Husan" # print(ims) #except NameError: # print("Xato -> NameError") #ValueError #try: # x = 1.3 # int(x) #except: # print("Xato -> ValouError" a = 0 try: ...
140f7e0ef9668b868aacb9bfec5a6ab2343e286a
ifaniwahida/1810530234-ujian-abj
/interfaces.py
673
3.5
4
ulang = "ya" while ulang == "ya": pilih = input("Input data Trunk Interface baru [yes/no]?: ") if pilih == "yes": hostname = input("Masukkan Hostname Switch: ") hostname = input("Masukkan Nama Interface: ") file = open("db-interface.txt", 'a') file.write("\n" +interface) el...
f4d7aba73990519ab1ca0b1025197965906ab5fb
julianfrancor/holbertonschool-higher_level_programming
/0x0F-python-object_relational_mapping/2-my_filter_states.py
1,442
3.5
4
#!/usr/bin/python3 """ script that takes in an argument and displays all values in the states table of hbtn_0e_0_usa where name matches the argument. """ import MySQLdb import sys def connect_to_database(): """Function that reads arguments from stdout and creates a connection to the MySQL server ...
e5fad15c2e5df03c05baecc6f55aaa64e4dd353d
BhagyashreeKarale/loop
/36outputques3.py
373
3.921875
4
#Niche diye gye code snippet ki output kya hoga? # i = 2 # while (i<num): # if (num%i == 0): # print(num, 'is not a prime number') # break # i = i + 1 # else: # print(num, 'is a prime number') #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<OUTPUT>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...
7d52c7e3a65dc9be6125b6f25ca6ae7ffe5c7127
mhee4321/python_algorithm
/programmers/Level1/getRidOfMinimumNumber.py
439
3.515625
4
# 시간초과 def solution(arr): result = [] for num in arr: if num == min(arr): continue else: result.append(num) if not result: result.append(-1) return result def solution2(arr): answer = [] minVal = min(arr) arr.remove(minVal) # arr이 빈배열이라면 ...
b43696ac3b6bb621de506916f8d6c86287ee8d1c
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/sbolsen/lesson03/mailroom.py
2,193
3.921875
4
#!/usr/bin/env python3 donors = [ ['Jesse Johnson', [150, 345]], ['Mary May', [1000, 750]], ['Spencer Samuels', [50, 200, 1100]], ['Zach Zillow', [85]], ['Tina Thompson', [76, 250, 300]] ] def donor_list(): for donor in donors: print(donor[0]) def prompt_...
0fd79481e17cdd2f3d45bbfb38c9ff6127cd4522
whugue/dsp
/math/matrix_algebra.py
1,629
4.09375
4
# Matrix Algebra ##Define Matrices as listed in exercises using NumPy import numpy A=numpy.matrix([[1,2,3],[2,7,4]]) B=numpy.matrix([[1,-1],[0,1]]) C=numpy.matrix([[5,-1],[9,1],[6,0]]) D=numpy.matrix([[3,-2,-1],[1,2,3]]) u=numpy.array([6,2,-3,5]) v=numpy.array([3,5,-1,4]) w=numpy.matrix([[1],[8],[0],[5]]) ##Part 1...
c5bb9ea670baa09b05f893b7801e0155086a03ec
davnav/crackingthecodinginterview
/chapter4/treebasics.py
1,082
4.0625
4
#Basic Tree operations will be implemented here.datetime A combination of a date and a time. class Node: def __init__(self,value): self.value = value self.left = None self.right = None def create_node(element): return Node(element) class BinaryTree: def __init__(self...
8a5ac1c92b5c4a54d6ce0ddeea7388d0f1edf84b
ShunKaiZhang/LeetCode
/delete_operation_for_two_strings.py
966
3.84375
4
# python3 # Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, # where in each step you can delete one character in either string. # Example 1: # Input: "sea", "eat" # Output: 2 # Explanation: You need one step to make "sea" to "ea" and another step to m...
39d77acc49eaab734efc9ef85fcc299de5caefb5
hossamasaad/Console-Projects
/Time Calculator/time_calculator.py
2,026
3.921875
4
def add_time(start, duration, day = None): # get Current time period and update the start string p = start[-2:] start = start[:-3] # split time start_hour, start_minute = splitTime(start) hour, minute = splitTime(duration) # if p = 'PM' add 12 if p == 'PM': start_hour += 12 ...
143534d4a9b255a6468fe029c030a3a7424bca7f
DingGuodong/LinuxBashShellScriptForOps
/functions/net/tcp/port/checkRemoteHostPortStatus.py
1,856
3.765625
4
#!/usr/bin/python # encoding: utf-8 # -*- coding: utf8 -*- import socket import sys # import os import time host = "" port = 0 timeout = 3 retry = 3 def usage(): print(""" Function: check remote host's tcp port if is open Usage: %s <host ipaddress> <tcp port> Example: python %s 127.0.0.1 22 Other...
bbfb4018d61fc3ff379e84021927c2cdff1ec316
learndevops19/pythonTraining-CalsoftInc
/training_assignments/Day_01/Nitesh_Mahajan/data_types_7.py
670
4.3125
4
#!usr/bin/env python def replace_last_value(input_list): """ This function replaces last value of tuples in a list by 100 Args: input_list Returns: output_list """ output_list = [] for tup in input_list: new_list = list(tup[:-1]) # Convert each tuple into a list leaving last eleme...
fa0c2e4b2cc6558b624b4bf4b9fd334fbe875bab
floydchenchen/leetcode
/977-squares-of-a-sorted-array.py
774
3.75
4
# 977. Squares of a Sorted Array # Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. # Example 1: # Input: [-4,-1,0,3,10] # Output: [0,1,9,16,100] # Example 2: # Input: [-7,-3,2,3,11] # Output: [4,9,9,49,121] class So...
6c9883cf8eb874e01cb03dc4ec0a566c5f6d79ec
SSJohns/klustering-using-nn
/src/kmeans.py
4,181
3.5
4
#Ben Gunning #Assignment 2 #Professor Wang import fileinput import json import ast """ *Need to take tweets as inputs into an array *Need to splice tweets into an array of words *Need to take each tweet and find Jaccard Distance to centroids; Find minimum and add to cluster *Need to recompute cluster centroids *Repea...
09ca7768a1a31dc184290ba5de95f5417759cf7d
aganpython/laopo3.5
/Test/124.py
177
3.546875
4
# -*- coding: UTF-8 -*- import pandas as pd import numpy as np data = pd.DataFrame(np.arange(99).reshape(11,9),index=list('abcdefghigk'),columns=list('ABCDEFGHI')) print(data)
4efa0d279c7ebb0fc7961be02bb0092c5d867f31
Styfjion/code
/BFS_a最短路径长度.py
1,502
3.53125
4
class Node: def __init__(self,x,y,step): self.x = x self.y = y self.step = step class BFS: dir = [[0,1],[0,-1],[1,0],[-1,0]] def bfs_operation(self,matrix,beginX,beginY,endX,endY): rows = len(matrix) cols = len(matrix[0]) matrix[beginX][beginY] = '#' ...
d801062f7f8a04cc5649cfa0a3f0d43d226bc1a9
sbollap1/pythondurga
/inputOutput1.py
106
3.6875
4
a,b = [int(i) for i in input("Enter 2 numbers separated by space: ").split(" ")] print("Sum is: ", a + b)
e184a44ce8a90f37c9ea0d74e427fb16e7551423
lilsweetcaligula/sandbox-codewars
/solutions/python/73.py
178
3.65625
4
def validate_word(word): from collections import Counter frequencies = Counter(word.lower()).values() return all(a == b for a, b in zip(frequencies, frequencies[1:]))
03f53bf4b38b87442cea6108b78bfcc5b40f507c
atozto9/algorithm
/programmers/programmers/hash-02.py
699
3.65625
4
def solution(phone_book): def _hash_sol(phone_book): answer = True hash_map = {} for p_n in phone_book: hash_map[p_n] = [1] for p_n in phone_book: c_seq = "" for c in p_n: c_seq += c if c_seq in hash_map and c_se...
ea28f3f50f2e4220cbc9df0f2bf567196405b50f
gomilinux/python-ThinkPython
/Chapter02/ThinkPythonEx2.4.1.py
186
4.21875
4
#Think Python Exercise 2.12 #Find the volume of a sphere print('What is the radius?') radius = input() VolSphere = float(4.0/3.0)*(3.14)*(pow(float(radius), 3)) print float(VolSphere)
fff4b8fe2417a836f55ad2490c2a6c3976cd7cb3
hc973591409/python_high_level
/03_闭包理解.py
933
3.828125
4
def test(num): print("%d ----test----" % num) def test_in(num_in): print("-----内函数返回-----") res = num + num_in return res print("-----外函数 返回-----") return test_in # 限定一个ret <===> ret = test_in(x(占位)) # 此处的20是给到外函数 ret = test(20) # 通过上面定义的函数访问内部函数,此处的100给到内函数 print(ret(100)) ...
1f916ef40333c091824d9f1ca134db614a168c7a
samarthjj/PreCourse_2
/Exercise_1.py
1,396
3.859375
4
# Time Complexity : O(log(n)) # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach def iterativeBinarySearch(arr, l, r, x): # for every iteration eliminating half the search space by...
2e64887d2964508ef8cfed528b1be30f2db3c5eb
fhulu84/Python_Crs
/Exercises/S01/Set01/05.py
265
3.921875
4
# Given a list of ints, return True if first and last number of a list is same def is_first_last_same(li): return li[0] == li[-1] my_list = [1,2,3,4,5,1] print(f'is the first and last number of {my_list} same?') print(f'Result is {is_first_last_same(my_list)}')
dae7c4ea3ede12352b25a7c9debecebd3c693081
JoaoPedroSoares/Atividades_lic
/MF João Pedro Soares 235678.py
402
3.59375
4
a1 = float(input('Nota A1')) a2 = float (input('Nota A2')) p1 = float(input('Nota P1')) p2 = float(input('Nota P2')) def media_final (a1,p1,a2,p2): MF = (2*a1 + 4*p1 + 3*a2 + 3*p2) / 12 if a1 >= 0 < 10 and a2 >= 0 < 10 and p1 >= 0 < 10 and p2 >= 0 < 10: print('A1:',a1,'P1:', p1) ...
5e2ff344ad364a64e8b05eb81cb76bdadf0b454c
fishleongxhh/LeetCode
/HashTable/771_JewelsAndStones.py
340
3.671875
4
# -*- coding: utf-8 -*- # Author: Xu Hanhui # 此程序用来求解LeetCode771: Jewels and Stones问题 def numJewelsInStones(J,S): jewels, cnt = set(J), 0 for item in S: if item in jewels: cnt += 1 return cnt if __name__ == "__main__": J = '' S = '' print(J, S) print(numJewelsInStones(J...
bcee42e5a97fb1b9bf9af01e48fcad7708f23c78
Daan97/Sandbox
/oddName.py
158
4.03125
4
"""Daan Felton-Busch""" name = str(input("Enter your name: ")) while name == "": print("Invalid name!") name = str(input("Enter your name: ")) print(name[0::2])
411f46f358f30e0b2e87d5c6f63964af577c5538
DayGitH/Python-Challenges
/DailyProgrammer/DP20150828C.py
1,581
3.609375
4
""" [2015-08-28] Challenge #229 [Hard] Divisible by 7 https://www.reddit.com/r/dailyprogrammer/comments/3irzsi/20150828_challenge_229_hard_divisible_by_7/ # Description Consider positive integers that are divisible by 7, and are also divisible by 7 when you reverse the digits. For instance, `259` counts, because `952...
ecfb35bfea3678bac831e0b03f7470b16a6eb797
ankurpathania/Training
/list_slicing.py
93
3.765625
4
a = [1,2,3,4,5,6,7,8,9] print("Original List: ",a) print(a[2:8:2]) print(a[::2]) print(a[::])
85b3c9c2781dff82bb29c9b0dc8317181f85831b
Skd10/Python_Projects
/eight_ball_fancy (1).py
475
3.59375
4
import random import sys while True: userQuestion = input("What is your question? enter q to quit ") response = random.randint(1, 5) if userQuestion == "q": sys.exit() if response == 1: print ("It is certain.") if response == 2: print ("Ask again later") if response...
11d05da99d5e09973a641999e7bb78a648d91903
ankitt010/File_operation
/code/ankit.py
1,657
3.96875
4
# # def print_weekdays(week_list): # # for week in week_list: # # yield week # # week_list = ['mon','tue','wed','thurs','fri','sat','sun'] # # my_num = print_weekdays(week_list) # # print(my_num) # # print(next(my_num)) # # print(next(my_num)) # # print(next(my_num)) # # print(next(my_num)) # # print(nex...
9dc7708a9525c5f3138db9de97522ca72f8aea2e
LeninCarabali/ahorcado-phyton
/juego_ahorcado.py
1,396
3.640625
4
import random, os def read(): list_palabras = [] with open("./archivos/data1.txt", "r", encoding="utf-8") as f: for line in f: list_palabras.append(line) palabra = random.choice(list_palabras) doclines = palabra.splitlines() doc_rejoined = ''.join(doclines) retur...
fd9033a81e88ed6f2e6309e5cbc82519aa8adda0
ivanromanv/manuales
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W5_Function_lista_raiz_cubica.py
775
4.5
4
# Write a function that accepts a positive integer k and returns the ascending sorted list of cube root values of all the numbers from 1 to k (including 1 and not including k). [if k is 1, your program should return an empty list] # def funcion_lista_raiz_cubica(number): import math # my_index=int(0) # contador=...
ecfff1d5fa3c08e22d9a8555dcc47c860b68b302
ZQ774747876/AID1904
/untitled/day04/file_read.py
677
3.71875
4
""" # """ # word=input("请输入单词:") # f=open('dict.txt','r') # for line in f: # tmp=line.split(' ')[0] # if tmp>word: # print("没有找到该单词") # break # elif tmp==word: # print(line) # break # else: # print("没有找到") # f=open('file','w') # # f.write("hello word\n".encode()) # # f....
285d818e39f17e10cb9f08dc58322f9cdcfe8ac8
DojoFatecSP/Dojos
/2018/20180504 - robo - python/robo.py
397
3.90625
4
#coding:utf-8 numeroDePassos = int(input("Insira o número de passos: ")) entradas=[] while(numeroDePassos>0): numeroDePassos -=1 passo = raw_input("Digite o passo: ") if(passo == "E"): entradas.append(-1) elif(passo == "D"): entradas.append(1) else: batata = entradas[int(pas...
5bd4093de17416783391a89537d540bd24c57f1b
Matteomnd/TPrecursivite
/EXERCICE4.py
143
3.65625
4
def listSum(I): if len(I)==0 : return 0 else: return I[0]+listSum(I[1:]) print(listSum([1,2,3])) print(listSum([]))
12e03abd8146db5d88ff8db1f6d500c7d6389edd
anildhaker/hackerrank
/InterviewPractice/comonString.py
387
3.9375
4
# Given two strings, determine if they share a common substring. # A substring may be as small as one character. # For example, the words "a", "and", "art" share the common substring . # The words "be" and "cat" do not share a substring. def twoStrings(s1, s2): s1 = set(s1) s2 = set(s2) result = s1.inte...
51d7fe3ac41360b983772e74e1e30490ca19700f
EUmbr/Py
/Books/Stepic/primes.py
277
3.515625
4
import itertools def primes(): i = 2 while True: var = 0 for j in range(1, i+1): if i % j == 0: var += 1 if var == 2: yield i i += 1 print(list(itertools.takewhile(lambda x: x <= 5, primes())))
f40264d213ddccd8f04d2fb3e0b2e4b30df9cf9e
KumaAlex/PP2_2021_Spring
/week3/day1/1.py
81
3.5
4
x = input().split() i = 0 while i < len(x): print(x[i], end = " ") i += 2
352c67c81decf6e79f6d2849199963babdc3cda1
wintangt/MyPortofolio
/SimplePy1.py
3,273
3.78125
4
#Soal Nomor 1 print("="*50) print("Soal Nomor Satu") try: jumlahHari = int(input('Masukkan jumlah hari :')) #Output nyatakan jumlah hari tersebut dalam #.... Tahun ... Bulan .... minggu ... hari tahun = 365 #hari bulan = 30 #hari pekan = 7 #hari sisaHari = 0 jumlahTahun = jumlahHa...
f9dd4aec5c2893d7329eb25fb3d12c1f42799176
gabee1987/codewars
/CodeWars/7kyu/find_count.py
787
3.828125
4
coll = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3] coll2 = [] #def most_frequent_item_count(collection): #counted_db = [] #duplicates = [] #counter = 0 #for item in collection: #if item not in counted_db: #counted_db.append(item) #else: #duplicates.append(item)...
900374ebfdea9eaae61bda444d6a8fb5ef1595a7
maheshwari2Anant/WhileLoop
/WhileUsage.py
413
4.1875
4
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, I didn't understand that.") continue else: #age was successfully parsed! #we're ready to exit the loop. break if age >= 18: print("You are able to vote in the Un...
7e77e92f088407f27c34760e6ff3d67533c7efb5
Blublac/univelcity
/list_class.py
1,701
4.25
4
#16-SEPT-2021 #list # a list is ordered and its changeble and can be indexed a = [0,1,5,20,1,2,0,False] a[3] = 6000 a[7]= True b = [4,1,5,"hi",False] #c = [a+b] a.extend(b) print(a) #create a new list of usernames. # Then write a program to get input from the user requesting his first name and last name # genetate...
28979fa56cfb090275654e02a0f8da0ee2947ddf
KaisChebata/Computing-in-Python-III-Data-Structures-GTx-CS1301xIII-Exercises
/Chapter 4.4 - File Input and Output/Examples/append_to_files.py
326
3.515625
4
myint1 = 12 myint2 = 23 myint3 = 34 myList = ["David", "Lucy", "Vrushali", "Ping", "Natalie", "Dana", "Addison", "Jasmine"] output_file = open('output_file.txt', 'a') for num in (myint1, myint2, myint3): output_file.write(str(num) + '\n') for name in myList: print(name, file=output_file) output_file.c...
c624d9b8e7b909ada391cf773a61008c741a83a9
abriggs914/CS2613
/Labs/lab19/test_fibonacci.py
439
3.578125
4
from fibonacci import fib, fib2, fib3 def test_fib1(): fun = fib2(1000) lst2 = [] while True: n = fun() if n!=None: lst2.append(n) else: break assert lst2 == list(fib(1000)) def test_fib2(): fun = fib2(1000) lst2 = [] while True: n = f...
181f683e1444e4ca8adcd6ae889f37148cc2b08c
gxmls/Python_NOI
/NOI2-2-03.py
820
3.65625
4
''' 描述 给出一个正整数a,要求分解成若干个正整数的乘积,即a = a1 * a2 * a3 * ... * an,并且1 < a1 <= a2 <= a3 <= ... <= an, 问这样的分解的种数有多少。注意到a = a也是一种分解。 输入 第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数a (1 < a < 32768) 输出 n行,每行输出对应一个输入。输出应是一个正整数,指明满足要求的分解的种数 样例输入 2 2 20 样例输出 1 4 ''' def factor(n,p): sum=1 for i in range(p,int...
57f77f85bc5a8128560149ee402d9178bf6e522f
tbcodes/python_how_to_find_the_sum_of_all_even_odd_numbers_from_zero_to_n
/16-Find_sum_of_even_odd_numbers.py
1,171
4.1875
4
# How to calculate the sum of all even/odd numbers from zero to 'n' # Youtube URL: https://youtu.be/xcu-1cO014Q # ********************************************************************** # Sum all even numbers from zero to 'n' total = 0 # num = 500 num = int(input("Please, enter a number: ")) even_numbers = []...
12b5a2078cd22ab2e5f5b04d72ab2b1830f3212f
jorchube/GameEngine
/game_engine/visual/rgb.py
755
3.515625
4
import random class RGB(object): def __init__(self, red, green, blue): self.__red = red self.__green = green self.__blue = blue @property def red(self): return self.__red @property def green(self): return self.__green @property def blue(self): ...
6fbaba2ccbb99d9af165bb7eede66fe97bd4f419
jasonposner/Network-Science-Project
/collaborator_writer.py
827
3.59375
4
# this code reads the "performers" data set and writes # a csv which contains only only_collaborators. import csv collaborators = [] # create a list which considers only musicians who collaborate with open('performers.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter='\n', quotechar='|') ...
a2e9029c4cdeb0e9a9094dde4a29054ba8728ed2
shach934/leetcode
/leet592.py
2,444
4.25
4
592. Fraction Addition and Subtraction Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fra...
bca006b7038539d18762b6b517375f47c47f086c
ninjaofpython/back_to_basics
/python-basics/sets.py
129
3.78125
4
my_set = {"January", "February", "March"} my_set.add("April") my_set.remove("February") for element in my_set: print(element)
60251967a4cf56c2ffee77f4790e80c253f6d173
manasa0917/python_code
/Assigments/dict1_solution.py
371
3.828125
4
mydict={5443:"Rahu",7786:"Jimmy",8762:"Manasha",6675:"Mukund",9876:"Sheshadri"} mylist=[] mylist=list(mydict.values()) print(mylist) mylist.sort() reversedict={} print(mylist) for key in mydict: val=mydict[key] reversedict[val]=key result=[] for item in mylist: tmp=[] tmp.append(item) tmp.append(rever...
cec10206c6766589c049202b6657484c08612697
ed-p-patch/Python
/Python Work/Python - 1/strings-lists.py
657
3.875
4
# E Patch words = "It's thanksgiving day. It's my birthday,too!" print words.find('day') # returns 18 print words.find('day', 19) # returns 36 print words.replace('day', 'month') # replaces day for month x = [2,54,-2,7,12,98] print min(x) # returns -2 print max(x) # returns 98 y = ["hello",2,54,-2,7,12,98,"world"] prin...
b1f05b03ff6ee3fa422af31e1cc7899b95c61df2
Aasthaengg/IBMdataset
/Python_codes/p03018/s154379157.py
201
3.578125
4
s = input() s = s.replace('BC','D') A_count = 0 ans = 0 for i in s: if i == 'A': A_count += 1 elif i == 'B' or i == 'C': A_count = 0 else: ans += A_count print(ans)
9ce3bb0a525057d868960b24bfeda7deca5e17c9
RutujaWanjari/Python_Basics
/python_strings.py
681
3.828125
4
# 01234567890123456789012345 # 65432109876543210987654321 alphabet = "abcdefghijklmnopqrstuvwxyz" # alphabet = "" print('reverse - ', alphabet[::-1]) # Perfect idiom to reverse string print('slices - ', alphabet[0:25:2]) print('reverse slices - ', alphabet[26:0:-2]) print('qpo - ', alphabet[16...
76d7e093f32c31794629abd9813467ef75dda821
noob643/Truss-Solver
/solver.py
8,288
3.5
4
# Write your code here :-) import math import numpy as np import copy class Support: supportCount=0 def __init__(self, point, sup_type): self.point=point self.sup_type=sup_type def sup_cols_rows(self): if self.sup_type=='PIN': return[self.point*2-1, self.point*2] ...
f458a0fcb0704e3c49989ed03daa329c07a1f5cd
kaushiknishant/problem-solving
/sort_colors.py
741
3.875
4
# dutch flag algo class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ low = 0 mid = 0 high = len(nums)-1 while mid<=high: if nums[mid] == 0: ...
f126eaf36048533826f940ea3c01057a08f12192
cgmorton/the-game
/players.py
7,119
4
4
import itertools import logging import random def random_player(hand, pile_dict, min_cards=2, max_cards=6): """Randomly play a card on a pile Args: hand (list): pile_dict (dict): min_cards (int): max_cards (int): Return boolean: return True if there is a valid mov...
fd27b3e000ffc08436cfd1c9d1133103157faee6
YiseBoge/CompetitiveProgramming2
/Weeks/Week3/bt_for_preorder_traversal.py
842
3.5
4
from Types.__tree_node__ import TreeNode class Solution: def flipMatchVoyage(self, root: TreeNode, voyage: list) -> list: index, impossible = 0, False result = [] def traverse(node): nonlocal voyage, index, result, impossible if index >= len(voyage) or node.val != ...
0e47942e08a5ef8ffb74a28806a741fb92695dcc
Angelofmystra/dnd-tools-py
/dice2.py
706
3.609375
4
import random def d6(sides, faces): n = 0 for i in range(sides): n += random.randint(1, faces) return n def room(): n = d6(1,6) m = d6(1,6) if n==1 or n == 2: print ("monster in room") if m == 1 or m == 2 or m == 3: print ("treasure present") else: print ("empty") if m == 1: print ("treasure p...
f56b6df37cfc7978e8c8b6dc7dfeb9e95ad352c9
aadhi24/python-snake-game-
/score.py
655
3.65625
4
from turtle import Turtle class Score(Turtle): def __init__(self): super().__init__() self.scores = 0 self.hideturtle() self.color("white") self.penup() self.goto(0, 250) self.times = 0.2 self.write(f"score {self.scores}", align="center",...
74eaf70857725b5385572553acadacfa15dbab32
NeonMiami271/Work_JINR
/Python/treug.py
511
3.96875
4
# Треугольник тип import sys a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) if (a + b < c) or (a + c < b) or (c+ b < a): print("Такого треугольника не сущствует") sys.exit(0) if (a == b == c): print("Треугольник равносторонний") elif (a != b) and (a != c) and (c != b): print("Тр...
e3e3542c4e3bb1cd99535e195b4ac6c8b473098c
wrideveloper/gitting-started-2020
/src/EM2CIQ2/rangoli.py
393
3.71875
4
""" Rangoli https://en.wikipedia.org/wiki/Rangoli """ import string def print_rangoli(size): strings = string.ascii_lowercase[0:size] for i in range(size-1, -size, -1): x = abs(i) if x >= 0: line = strings[size:x:-1]+strings[x:size] print ("--"*x+ '-'.join(line)+"--"*x...
6d68c99149ba7656c6fc2595693cfd475d1a1e00
Amanjot25/M03
/division-exacta.py
438
3.984375
4
#Coding: utf-8 dividendo = int(input("Escribe el dividendo: ")) divisor = int(input("Escribe el divisor: ")) if divisor == 0: print("No puedes dividir por 0") else: cociente= dividendo // divisor resto= dividendo % divisor if dividendo % divisor == 0: print("La división es exacta. cociente:" ,c...
fcf2ba2bbcd1b20e6bda3141eb05c7e6bb042cff
peter-wangxu/python_play
/test/metatest/meta_derive.py
519
3.625
4
import abc import six @six.add_metaclass(abc.ABCMeta) class ClassBase(object): @abc.abstractmethod def fun_a(self): """This function must be implemented by subclass""" pass def fun_b(self): pass def fun_d(self): pass class ClassDerive(ClassBase): def fun_c(self...
02c2af5a6daf918c0e78d20787180f04a4d8ff10
Luolingwei/LeetCode
/Stack/Q921_Minimum Add to Make Parentheses Valid.py
518
3.671875
4
# Input: "(((" # Output: 3 # 思路: left和right分别表示没有配对的左括号和右括号的个数. class Solution: def minAddToMakeValid(self, S): left=right=0 for char in S: if char==')': if not left:right+=1 else: left-=1 else: left+=1 return left+rig...
141b6d72a3890b96f51838d1b4806763f0c60684
sivaneshl/python_ps
/tuple.py
801
4.25
4
t = ('Norway', 4.953, 4) # similar to list, but use ( ) print(t[1]) # access the elements of a tuple using [] print(len(t)) # length of a tuple for item in t: # items in a tuple can be accessed using a for print(item) print(t + (747, 'Bench')) # can be concatenated using + operator print(t) # imm...
1d1491e2301ef344d82253c593dc849e93440ea6
rishinkaku/advanced_python
/decorators/decorators_p2.py
572
4.0625
4
# Make a Sandwich with the help of decorators def bread(func): def wrapper(): print("|---bread---|") func() print("|---bread---|") return wrapper def ingredients(func): def wrapper(): print('|~~tomates~~|') func() print('|~~~salad~~~|') return wrapper ...
f3824023d3b4d2132dbdd4ea2bdd357e865d90f2
Owaisaaa/Python_Basics
/test_script.py
356
3.875
4
# Read n and the scores from STDIN n = int(input()) scores = list(map(int, input().split())) # Sort the scores in descending order scores.sort(reverse=True) # Find the second highest score runner_up = -1 for score in scores: if score < scores[0]: runner_up = score #print(runner_up) break ...
7c09ebcce46b1a9fdf7f8d2cf02561043ebc103c
connorlunsford/text-based-adventure-game
/create_bottom_floor.py
52,095
3.546875
4
import system import room import object import feature import person # DESC # This python file will use everything from the system to generate the json files for the game # simply instantiate the rooms and interactables you want to create, then add them to the system # the system will then call a command to save the b...
308c51376ab2720cbad7b0392829d99ba787b2af
GuilhermeSilvaCarpi/exercicios-programacao
/treinamento progrmação/Python/cursoemvideo/exercicios/ex036.py
500
3.734375
4
#aula 12 #inputs vCasa = float(input('valor de casa pra comprar: ')) vSalario = float(input('salário de um hipotético comprador: ')) quantosAnos = int(input('anos de financiamento da casa: ')) #calculo prestação prestacao = vCasa / (quantosAnos * 12) print('para pagar uma casa de R${:.2f} em {} anos a prestação da c...
a7998e1dc29363b6cd19ced788534097a6eb44ee
sunquan9301/pythonLearn
/day8/Student.py
428
3.71875
4
class stu: def __init__(self, name, age): self.name = name self.__age = age def study(self, subject): print('I am studying class %s' % subject) # 访问器 - getter方法 @property def age(self): return self.__age @age.setter def age(self, age): self.__age = a...