blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f17ac5f966dc4f91e33b46a53507299affb01298
shehryarbajwa/Algorithms--Datastructures
/algoexpert/medium/reverse_string.py
185
4.09375
4
def reverse_string(string): reverse = '' i = len(string) - 1 while i >= 0: reverse += string[i] i -= 1 return reverse print(reverse_string('Shehryar'))
7a3bd200872e2b6071ae9fbf8eb25806aeca3ea5
dalq/python-cookbook
/cookbook/two/16FormatByColum.py
497
3.9375
4
# 以固定的列数重新格式化文本 - textwrap import textwrap s = "Look into my eyes, look into my eyes, the eyes, the eyes, " \ "the eyes, not around the eyes, don't look around the " \ "eyes, look into my eyes, you're under. " print(textwrap.fill(s, 70)) print("====================>") print(textwrap.fill(s, 40)) print("=======...
27268750ca772d65fb3fac7b432d3e8d137dec65
AnonymerNiklasistanonym/SubstitutePlanNotifierAEG
/data/html_email_to_html_json.py
4,940
3.734375
4
''' With this script you can convert an html email in the file email.html in the same directory to an JSON file which is also editable and nice to read for the main script.py ''' import json # load all the lines from the html email with open("email.html") as file: content = file.readlines() # create empty walkin...
cccf441073df6032fa982b1b017ecc95bf516fcf
programmer-666/Python
/Python/KumelerVeDondurulmuskumeler.py
2,620
3.765625
4
#Kume olusturma kume = set(["Deneme","1",2,"3"]) print(kume) #liste,demet,string,sozluk ve char tiplerinden kume olsuturulabilir fakat int lar olusmaz kume2 = {1,2,3,4,5,6,7,8,9}#diger bir kume atama yolu print(kume2) #kumelerde iki ayni veri depolanmaz k3 = {"1",2,3,"1"} print(k3) #Kumelerin uretecleri impor...
e4035f3a42790b13172adb22cc54dc6275f5dc97
Dragonriser/python_workshop
/simulations/coins.py
238
3.640625
4
import random as r def heads_or_tails(): if r.random() < 0.5: return "H" else: return "T" def run (n): output = "" for k in range(0,n): output = output + heads_or_tails() return output print run(20)
5e5607391e1d5e0b22f1100dac47b50693be2cc8
niwza/dowson_python
/guess_the_word.py
2,737
4.0625
4
#! python3 import random WORDLIST = ['advice', 'anger', 'answer', 'apple', 'arithmetic', 'badge', 'basket', 'basketball', 'battle', 'beast', 'beetle', 'beggar', 'brain', ...
47f3c936757c0e64724635b07201641da92346fe
appdutao/python
/python/com/dutao/spider/multi_thread.py
953
3.609375
4
''' Created on 2015-12-18 @author: dutao ''' from time import ctime,sleep import threading def music(music_name): for i in range(2): print("I was listening to %s. %s" % (music_name,ctime())) sleep(1) def move(movie_name): for i in range(2): print("I was at the %s! %s" %...
21bb9d8c68f8ff999750df895b9011ed87202a10
ziyeZzz/python
/LeetCode/241_为运算表达式设计优先级.py
1,226
4.0625
4
''' 给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。 示例 1: 输入: "2*3-4*5" 输出: [-34, -14, -10, -10, 10] 解释: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 ''' def diffWaysToCompute(input): opt = {'+':lambda x,y:x+y, '-':lambda x,y:x-...
1238d751a6ef86a7ac75b57a944ec625aee62b2b
hanlei0377/RF-CNS
/cns/example_qkp.py
1,242
3.71875
4
# An example for quadratic knapsack problems #### Authors: Lei Han, Handing Wang #### Xidian University, China. #### EMAIL: lhan_1@stu.xidian.edu.cn, hdwang@xidian.edu.cn #### WEBSITE: https://sites.google.com/site/handingwanghomepage #### DATE: January 2021 # ----------------------------------------------------------...
6080cda17d2318830b825febd27bc7c3e37a7510
sebbele/Advent-of-Code-2017
/day3-1.py
2,165
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function #input function for both python2.7 and 3 def getInput(prompt=''): try: line = raw_input(prompt) except NameError: line = input(prompt) return line import pprint def generateRigh...
cd1f314360e60097c3d03a73f3ca859b62c71661
EEExphon/Basic_Codes_for_Python
/WHILE and FOR loop/FOR loop.py
456
4.03125
4
for i in range (1,20): print("count number",i) input(" ") print("ok,finishied") #---------------------------------------------- input(" press enter to start.") i=input("enter the number of times table:") j=input("enter the highest number to multiply:") i=int(i) j=int(j) for i in range (1,i+1): ...
29f0ef598f98a0b12717bbf9f062470829dbaad2
riyadhswe/Python_Javatpoint
/04 Python Literals/Boolean literals.py
159
3.75
4
x = (1 == True) y = (2 == False) z = (3 == True) a = True + 10 b = False + 10 print("x is", x) print("y is", y) print("z is", z) print("a:", a) print("b:", b)
d1046c19267ceefc9feb883bc3926bf4af17fa11
ubcbaja/eCVT
/Misc/pythonTest.py
623
3.578125
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 12 13:05:06 2019 @author: Safet """ import time from datetime import datetime import numpy as np import resources print(resources.mapVal(0, (0, 20), (3.6, 9.3))) # x = list(np.linspace(0, 10, 1001)) # #print(x) # xs = list(range(0, 200)) # #print(xs) # #for i in r...
d2b0d97a37bdac34c4d5d9150f4c031fb75e7cae
alexalvg/cursoPython
/EjsBucles.py/3.6.py
300
4.25
4
#Escribir un programa que pida al usuario un número entero #y muestre por pantalla un #triángulo rectángulo como el de más abajo, #de altura el número introducido. triangulo = int(input("¿Qué altura quieres que tenga el triángulo?: ")) for i in range (1, triangulo + 1): print("*"*i)
a9442128c493443debdbba5ddcfbba1193054576
PeterZhangxing/codewars
/find_words.py
1,579
3.546875
4
#!/usr/bin/python3.5 import os,re def findword(dir,ignore_list): if not os.path.isdir(dir): return '%s is not a valid dirname!' file_list = os.listdir(dir) re_obj = re.compile(r'\b(\w+)\b') for file in file_list: file_path = os.path.join(dir,file) # splitext可以获取路径中文件的后缀名,以'.'作为...
d09e40c9ee9f796b77b07306c60f9cbee2283b32
tylersojka/100-Days_of_code
/day-7-hangman/day-7-3/main.py
893
4.34375
4
#Step import random word_list = ["aardvark", "baboon", "camel"] chosen_word = random.choice(word_list) #Testing code print(f'Pssst, the solution is {chosen_word}.') # Create an empty List called display. (to hold "_" for each letter of word) display = [] for i in range(0,len(chosen_word)): display.append("_") ...
cefd456b1a327ba6bb5bac9df4c0f7dff872c89d
travisbstop/pyRayTracer
/pixel.py
919
3.640625
4
""" stores color information in rgb triplets. """ class Pixel: def __init__(self, r=0.0, g=0.0, b=0.0): self.r = r self.g = g self.b = b def __add__(self, other): r = self.r + other.r g = self.g + other.g b = self.b + other.b return Pixel(r...
f31ba6cdbd1e942dcc21dd7b1f7c7319e99d4a90
alexartwww/geekbrains-python
/lesson_08/05.py
2,659
3.609375
4
task = ''' Продолжить работу над первым заданием. Разработать методы, отвечающие за приём оргтехники на склад и передачу в определенное подразделение компании. Для хранения данных о наименовании и количестве единиц оргтехники, а также других данных, можно использовать любую подходящую структуру, например словарь. ''' ...
a935561050f1775260a7f7fa3da95d9ab53c718f
mitalshivam1789/python
/updating a spread sheet.py
511
3.578125
4
import openpyxl wb=openpyxl.load_workbook('produceSales.xlsx') sheet = wb.get_sheet_by_name('Sheet') PU = {'Garlic':3.07, 'Celery': 1.19, 'Lemon':1.27} condition = "y" while condition == "y": produce = input("item whose price is increased") for keys,values in PU.items(): if keys ...
ec2e893a7122be11eddb8aabc6fd4b4db2e96036
subramanyakashyap/mpl_python_assignments
/Assignment Day 2/MedianOf3.py
267
3.859375
4
def findMedian(a): a.sort() return a[1] if __name__ == "__main__": n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) n3 = int(input("Enter third number: ")) print("Median:", findMedian([n1, n2, n3]))
951fbe0d69b1f1d9b909e0c963d624f3b82dcc6a
SujayDamani/Leetcode
/hammingDistance.py
685
3.609375
4
class Solution: def hammingDistance(self, x: int, y: int) -> int: str_x = "{0:b}".format(x) str_y = "{0:b}".format(y) print(str_x, str_y) str_x = str_x[::-1] str_y = str_y[::-1] print(str_x, str_y) if len(str_x) > len(str_y): while l...
5590e70000a0f994b7995bfa9d4bfde04df811a2
ericchen12377/Leetcode-Algorithm-Python
/1stRound/Easy/766 Toeplitz Matrix/OnebyOne.py
392
3.578125
4
class Solution(object): def isToeplitzMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: bool """ return all(matrix[row+1][1:] == matrix[row][:-1] for row in range(len(matrix)-1)) #slice match one in a row and forward one in second row p= Solution() matrix = [ ...
df88fe7186920ff4c39efc72adb43b7e9a994206
z0x010/medusa
/medusacode/python_demo/decorator_tutorial/decorator_10_best_practice.py
1,685
3.921875
4
#!/usr/bin/env python # coding:utf-8 def benchmark(func): """ A decorator that prints the time a function takes to execute. """ import time def wrapper(*args, **kwargs): start = time.clock() res = func(*args, **kwargs) stop = time.clock() print '[benchmark]', func....
b962a693d19cf00d973cf1acda740f3ec2e58b60
higee/project_euler
/31-100/31-40/40.py
1,713
3.78125
4
def get_number_of_elements(group_idx): number_of_elements_in_group = 10**(group_idx)-10**(group_idx-1) length_of_each_number = group_idx return number_of_elements_in_group * length_of_each_number def get_group_idx(n): # set initial value total_number_of_elements = get_number_of_elements(1) g...
344cda60ddff27982291dc99e2f95527b24b90a6
aryathakur2008/python-training
/journey to the mysterious pyramidloopy version.py
2,019
4.0625
4
import random exitchoice = "nothing" while exitchoice != "EXIT": print("YOU ARE STUCK IN A PYRAMID,WITH A PUZZLE IN FRONT OF YOU.") print("YOU NEED TO SOLVE IT TO GO TO THE TREASURE") print("YOU HAVE TO GO THROUGH A DOOR ") print("which will you pick?") print("write answer in small letters") pla...
bc13f1d7751600275d34b3a3a6f6d7c2e556b5eb
saim-doruklu/python-exercises
/hackerrank/python-division.py
133
3.578125
4
if __name__ == '__main__': num_a = int(input()) num_b = int(input()) print(str(num_a//num_b)) print(str(num_a/num_b))
7cac18d1bbd5443ed9f80023d60073ac0adee9aa
lucken99/Qs
/manipulated_sieve.py
906
3.671875
4
prefix = [] prefix.append(0) prefix.append(0) def SieveOfEratosthenes(n): # Create a boolean array # "prime[0..n]" and initialize # all entries it as true. # A value in prime[i] will # finally be false if i is # Not a prime, else true. prime = [True for i in range(n+1)] p = 2 w...
c572aade6e3709e68eddd803ac1700db1789333a
jcorines/dna-toolkit
/DNAToolkit.py
1,394
3.515625
4
# DNA Toolkit file import collections from structures import * Nucleotides = ["A", "C", "G", "T"] DNA_ReverseComplement = {"A": "T", "T": "A", "G": "C", "C": "G"} # Check the sequence to make sure it is a DNA String def validateSeq(dna_seq): tmpseq = dna_seq.upper() for nuc in tmpseq: if nuc not in ...
2b9d56106fa73e6b8a1ac114d9d611c0bd71bcc2
BumbarG/Hex-Tournament
/hex/libs/disjoint_set.py
838
3.703125
4
class DisjoinSet: def __init__(self): self.parents = {} self.ranks = {} def find(self, a): if a not in self.parents: self.parents[a] = a self.ranks[a] = 0 return a while self.parents[a] != a: prev = a a = self.parents[...
3ab81efa8f14cab73fa00896d11e4a5a74ca2aff
grst/reportsrender
/reportsrender/index.py
1,680
3.640625
4
""" Create an index file listing all specified html files. """ from typing import List import lxml.html import re from urllib.parse import urljoin import os.path from tempfile import NamedTemporaryFile from .pandoc import run_pandoc def _get_title(html_file): """Extract the title from an HTML file""" t = lxm...
03b765114eeddb45fd7b2adfecaa920da64d2536
supsa-ak/Basic-OOP-in-Python
/OOP 3.py
436
3.703125
4
#class class BestCourse: #class name website = 'http://www.sak.com' def __init__(self, name): #method #parameter/argument self.name = name #attribute #Object python_course = BestCourse("Learn Python") learn_command_line_course = BestCourse("Learn command line") print(python_course.name) print(BestCourse...
ea04a99c63f0b1cd3ca67d987d8d903c6b2d14a5
QI1002/exampool
/Cracking_the_Coding_Interview/19-6.py
1,317
3.546875
4
def showS(num): return "" if (num == 1) else "s" def showNum999999(num): if (num > 999999): return "" if (num == 0): return showNum999(num) if (num <= 999): result = "" else: result = showNum999(num//1000) + " Thunred" + showS(num//1000) + " " ...
6063be6db33ae5afc20ba733c1c5a96c457b487e
lakshay123-ctrl/102-project
/102project.py
760
4
4
"""I dont like to to calculations of maths so i am building this calculator""" num1 = int(input("Enter first number")) num2 = int(input("Enter second number")) print("Enter 1 for add") print("Enter 2 for substract") print("Enter 3 for multiply") print("Enter 4 for divide") choose = int(input("enter the operati...
8992072c89a68e2f8a2b3da265ef732b1fd86be2
sriharshavaleti/test
/Count_no_of_integers_list.py
182
3.859375
4
from collections import Counter list = [1, 6, 201,8, 21, 10, 21, 21, 6, 2, 8, 6, 1] #input values c = Counter(list) print (c) # displayes the Counting of values in Assending order
ef834007657628558528215bd496c312bf0f95dd
armstrong019/coding_n_project
/Jiuzhang_practice/lowest_common_ancestor_bianry_tree.py
2,120
3.90625
4
""" comments: 注意这里面A和B一定存在 dfs recursion function 输入是root, A,B; 输出是结果: 如果先找到A 则为A; 先找到B则为B 没找到则为None 这里面是分置算法, 左右两边分别深搜, 找到A或者B其中一个即返回。 e.g. 如果left-result 或者right-result其中一个为A, 另外一个为B, 那么当前的root即为lca 如果left-result 或者right-result其中一个为A(或B), 另外一个为None, 那么A和B在以当前root为subtree的里面。当前的root就是lca 返回result到上一级 Definition ...
ac3fdbd6a96c9c4af72fc4ab89670f42414239de
gitter-badger/python_me
/learnthepythonhardway/ex38.py
651
3.625
4
#!/usr/bin/python #-*- coding: utf-8 -*- # File Name: ex38.py # Created Time: Wed May 11 13:45:20 2016 __author__ = 'Crayon Chaney <mmmmmcclxxvii@gmail.com>' ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that" stuff = ten_things.split(' ') more_s...
692fffeed8b8c97675f9fd64c9e0a7a571a9a943
gravmath/Projects
/Python/Astar.py
6,593
3.953125
4
##### A simple A* package ##### ##### the basic data structure is a grid_point - a dictionary with 4 keys ##### 1) 'loc' - a tuple indicating the grid location ##### 2) 'terrain' - a integer with the terrain cost ##### 3) 'cost' - total cost 'terrain' plus 'heuristic' ##### 4) 'dist' - distance f...
437cbad1f9d29580a7a82dca9fc6f9e1fd8ad40f
shotaUezono/webapp_test
/old/test.py
832
3.734375
4
import sqlite3 con=sqlite3.connect("../:memory") cur=con.cursor() create_str=""" CREATE TABLE address( id serial, postcode text, prefecture text, street text); """ #cur.execute(create_str) insert_str=""" INSERT INTO address(postcode, prefecture, street) VALUES(?, ?, ?); """ info = ('100', 'Tokyo', 'Chiyodaku') cur....
deb2a659e34949b67b123dc1b1dd758e01079628
VictorMinsky/Algorithmic-Tasks
/Codewars/5 kyu/RGB To Hex Conversion.py
627
4.03125
4
""" The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned. The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should be rounded to the closest valid value. The following are...
ce0e900d270dad5790ae8792acd560018ed085ed
vanderson-henrique/trybe-exercises
/COMPUTER-SCIENCE/BLOCO_39/39_1/conteudo/linked_list_content.py
4,520
4.0625
4
from node import Node class LinkedList: def __init__(self): self.head_value = None self.__length = 0 def __str__(self): return f"LinkedList(len={self.__length}, value={self.head_value})" def __len__(self): return self.__length def insert_first(self, value): f...
8089f0e2d9f020f39595aa71bf9fd90b047d984c
justincrapse/practice
/sudoku.py
1,900
3.515625
4
import math from collections import OrderedDict # http://www.websudoku.com/?level=1&set_id=9584958293 puzzle = [[0, 5, 0, 0, 0, 4, 0, 3, 9], [7, 4, 0, 6, 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 7], [3, 0, 5, 7, 4, 0, 8, 9, 0], [0, 9, 0, 3, 2, 1, 0, 5, 0], [0, 7, 6, 0,...
850c28528d90cdc25053201bf0560bb9c944b5a4
RubhanChakkaravarthy/CS50-Introduction-to-AI
/tictactoe/tictactoe.py
4,467
3.984375
4
""" Tic Tac Toe Player """ import math import random from copy import deepcopy import util X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(...
7ce65fac2bdc2da710d0e8b467c3972d34127e55
csj561/python
/code/exercise/001/e001.py
576
3.859375
4
#!/usr/bin/python #-*- coding:utf-8 -*- ''' **第 0001 题:**做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用**生成激活码**(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? ''' import random #print ("%08X" % random.randrange(1000000,4*10**9)) def gen200(): "产生200个不重复的激活码" ret =[] while True: num="%08X" % random.randrange(1000000,4*10**9) i...
70738345de28e31246a3a1a53e15e04bbdc6efc7
Richardbmk/PythonFundamentals
/08Listcomprehension3.py
419
3.625
4
# Activities print("---------------- My Solution 1 -------------") #numbers = range(1, 101) answer = [num for num in range(1, 101) if num%12 == 0] print(answer) print("---------------- My Solution 2 -------------") numbers = range(1, 101) answer = [num for num in numbers if num%12 == 0] print(answer) print("-------...
59dd8dc5861c55e0f3bf0abed58e709168afd5c7
ShivaMMurugan/FITA
/string_join.py
253
3.875
4
# user_string = input("enter a word: ") # data = ''.join(user_string.split(',')) # print(data) if elif else user_input > 18: should run if user_input < 18: should run elif user_input thrid case: 65 and above not eligible and or not & ! !=
1f11b19c786b3cf1a77b80a8a1198035abc1489e
Aasthaengg/IBMdataset
/Python_codes/p02939/s635777658.py
460
3.546875
4
def myAnswer(S: list) -> int: ans = [S.pop(0)] flag = False for s in S: if(flag): ans[-1] += s flag = False elif(ans[-1] == s): flag = True ans.append(s) else: ans.append(s) return len(ans)-1 if(flag==True) else len(...
278f504c1508d30fc55bb1b628c1e1c51c737367
Wakib-Rashad/Problem-Solvings
/Python/prime_factor.py
793
3.59375
4
##from math import floor ## ##def factors(n): ## result = [] ## s = 0 ## for i in range(2,n+1): # test all integers between 2 and n ## if n/float(i) == floor(n/float(i)): # is n/i an integer? ## n = n/float(i) ## s += 1 ## if s > 0: ## for k in range(s): ## res...
49d7a8ea71ce02408354e6abc32ece1c30fbfe33
suleyagmurkara/SiberGuvenlikIcinPython
/Donguler/if1.py
703
3.953125
4
# Hesap Makinesi print("Toplama = 1 \n" "Çıkarma = 2 \n" "Çarpma = 3 \n" "Bölme = 4") islem = input("İşlemi Seçiniz: ") sayi1 = int(input("Sayi 1: ")) sayi2 = int(input("Sayi 2: ")) if islem == "1": sonuc = int(sayi1) + int(sayi2) print("Sonuç: ", str(sonuc)) elif islem == "2": sonuc ...
78ef20a9e5be6b862b9a8a089af8824a45b8c764
RinkuAkash/Python-libraries-for-ML
/Pandas/17_append_new_row.py
854
3.765625
4
''' Created on 21/01/2020 @author: B Akash ''' ''' Problem statement: Write a Python program to append a new row 'k' to data frame with given values for each column. Now delete the new row and return the original DataFrame. ''' import pandas as pd import numpy as np exam_data = {'name': ['Anastasia', 'Dima', 'Kat...
43f78fa1f43e391d329c9bc97ba5057fb7fec9f3
uosoul/soul
/力扣题目/第三题无重复的最长字串.py
1,117
3.953125
4
"""给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度""" string = "pwwkew" def Shortest_str(s): li = [0] n = 0 str1 = s while n < len(str1): s = str1[n:] print(s) m = '' for i in s: if i not in m: m +=i else...
b4d5e422806b7498cffd57bf79c96304d5f3695f
Python87-com/PythonExercise
/day16_20191127_28/迭代图形管理器对象改成yield.py
1,244
4.09375
4
""" 练习:图形管理器记录多个图形 迭代图形管理器对象 """ class Graphic: pass # 图形迭代器 # class GraphicIterator: # def __init__(self, target): # self.__target = target # self.__index = 0 # # def __next__(self): # # 如果index超出范围则停止 # if self.__index > len(self.__target) - 1: ...
2a7942f6b3629aa997275d977e193c7264eb9f7c
Aro935/Retail-Project
/Lists; Types of pizzas Project.py
620
4.34375
4
toppings = ["pepperoni","pineapple","cheese","sausage","olives","anchovies","mushrooms"] prices = [2,6,1,3,2,7,2] num_pizza = len(toppings) print("We sell "+str(num_pizza)+" different kinds of pizza!") pizzas = list(zip(prices, toppings)) pizzas.sort() print(pizzas) cheapest_pizza = pizzas[0] print("Our che...
2c40dc7d9bd72004f353886c4117268a60361582
hugin-coder/python-sandbox
/number-game/main.py
713
3.609375
4
import random import const import util maxGuess = int(input("hvussu ofta vil tú gita: ")) counter = 0 secret = int(random.random() * (const.MAX_NUM + 1)) go = True while go and counter < maxGuess: number = util.input_int_between(const.MIN_NUM, const.MAX_NUM) if number < secret: print("Ov lágt!") ...
333dd51f9119f5469fde5a471195a8193fc92519
dorathoto/PythonUnivesp
/6_Bimestre/S1_DecimalToBinario.py
258
4.09375
4
numeroInteiro = int(input("Digite um número inteiro:")) numeroBinario = bin(numeroInteiro) print(f"O número na base 10 {numeroInteiro} em binário (base 2) é : {numeroBinario}") print(f'Convertendo em binário de outra forma: {numeroInteiro:b}'.format())
9fdc944d4ff2899c3cb5860d841b51e8fea24070
thuerje/01-IntroductionToPython
/src/m6_your_turtles.py
1,830
3.875
4
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Dave Fisher, Vibha Alangar, Amanda Stouder, their colleagues and Jess Thuer. """ ############################################################################### # DONE # On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name. #...
7eacac0a9b2324684d88809988bda384678c87dd
hundsdor/fourier
/src/fourier.py
1,571
3.828125
4
from math import pi, sin, cos import sys from typing import Dict from svg_processor import SvgPath, determine_points, draw_result def fourier_series(points: list, number_of_harmonics: int) -> Dict[int, complex]: """ Performs the analysis of a discrete fourier series Calculates the complex fourier serie...
d0aeef11f9bd2098e4a0de85dae794b159ca2759
Michedev/TrainingForHashCode
/Point.py
279
3.640625
4
import math class Point: def __init__(self, position : (int, int)): self.x = position[0] self.y = position[1] def distance(self, otherPoint): d = (abs(self.x - otherPoint.x)**2 + abs(self.y - otherPoint.y)**2)**(1/2) return math.ceil(d)
0db08e0dc88b62c47cb5d2ac61bf5c76d9fda45d
kaushikaraj/Python-learning
/String/count_words_through_for_loop.py
99
3.71875
4
fruit = 'banana' count = 0 for i in fruit: if i == 'a': count = count + 1 print(count)
aa9faf0cef7e630b0799a6e4d9572abdcf185425
DSJ-23/DS_Algorithms
/binary_search_ref_.py
388
3.625
4
nums = list(range(1,1001)) def search(nums, target): lower = 0 upper = len(nums)-1 mid = 0 while lower <= upper: mid = (upper + lower) //2 print(nums[mid]) if nums[mid] > target: upper = mid + 1 elif target > nums[mid]: lower = mid -1 e...
4cc9eb5a1dfa153fad2ed3bc399022f8c17d5c6d
nathangroblewski/coding-problems
/Python/get-common-nums/main.py
455
3.625
4
#!/usr/bin/env python import ast from collections import Counter from six import iteritems import sys def get_common_nums(*nums): """ returns a list of the most frequently occurring integers in a list """ count_map = Counter(nums) max_count = max(count_map.values()) return [num for num, count in ite...
ef7fbf4f1629396d1b0a1ac3ad8f6fe6ff866278
mukeshprasad/30-Day-LeetCoding-Challenge
/July-LeetCoding-Challenge/Week-1/island_perimeter.py
2,744
3.953125
4
''' # Island Perimeter # You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. # Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land ce...
536dcf21c2f909ba9e6c062277bec773265a42b9
EmmanuelTobi/PythonBasics
/loop.py
427
4.09375
4
#creating and controlling loops # prints i 10 times for i in xrange(1, 11): print (i) #using the break command to stop a loop for i in xrange(1, 11): print (i) if i == 6: break #using while to make a loop x = 10 y = 0 while(y <= x) print (y) #prints y y = y + 1 #performs additon to y by 1...
879b22ce52b470a09df4d2fa1a9b60ac390857b5
yushantsai/leetcode
/sol_alg.py
2,888
3.890625
4
import math # Determine whether an integer is a palindrome. def isPalindrome(x): y = [ch for ch in str(x)] return list(reversed(y)) == y # Return the index if the target exists. If not, return the index where it would be. def searchInsert(nums, target): return nums.index(target) if target in nums else len(filter(l...
132a631cba4956b50cab114421f211211fd7f8cb
SimmonsChen/LeetCode
/哈希表/508. 出现次数最多的子树元素和.py
2,647
3.9375
4
""" 给你一个二叉树的根结点,请你找出出现次数最多的子树元素和。一个结点的「子树元素和」定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。 你需要返回出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的子树元素和(不限顺序)。 示例 1: 输入: 5 / \ 2 -3 返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。 示例 2: 输入: 5 / \ 2 -5 返回 [2],只有 2 出现两次,-5 只出现 1 次。 """ # Definition for a binary tree node. class TreeNode(obje...
3f305ceebc5b63915ad60f4723fff0684f1bb2cb
hellojessy/CSCI-1100
/Homeworks/Homework 2/geometry and breathing.py
1,431
4.3125
4
''' Utilities to demonstrate use of functions ''' from math import pi from math import ceil ''' Function to calculate the total amount of oxygen needed during the journey to Mars. Use the equation for a sphere Volume = pi * radius **2 * 4/3 ''' def volume_sphere(radius): volumeSphere = pi * radius**3 * ...
21985d5b967cdaf0346283651caa4ee46cf62484
tainenko/Leetcode2019
/python/90.subsets-ii.py
1,129
3.609375
4
# # @lc app=leetcode id=90 lang=python # # [90] Subsets II # # https://leetcode.com/problems/subsets-ii/description/ # # algorithms # Medium (43.27%) # Total Accepted: 217.8K # Total Submissions: 502.5K # Testcase Example: '[1,2,2]' # # Given a collection of integers that might contain duplicates, nums, return # al...
4b0ba868871f35438652e4b47a86013e0bdd6520
eegkno/cursos
/Python/code/03_OO/04_Herencia.py
845
4.21875
4
# -*- coding: utf-8 -*- #Nos permite reutilizar código, agregando funcionalidades #extras a clases que ya estan definidas class Animal: def __init__(self,num_patas): self.num_patas = num_patas self.alimento = 0 def comer(self): self.alimento += 1 def hablar(self): print "...
4f1fe7309e4ece6bf3bacd6a068452516715bad4
dannymulligan/Project_Euler.net
/Prob_125/prob_125.py
1,804
3.546875
4
#!/usr/bin/python # # Project Euler.net Problem 125 # # The palindromic number 595 is interesting because it can be written # as the sum of consecutive squares: 6^(2) + 7^(2) + 8^(2) + 9^(2) + # 10^(2) + 11^(2) + 12^(2). # # There are exactly eleven palindromes below one-thousand that can be # written as consecutive ...
e87d088656fe06d2637903fd49a1a76d7ecbfc3a
SuperstarterJaeeun/Learn-Programming-Book
/두근두근_파이썬/07_Function/Labs/216_drawing_to_mouse.py
214
3.765625
4
import turtle def draw(x, y) : t.goto(x,y) t = turtle.Turtle() t.shape('turtle') t.pensize(10) s = turtle.Screen() s.onscreenclick(draw) s.onkey(t.up, "Up") s.onkey(t.down, "Down") s.listen() turtle.done()
cb73e09bcf4dfec77ab0d099d6e8e8d756856ecb
karngyan/Data-Structures-Algorithms
/Heaps/RunningMedian.py
8,691
4.09375
4
""" Given an input stream of integers, you must perform the following task for each i-th integer: 1. Add the i-th integer to a running list of integers. 2. Find the median of the updated list (i.e., for the first element through the i-th element). 3. Print the list's updated median on a new line. *) Input Format ...
d3077f266d3257e54ba28db9dae7f88b109ed5e2
mingijeon/tic-tac-toe
/tic-tac-toe.py
1,641
3.546875
4
from tkinter import * def checked(i) : global player global count button = list[i] if button["text"] != " " : return button["text"] = player button["bg"] = "yellow" if player == "X" : player = "O" button["b...
408186baf4ee51623fef656e0dba45bfe28d0a04
ColeCrase/Week-10Assignment
/Page212.py
461
3.953125
4
from turtle import Turtle def square(t, sLength): """Draws a square with the given length.""" for count in range(4): t.forward(sLength) t.left(90) def hexagon(t, hLength): """Draws a hexagon with the given length.""" for count in range(6): t.forward(hLength) t...
7a27294c3e53e6738e854442caa067b20fd2bcf7
Jatin345Anand/Python
/01-PythonBasics/06-StonePaperScissor.py
1,259
3.8125
4
import random a = ["stone","paper","scissor"] b = random.choice(a) print(b) counter = 0 while True: user_input = input("Enter your choice : ") if user_input == b: print("Match Tie") elif user_input == "stone" and b == "paper": print("CPU's",b,"beats your",user_input) ...
f0e6f7acc7c7130b36797b154e0b06514aa9fd5f
andyavu/Machine-Learning-Hw
/Assignment 2/knn.py
2,762
3.984375
4
#------------------------------------------------------------------------- # AUTHOR : Andy Vu # FILENAME : knn.py # SPECIFICATION : Calculates the error rate of KNN # FOR : CS 4210 - Assignment #2 # TIME SPENT : 02/22/2021-02/28/2021 #------------------------------------------------------...
ca8e1387297bd44355c7c518e2b6a541ff48a45b
fagan2888/original-machine-learning
/cs231n-convnets-2016/assignment-1/assignment1/cs231n/classifiers/softmax.py
2,409
3.625
4
import numpy as np def softmax(scores, idx): return np.exp(scores[idx]) / np.sum(np.exp(scores)) def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A ...
bcf1851c5207297d3b754b9b4d6c53c79c037219
haakon-e/mastersproject
/src/mastersproject/GTS/fit_plane.py
4,996
3.859375
4
""" Methods for fitting a plane to a point cloud. Public methods: plane_from_points(points: np.ndarray) -> np.ndarray: - For an arbitrary point cloud of n points in 3D space (3,n) fit a plane to these points by computing the least squares fit with respect to the best conditioned spatial direction. ...
e8f1b39b1b6ba1243fbd6ef7e49ce94716e96f4e
truonghieu0511/truongminhhieu-fundamental-c4e24
/session2/truongminhhieu.homework2/rua_2.py
298
4.03125
4
from turtle import * shape("turtle") color("blue") for i in range(3): forward(50) left(120) color("red") for i in range (4): forward(50) left(90) color("blue") for i in range(5): forward(50) left(72) color("red") for i in range(6): forward(50) left(60) mainloop()
bc36a84aa873d8567616f9b6273abc0450c3b730
yao76/Coding-Dojo-Python
/Week_3/python/fundamentals/function_basic2.py
887
3.828125
4
#1 Countdown def countdown(num): return list(range(num,-1,-1)) print(countdown(5)) #2 Print and return def printandreturn(a_list): print(a_list[0]) return a_list[1] printandreturn([1,2]) #3 First Plus Length def firstpluslength(a_list): return a_list[0] + len(a_list) print(firstpluslength([1,3,5]))...
d0c4ae179eb719026ba5e860525707912652108c
sunitakunwar/test_feb_19
/q1.py
269
3.546875
4
class SquareGeometry: def __init__(self, length): self.length = length def getArea(self): return self.length*self.length def getPerimeter(self): return 4*self.length s1 = SquareGeometry(4) print(s1.getArea()) print(s1.getPerimeter())
db78c5e137d470acd919725ee104745fbfcc96d2
danmaloney745/Python_Countdown
/coundown_dict.py
2,532
4
4
#Daniel Maloney #G00303381 #Import the time and random packages for timing how the program runs, and for randomising the anagram. import random import time start_time = time.time() #Readin from the file, populate a list with the contents of the file. with open('sorted_words.txt', 'r') as fileopen: words = [line.s...
100e301b2e5591045a3d636fb941c478a96ba47a
emildekeyser/tutoring
/fh/opl/Solutions-session5/Solutions-new/ex7_credit.py
979
4.03125
4
# See solution without functions for explanation of the code def intermediate_result(number): num_step1 = number result_step1 = 0 for i in range(0, 4): result_step1 += num_step1 % 10 num_step1 //= 100 num_step2 = number result_step2 = 0 num_step2 //= 10 for i in range(0, 4)...
aa421b38990a5ab9068f90af5667719603832461
jstrnbrg/Learning-Python
/LPTHW-1/ex3.py
288
4.0625
4
print('I will now count my chicken:') print('Hens',25+30/6) print('roosters', 100-25*3%4) print('Now I will count my eggs:') print(3+2+1-5+4%2-1/4+6) print('Is it true that 3+2<5-7?') print(3+2<5-7) print('What is 3 + 2?',3+2) print('What is 5-7?', 5-7) print("Oh that's why it's False")
01c953af872945eb22d34ddbf38e6e0033539d08
W7297911/test
/python/wangyi/领奖.py
161
3.765625
4
num = int(input("请输入一个数字(0-9):")) if not(num>=4 and num<=7): print("请到办公室领奖") #else: # print("对不起,您没有中奖")
3e38d32be24f5b773a93dee6e9c4fda58bcb4f7a
songzhenhua/leetcode
/155.最小栈+++.py
3,329
4.125
4
# coding=utf-8 """ 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) -- 将元素 x 推入栈中。 pop() -- 删除栈顶的元素。 top() -- 获取栈顶元素。 getMin() -- 检索栈中的最小元素。 示例: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. m...
2781c85bdba3f384585a83ddc3835958e9aabe21
gen0v/KI_P2_01
/BacktrackingSearch.py
4,004
3.53125
4
from Board import Board import BoardUtil import copy import timeit class BacktrackingSearch: def __init__(self): self.sol_count = 0 def complement_intersection(self, lst1, lst2): lst3 = [value for value in lst2 if value not in lst1] return lst3 # return col of un...
4ae7a2e7b4b62899fd30ed634a490563065b5045
emhoainam/bu-i-6
/buổi 6/8.py
2,261
3.984375
4
class Bank: Account_type = "Savings" location = "Guntur" def __init__(self, name, Account_Number, balance): self.name = name self.Account_Number = Account_Number self.balance = balance self.Account_type = Bank.Account_type self.location = Bank.location ...
e78279dbda747e1ea5e13d1da78c2759e05b6133
newfull5/Programmers
/3진법 뒤집기.py
732
3.671875
4
""" #2020.10.13 def convert(n, base): T = "0123456789ABCDEF" q, r = divmod(n, base) if q == 0: return T[r] else: return convert(q, base) + T[r] def solution(n): return int(convert(n, base=3)[::-1], 3) """ """ #2020.12.21 def convert(n,base): nomi, denomi = divmod(n,base...
d4d97efa53b6682a649f94ba45ad1dfe5f2d1409
valphillips/mypython
/GUI_OOP_Design/Prev_Bookstore/Bookstore_FrontEnd.py
5,483
4.03125
4
""" A program that stores this book information: Title, Author, Year, ISBN User can: View all records Search an entry Add entry Update entry Delete Close Need Labels, Entry fields, Listbox, Scrollbar, Buttons Make a drawing of what you want the screen to look like and work from that Bind method - ...
9a756e18be5c033a48b42fe9ccef5bc66439b810
mllewellynjones/Todoist-Automator
/todoist_tools/habit_tracker.py
3,610
3.640625
4
from datetime import datetime import re HABIT_RE = re.compile("\[(?P<counter>\d+)\](?P<text>.*)") class HabitTracker(): """Monitors and updates habits maintained in Todoist""" def __init__(self, api_wrapper): """Initialise the habit tracker with an API connection""" self.api_wrapper = api_wr...
ae82b921e7beb8f17bc1d4735aeeb2762d911c3c
Lesetja2010/Python-Book
/chapter11_exercises.py
8,446
3.765625
4
#! /usr/bin/env python import sys import types import string import time import operator def combo_function(num_1, num_2): """ Chapter 11. Question 2 function returns (sum, product) """ return (num_1 + num_2, num_1 * num_2) #--------------------------------------------------...
db14649542bac6f1ad18de3c8fbebd0513c5c1f6
szk0139/python_tutorial_FALL21
/mysci7.py
898
3.59375
4
# Initialize my data variable data = {'date':[], 'time':[], 'tempout':[]} #time = data['time'] # Reading the data file filename = "./data/wxobs20170821.txt" with open(filename, "r") as datafile: # read first three line (header) for _ in range(3): #print(_) datafile.readline() # Read an...
599bd8b18679bbc9283de5950a4bfc3362c34ff5
lanhyan/NoteOfCs61a
/disc/disc03/disc03.py
1,566
4.125
4
def expt_iter(base, power): """ Implements the exponent function iteratively >>> expt_iter(2, 3) 8 >>> expt_iter(4, 0) 1 """ result, count = 1, 0 while count < power: result, count = result * base, count + 1 return result def expt_rec(base, power): """ Implements the exp...
0345ea6fed17e309d1ce333be1d2dae1d0a2d3f9
YiqunPeng/leetcode_pro
/solutions/1480_running_sum_of_1d_array.py
310
3.515625
4
class Solution: def runningSum(self, nums: List[int]) -> List[int]: """Array. Running time: O(n) where n is the length of nums. """ n = len(nums) res = [0] * n res[0] = nums[0] for i in range(1, n): res[i] = res[i-1] + nums[i] return res
2180ac4ec0c1927522103ce614d379d3ac14c94d
trigodeepak/advent_of_code_2017
/day9_part2.py
454
3.5
4
with open('input.txt') as f: lines = f.readline() s = lines.strip() count = 0 res = 0 i = 0 n = len(s) gar = 0 while(i<n): if s[i] == '{': count+=1 elif s[i] == '<': gar-=1 while(s[i]!='>'): if s[i] == '!': gar-=1 i...
e4a175b269ec4bab2b1d40c11e08402d54dc85d0
GraceSu/PythonClassTest
/week4test.py
325
3.9375
4
# -*- coding: utf-8 -*- def isPrime(N): while N<=1000: num=0 j=1 while j<=N: if N%j==0: num=num+1 j=j+1 if num==2: return 1 else: return 0 N=N+1 N=2 sum=0 for N in range(2,1001): print '%d Prime:%d' %(N,isPrime(N)) x=isPrime(N) if x==1: sum=sum+N print 'The sum of the prime is %d.' ...
e752b65a81258be8037e7804f1d5ab09d067796b
JoePater/eurobot
/code/py/path.py
772
3.640625
4
import route, buoys """ Functions for following a list of points leading to a destination """ buoy_path_list = [ [Pt(0,0),Pt(0,10)], [Pt(3,0),Pt(0,3)], ] buoy_orientation_list = [ 20,40 ] """ Follow a list of points (p) True on success, False on failure """ def followPath(p,orient=None): for pt...
1eb6878418d4cb1573dbba45f296dbd280e65980
Coupechoux/adrar
/Algo/turtle/polygon.py
724
4.09375
4
from turtle import * # Triangle # forward(200) # left(120) # forward(200) # left(120) # forward(200) # Carré # forward(200) # left(90) # forward(200) # left(90) # forward(200) # left(90) # forward(200) # Pentagone # forward(200) # left(72) # forward(200) # left(72) # forward(200) # left(72) # forward(200) # left(7...
0394283b5bcf8db8c52b05bfe4e150dc3a36e7a2
km140/prime_bingo
/bingo.py
1,464
3.6875
4
#!/usr/bin/python3 # coding:utf-8 import math import random try: import Tkinter as tkinter except ImportError: import tkinter try: import tkFont as font except ImportError: from tkinter import font def eratostenes(num): # 素数かどうか判定、素数ならTrue、そうでなければFalseを返す if num == 1: return False ...
6a3ad335c081f802d69d7dced0845007f215c1cd
1615961606/-test
/备份/1804爬虫/第二周/第六天/线程的执行顺序.py
466
3.515625
4
import threading import time def do(): print('我喜欢你'+threading.current_thread().name) time.sleep(1) def dance(): print('我要洗澡'+threading.current_thread().name) time.sleep(1) threads = [] if __name__ == '__main__': for i in range(0,100): td1 = threading.Thread(target=do) threads.appen...
e1a80d3691f2bf378b7c2438d69d02a75a5a75f1
rafaelperazzo/programacao-web
/moodledata/vpl_data/399/usersdata/292/80846/submittedfiles/av1_programa1.py
246
3.875
4
# -*- coding: utf-8 -*- num=int(input()) if num==5: print("IGUAL A 5") elif num==200: print("IGUAL A 200") elif num==400: print("IGUAL A 400") elif 500<num<1000: print("ENTRE 500 E 1000") else: print("OUTRO CASO")