blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
831b7f2ee30d1c3a6502c01d36fe3a4b4121b32a
Yevgen32/Python
/Games/guess the number.py
273
3.84375
4
import random rezult = random.randint(1,100) number = 0 while number != rezult: number = int(input("Number:")) if number > rezult: print("Input less") elif number < rezult: print("Input more") elif number == rezult: print("Winnnn")
9449ffba731f3e23dd5e1f588bfb8040312d13fe
justinchoys/ctc_practice
/Chapter 1/1.4_Palindrome_Perm.py
645
3.71875
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 15 15:06:36 2018 @author: justin """ #check if string is permutation of palindrom #concept: dict of palindrome has all values even, or all even except for one 1 def palinCheck(word): d = {} new_word = word.replace(" ","") for i in new_word: if i not ...
1d2ca60e8e1aa88f22525a18ba615521b83ffe9e
Akash09-ak/Python-Scripting
/texting script.py
398
3.796875
4
import keyboard import time time.sleep(2) # to give some time for interpreter to execute for i in range(10): # here we are using loop for how many time we need to run our script keyboard.write("hy \n") # write() function take the text as input keyboard.press_and_release("enter") # here ...
ba366bedf93f18b4ae06f90867cd5b44aed450c2
Drewsup123/Algorithms
/stock_prices/stock_prices.py
1,537
3.8125
4
#!/usr/bin/python import argparse def find_max_profit(prices): # min_buy = min(prices) # max_sell = max(prices) # min_buy = 10000 # max_buy = [0, 2] # index = 0 # for i in prices: # # if i > max_buy[0] and index > 0: # max_buy[0] = i # max_buy[1] = index ...
35c4be29f6527801c194ff92b7d049b6016f400a
hdcsantos/Exercicios_Python_Secao_04
/41.py
295
3.765625
4
print("Salário líquido") ht = float(input("Informe o valor da hora trabalhada R$: ")) h = float(input("Informe o numero de horas trabalhadas no mês H: ")) bruto = h * ht liquido = bruto + (bruto * 0.10) print(f"O valor de hora/trabalho X horas, com a dicional de 10% é de R$ {liquido}")
341cd0976baacba7861ece23d93edb978470a343
theakhiljha/Ultimate-Logic
/Encryption/Reverse Cipher/reverse.py
519
4.15625
4
# an implementation of the ReverseCipher # Author: @ladokp class ReverseCipher(object): def encode(self, message: str): return message[::-1] def decode(self, message: str): return self.encode(message) # Little test program for ReverseCipher class message = input("Enter message to encrypt: "...
53b4c8e1400808b78072f35cadf47b79eed3598e
stefan-toljic/MultipliedNumber
/main.py
771
4.09375
4
""" 1. Multiplied number Ask user to enter three numbers. If first number is > 10 write sum of second and third number to the console. If first number is <=10 write it directly to the console. """ def handle_input(message): while True: try: user_input = int(input(message)) break ...
b3efdc5a252e337daee389132af3ffc472b19931
aishux/March-LeetCode-Challenge
/SwappingNodesInLL.py
869
3.84375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: # record for first kth node, last kth node, and running cursor first_k, last...
6316e4fc4542d947593a23cece081552b64c15aa
anurag5398/DSA-Problems
/DynamicProgramming/UniquePathInaGrid.py
908
4.03125
4
""" Given a grid of size n * m, lets assume you are starting at (1,1) and your goal is to reach (n, m). At any instance, if you are on (x, y), you can either go to (x, y + 1) or (x + 1, y). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked...
5ab84795cf738df8b76f13d505d9f84cf07ec8f7
lihip94/countingPolyominos
/test.py
2,339
3.734375
4
import unittest from counting_polyominos import counting_poly class TestCounting(unittest.TestCase): def test_sum(self): """ test that it can calculate sum of fixed polyominos from number x """ up_to_1 = counting_poly({(0, 0)}, set(), [], 1) up_to_2 = counting_poly({(0, 0)}...
0d42b3489badf0f1f416f80b1c060348a08500e4
bkruszewski/Python_Courses_2017-2019
/a140917/While.py
326
3.734375
4
#while True: # print ("Hello") #stan = True #while stan: # print (100) # stan = False #liczba = 1 #while liczba <= 100: # print(liczba) # liczba +=1 liczba = 1 while liczba <= 100: if liczba % 2 == 0: print (liczba, "parzysta") else: print(liczba, "nieparzysta") liczba +=...
1e2a630703c085637f233a54e24e2588a462daa9
jwjenkins0401/Oct-10-lists
/October10.py
1,442
4.21875
4
# This is the grading program we looked at earlier # 4) Grading program - if score is > 90 you get an A, ## > 80 < 90 you get a B ## > 70 < 80 a C ## > 60 < 70 a D ## anything else you flunk grade = 55 if grade >= 90: print("A") elif grade >= 80: print("B") elif grade >= 70: print("C") elif grade >= ...
38700d8527ea41913a37460a967e8202f59aa27e
AndresFWilT/MisionTIC-2022_C1
/venv/Scripts/reto_4MINTIC2022c1.py
798
3.671875
4
def msjOrigi(m): msj = ""; for i in range(len(m)): msj += m[i] + " "; return msj; def mensajeEncr(d,m): encr = ""; for i in range(len(m)): for j in range(len(d)): if(m[i]== d[j]): try: encr += d[j+1]; except: ...
2d4dba7aad824b47396020996b8a89a8276fa2a3
tylerbrown1857/Week-Three-Assignment
/StarWars/StarWars.py
555
4.125
4
__author__ = "Tyler Brown" __program__ = "StarWarsName" __assignment__ = "WeekThreeLab" def main(): x = 0 while x != 1: #recieve input first = input("Enter your first name: ") last = input("Enter your last name: ") mother = input("Enter your mother's maiden name: ") city = input...
c7e5593464895f2778b0137c258b2f5ec9d8c41e
MaxSaunders/1aDay
/rotateLeft3.py
399
4.3125
4
""" Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}. rotate_left3([1, 2, 3]) → [2, 3, 1] rotate_left3([5, 11, 9]) → [11, 9, 5] rotate_left3([7, 0, 0]) → [0, 0, 7] """ def rotate_left3(nums): temp = nums[0] for i in range (len(nums) - 1): ...
767e34e152a2123d71676f73347631b054230bc5
huahuaxiaoshao/Python
/Algorithm/排序/插入排序.py
471
3.875
4
class Solution: def insertion_sort(self,array): if array == []: return for i in range(len(array)): pre_index = i - 1 current = array[i] while pre_index >= 0 and current < array[pre_index]: array[pre_index + 1] = array[pre_index] ...
6c62eedc216fa9aad28489e66e6d55b4bebb5751
Devalekhaa/deva
/set29.py
216
4.125
4
def factorial(num): if num == 1: return num else: return num * factorial(num - 1) num = int(input()) if num < 0: print(num) elif num == 0: print() else: print(factorial(num))
e46ded97444973e5ad8c45b94f1fbd81a2fb46cc
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH13/EX13.17.py
1,755
3.984375
4
# 13.17 (Process large dataset) A university posts its employee salary at http://cs # .armstrong.edu/liang/data/Salary.txt. Each line in the file consists of faculty first # name, last name, rank, and salary (see Exercise 13.16). Write a program to display # the total salary for assistant professors, associate professo...
e247b85788d23727fd504ca5d141c1f7317d3bdb
wenima/codewars
/kyu3/Python/src/sudoku_solver_hard_cw_submission.py
10,594
3.84375
4
""" Solution for code-kata https://www.codewars.com/kata/hard-sudoku-solver This version contains less code than the original solution I came up with as implementing the naked pairs/set/quads strategy increased the run time slightly while adding more complexity so it won't be included in the final submission on codewar...
7798caaf15ecce933485acdb7d5414119c87d0d1
Pyabecedarian/Data_Sructure-Algorithm__Learning
/excersices/task5/max_depth.py
988
3.765625
4
""" Max depth of btree """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def maxDepth(root: TreeNode) -> int: # ugly d = 0 if root: stack = [root] d += 1 while stack: ...
e1b46574c26f06c0f043aaa8cc33582b137f38fe
NMTPythonistas/nmt_python_labs
/labs/lab5/test_lettercount.py
1,153
3.890625
4
""" This test assumes your function is named `count_letters`. This function must take a string and return a dictionary. """ import unittest class TestCountLetters(unittest.TestCase): test_cases = [("", dict()), ("abc", {'a': 1, 'c': 1, 'b': 1}), ("ABC abc", {'a': 2, 'c': 2, 'b'...
c89fdcc3fd0b742093a69ddc7dfe209301b25dc1
17621251436/leetcode_program
/匹配/1008 先序遍历构造二叉树.py
609
3.734375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if not preorder: return None...
f41c2b33f50ac9cc92d0f6f53c92118b28110e05
IsseW/Python-Problem-Losning
/Workshop 3/while.py
681
4.0625
4
""" Uppgift 1 - while-loop Skriv ett program, som frågar efter ett heltal mindre än 100. Programmet ska sedan summera detta tal och alla i ordningen efterföljande heltal tills summan av talen är större än tvåhundra. Skriv ut det sista talet som tas till summan och hela summan. """ should_exit = False sum = 0 while (...
e270c59c7d4af031d08a00182460deea8963e31f
nuotangyun/qq
/regis.py
1,222
3.703125
4
""" 模拟注册过程 """ import pymysql class Database: def __init__(self): # 连接数据库 self.db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', ...
80641caf66e52b34e76d838ea1fe73a30180eaa9
itsss/SASA_OOP
/exam01_answer_code/no1.py
493
4.0625
4
''' 다음 Code를 보고, 실행 결과를 작성하시오. ''' my_list = [1,2,3,4,5] print(my_list[-1]) # 5 print(my_list.pop()) # 5 print(my_list.pop(1)) # 2 my_list = [1,2,3,4,5] my_list.remove(3) print(my_list) # [1, 2, 4, 5] my_list = [1,2,3,4,5] my_list.append([4, 5]) print(my_list) # [1, 2, 3, 4, 5, [4, 5]] my_list = [1,2,3,4,5] prin...
69f775ea5bc117ba1c2462c9cfbc9e5264cff09b
VbaGGz/LeetCode
/Find Numbers with Even Number of Digits/Digits_Count.py
226
3.8125
4
nums = [12,345,2,6,7896] def findNumbers(nums) -> int: count = 0 for num in nums: if len(str(num)) % 2 == 0: count += 1 else: continue return count print(findNumbers(nums))
9f277b181804568cb414139c12eb0885cbbafbd4
meadorjc/PythonLearning
/e_11.py
435
3.828125
4
#Caleb Meador meadorjc at gmail.com print("How old are you?"), age = input() print("How tall are you?"), height = input() print("How much do you weight?"), weight = input() name = input("\n\n\twhat is your name?") age1 = int(input("how old are you again? ")) age2 = int(input("how old is your dog? " )) print("So, you...
45181ddfeae8837e7399facda86912ed834ecaf2
xiaohuanlin/Algorithms
/Intro to algo/chapter 2/BinarySearch.py
876
3.75
4
import unittest def binary_search(A, v): ''' :param A: sorted int list :param v: target value :return: the index of the value, the complex is O(lgn) ''' if len(A) == 1: return 0 if A[0] == v else None q = len(A) // 2 if A[q] > v: return binary_search(A[:q], v) else:...
ecbbfd57def8c411b502ad4c0f50883b9194b7ad
thiagofb84jp/python-exercises
/pythonBook/chapter03/exercise3-13.py
196
3.9375
4
""" 3.13. Conversor de Celsius para Fahrenheit """ celsius = float(input("Digite a temperatura em °C: ")) fahrenheit = (9 * celsius / 5) + 32 print(f"{celsius}°C equivale a {fahrenheit}°F.")
944b4f3ceb28868293180214e9d589319680b6da
MasBad/pythonintask
/PMIa/2015/ANDROS_D_A/task_5_49.py
470
3.65625
4
#Задача 5.Вариант 49. #Напишите программу, которая бы при запуске случайным образом отображала название одного из девяти действующих вокзалов Москвы. #Andros D.A. #28.04.2016 import random vokzaly=["Belorusskiy","Kazanskiy","Kievskiy","kurskiy","Leningradskiy","Paveletskiy","Riszkiy","Savelovskiy","Yaroslavskiy"] v=ra...
3befcb2d9b5cc0f829061f22f084b389c4e4760a
mateusguida/ExerciciosPython
/ex068.py
837
3.65625
4
import os os.system("cls") #limpa janela terminal antes da execução from random import randint print("=-" * 15) print("VAMOS JOGAR PAR OU ÍMPAR") vit = 0 while True: print("=-" * 15) num = int(input("Digite um valor: ")) jogador = str(input("Par ou Ímpar? [P/I]")).strip().upper()[0] comp = randint(...
42624beed395508a8f1974bbcdb6aba3cefbb4db
s3714217/IOT-GreenhouseMonitor
/data/sqlite_repository.py
1,434
3.59375
4
import sqlite3 ''' Generic SQLite repository ''' class SqliteRepository(): SEPARATOR = ", " INSERT_SQL = "INSERT INTO %s (%s) VALUES (%s)" ONLY_DEFAULT_VALUES_INSERT_SQL = "INSERT INTO %s DEFAULT VALUES" def __init__(self, database): self.__database = database ''' Executes the supp...
2ef12b81aa4b5fc3ef4298b92680251a9bb98a76
gracejansen227/CodingDojoAssignments
/Python Stack/OOP/hospital.py
1,402
3.71875
4
#hospital import random class Patient(object): def __init__(self, name, allergies): self.id = random.randrange(1,501) self.name = name self.allergies = allergies self.bedNum = 0 class Hospital(object): def __init__(self): self.patients = [] self.name = 'Da Hosp...
2c1a05d74485982b8b3ec9e72e788feeb9816b66
KDiggory/pythondfe
/PYTHON/Files/Files.py
1,213
3.828125
4
#help(open) ##opens the help info for the inbuilt method open openedfile = open("README.md") print(openedfile) ## prints metadata - (open file IO type of data). Not the contents of the file! #help(openedfile) ## will then open help for the new variable you've made - can see there is a read function in there. ...
28feba8e0eca7b22fc117ab5ecace6408cb0b72c
villarrealp/sudokuD
/Code/SudokuTXTWriter.py
2,061
3.625
4
""" Author: Pilar Villarreal Date created: 07/18/2013 Description: This class creates a .txt file with a generated unsolved game. Modified: Comments: Revised by: """ import datetime """ Class Name: SudokuTXTWriter Description: This class creates a .txt file with a generated unsolved game. Attribut...
fde5ab5b780d6c06c55c44e22466b12a5eabe8a5
jaydavey/python-examples
/basic-python/learn-python-in-one-day/ch6/ex_ch6.4_for_loop.py
475
3.734375
4
#python3 pets = ['cats','dogs','rabbits','hamsters'] for i in pets: print(i) for index, i in enumerate(pets): print(index, i) age = {'Peter':5,'John':7} for i in age: print(("Name = %s, Age = %d" %(i, age[i]))) for i,j in list(age.items()): #python2.7 print("Name = %s, Age = %d" %(i,j)) for i in list(range(...
0281bf5fabdf0edea90a5f85c5884036d5aff68e
Sabhari-CEG/Python-dataStructures-training
/Trees/Binary_Search_tree.py
4,849
3.828125
4
class Node(): def __init__(self,data = None): self.data = data self.left_child = None self.right_child = None class BinarySearchTree(): def __init__(self): self.root_node = None def find_min(self): current = self.root_node while current.left_chil...
d633210b5cf5925a42478955b173b32544c2be7e
josemorenodf/ejerciciospython
/Bucle for/BucleFor4.py
110
3.6875
4
print('Comienzo') for number in [0, 1, 2, 3]: print(f"{number} * {number} = {number ** 2}") print('Final')
91c4af4bfa8fda9b98a609d155fd0496aa44d2ea
abbytran1996/Blackout-Puzzle
/blackout.py
8,435
3.765625
4
""" Author: My Tran File name: cpmpute.py Purpose: Solve Black-out puzzle using Stack and Queue. 2 black-out squares. """ from number import * from operation import * def calculate( numStack, operStack ): """ Takes the first two numbers from the numStack and the first operation from the operStack Does th...
716f0e036e25608ab200eb72013469bd82bf023c
barneyhill/AOC19
/Day 1/main.py
481
3.828125
4
def read_input(): with open("input.txt") as f: file = f.readlines() file = [x.strip() for x in file] file = [int(x) for x in file] return file file = read_input() #part one def fuel(mass): return int(mass/3)-2 total = 0 for mass in file: total += fuel(mass) print(total) #part two t...
2356a51fe0df76c731104a80bf310ceddfdd6469
inaram/workshops
/python2/scheduling.py
1,415
4.25
4
def sortedCalendar(myCalendar): print "Monday:", myCalendar["Monday"] print "Tuesday:", myCalendar["Tuesday"] print "Wednesday:", myCalendar["Wednesday"] print "Thursday:", myCalendar["Thursday"] print "Friday:", myCalendar["Friday"] print "Saturday:", myCalendar["Saturday"] print "Sunday:",...
d6cbcc0ef65c66b676e61c5a3c17d7104a34d838
HarishKSrivsatava/DataStructureAndAlgorithms_Python
/Array/ArrayDemo.py
515
3.703125
4
from array import * myArr = array('i',[10,20,30]) for i in range(len(myArr)): print(myArr[i], end =" ") print("\n") # insertion : insert at the index myArr.insert(1,90) for i in myArr: print(i,end = " ") print("\n") # insertion : insert at the end myArr.append(100) for i in myArr: print(i, end = " ") print("...
32ad7a3f2318803af4b3d382034d3c83ccc401a2
qkrtndh/coding_test_python
/그리디,구현문제/7.py
881
3.609375
4
""" 알파벳 대문자와 숫자(0~9)로만 구성된 문자열이 입력으로 주어진다. 이때 알파벳을 오름차순으로 정렬하여 이어서 출력한 뒤에 모든 숫자를 더한 값을 이어서 출력한다.""" #아이디어 """입력된 값을 하나씩 읽어서 문자열은 따로 하나씩 list에 저장하고 숫자는 변수에 각기 더하고, list.sort후 출력하면 되지 않을까?""" """ string = input() result = 0 num=['0','1','2','3','4','5','6','7','8','9'] a = [] for i in string: if i in num: re...
51104fbc478b492d1a17b921eb366a6080e17a92
gr2y/leetcode
/solutions/binary_tree/bfs/199.py
575
3.578125
4
# https://leetcode.com/problems/binary-tree-right-side-view/ class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if not root: return [] q = deque([root]) result = [] while q: n = len(q) for i in range(n): node ...
7908314344ab87d5f95b2897288139ec37348ab7
yokomotoh/MachineLearnigExercises
/neuralNetPredictHandwrittenDigits.py
1,498
4.03125
4
from sklearn.datasets import load_digits import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier X, y = load_digits(return_X_y=True) # when only two digits, 0 and 1, n_class=2 # we will initially only be working with two digits (0 and 1), # ...
7e74a223c02ccef52c2ea51dd9aafd13d88dbfd1
wangqianyi2017/wqycode
/StudyPython/Python6.py
855
3.5625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # __author__ = 'wangqianyi1' def fin(n): a,b = 1,1 for i in range(n-1): a,b = b,a+b return a # 输出了第10个斐波那契数列 print fin(10) #使用递归 def fib(n): if n == 1 or n == 2: return 1 return fib(n-1)+fib(n-2) # 输出了第10个斐波那契数列 print fib(10) def fic(n): if n == 1: return [1] ...
2a514d99f12af58aec04b8d768ba131949358bb1
QingqinLi/hm
/old_boy/leetcode/leetcode_greedy.py
6,852
3.578125
4
# !/usr/bin/python # -*- coding: utf-8 -*- """ __author__ = 'qing.li' """ class Solution: """ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell on...
463311559b1bea722f0485d1c9f947fb34951952
Ena-Sharma/IMDB-Top-250-Movie-Scraper
/web_scraping/IMDB_task_10.py
1,046
3.609375
4
from IMDB_task_9 import * # Task_10 #This function returns a dictionary stating numbers of movies in each language for each directors def analyse_language_and_directors(movies_list): list_of_directors={} for i in movies_list: for director in i["Director"]: list_of_directors[director]={} #Creating dictionary ke...
dc8e52390d61ee847ce34c2bf33138addd3e6fbb
shunerwadel/python
/readability.py
1,035
3.875
4
# Program to determine grade level of the given text using the Coleman-Liau formula from cs50 import get_string def main(): # Ask for text text = get_string("Text: ") # Declare variables letters = 0 words = 0 sentences = 0 # Count spaces, sentence punctuation, and letters in text f...
11e6aa51917cbd4c4155e9b6ec1a4b44f67bf8cd
CatIsCodingForU/LeetCodeProblemsRepo
/leetcode-7-easy.py
570
3.921875
4
def reverse(x): """ :type x: int :rtype: int """ if x > (2 ** 31 - 1) or x < (2 ** 31) * (-1): return 0 else: old_int_str = str(x) new_int_str = "" minus = False if old_int_str[0] == '-': minus = True old_int_str = old_int_str[1:] ...
d085c3e6952b30c1e4e1c70c39b0cc0d12552beb
michodgs25/python-exercises
/exercises/loops-lists.py
4,116
4.84375
5
# Programs need to do repetitive things very quickly # I am going to use a for-loop to build and print various lists # The best way to store the results of a for-loop is via lists # Here is a list example: # hairs = ['brown', 'blonde', 'ginger'] # eyes = ['green', 'blue', 'brown'] # weights = [1, 2, 3, 4] # You star...
a8c04cfe510487d51863894f5b14067d3bdebf29
tuannguyen0115/Python
/PythonFundamentals/CoinTosses.py
375
3.546875
4
import random head = 0 tail = 0 print "Starting the program..." for i in xrange(5001): coin = round(random.random()) if coin == 0: head+=1 else: tail+=1 print "Attempt #", i, ": Throwing a coin... It's a", "head" if coin ==0 else "tail", "! ... Got", head, "head(s) so far and", tail,"t...
24b1cd60aedcf2a2a6b532256f7cbe878783a266
saint333/python_basico_1
/list_and_tuples/10_ejercicio.py
280
4.03125
4
#Escribir un programa que almacene en una lista los siguientes precios, 50, 75, 46, 22, 80, 65, 8, y muestre por pantalla el menor y el mayor de los precios. precio=[50, 75, 46, 22, 80, 65, 8] mayor=max(precio) menor=min(precio) print(f"el mayor es {mayor} y el menor es {menor}")
9584d73c0a5aae8c44b5cd1bf2fdee03fdead1fc
subutai/appraise
/ivs/ivs.py
6,501
3.8125
4
# Simple scripts to calculate rate of return assuming dollar cost averaging # using daily closing values import sys import math import pandas import collections ###################################################################### # # Basic utility functions # The named tuples we use Closing = collections.namedtup...
40faf0e387d414e472ace7367cb098f186bf2a85
YanZheng-16/LearningPython
/Python语言程序设计/Week1/MoneyConvert_1.py
228
3.8125
4
# 货币转换 I money = input() if money[0:3] == 'USD': RMB = eval(money[3:]) * 6.78 print("RMB{:.2f}".format(RMB)) elif money[0:3] == 'RMB': USD = eval(money[3:]) / 6.78 print("USD{:.2f}".format(USD))
cd22bd6c9ef3dd89e2236b9f33da89abb89ec38c
gabriel-valenga/CursoEmVideoPython
/ex053.py
256
4
4
numero = int(input('Digite um número:')) total = 0 for i in range(1, numero + 1): if numero % i == 0: total += 1 if total == 2: print('{} é um número primo.'.format(numero)) else: print('{} não é um número primo.'.format(numero))
800013084df9bf052a3bbdfa6702b850e1cbf4d8
Oscar-Oliveira/Python-3
/10_Exceptions/I_with.py
728
3.5625
4
""" with - with EXPR as VAR: BLOCK - call VAR.__enter__ method at the begining - call VAR.__exit__ method at the end """ import os import inspect from pathlib import Path filePath = str(Path(os.path.dirname(__file__)).parent.joinpath("_Temp", "with.txt")) # Guaranteed to close the file with open(filePa...
e47f9e1318020445191fb3de430eb80e3c08ae70
jesa7955/gengoshori100nokku
/0/05.py
434
3.609375
4
source = "I am an NLPer" def ngram(source, n): l = len(source) if type(source) == str: source = "$" * (n - 1) + source + "$" * (n - 1) for i in range(l + 1): print(source[i:i+n]) elif type(input) == list: source = ["$"] * (n - 1) + source + ["$"] * (n - 1) for i...
23412a7c2698b9044c5bf0ca29634a5e1ace7998
jbrdge/ProjectEulerSolutions
/Python/problem0005.py
308
3.84375
4
#project0005 #github.com/jbrdge def smallest_multiple(number): a = list(range(2,number+1)) n = 1 for i in range(0,len(a)): for j in range(i-1,-1,-1): if(a[i]%a[j]==0): a[i]=a[i]//a[j] for i in a: n*=i return(n) print(smallest_multiple(20))
06d1292182cbcb289b2f9d35fd8149f368351b76
lwtor/python_learning
/03_demo/fact.py
440
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def fact(num): if num == 1: return 1 return fact(num - 1) * num # 使用尾递归 # 然而python并没有对尾递归做优化。。。 def fact_good(num): return fact_real(num, 1) def fact_real(num, product): if num == 1: return product return fact_real(num - 1 , num * pro...
d79fb9da01de41d0c3baf2ddbd601fe21b9232d4
sabinbhattaraii/python_assignment
/Functions/q20.py
212
4.0625
4
''' Write a Python program to find intersection of two given arrays using Lambda. ''' array1 = [1,2,3,4,5,6] array2 = [4,5,6,7,8,9] intersection = list(filter(lambda x : x in array1, array2)) print(intersection)
fae03c7a8b8441149d3de60a98363084415ef50b
NairitaMitra/JISAssasins
/4th.py
439
3.984375
4
# How many number we have to sort num = int(input("How many figures : ")) storage = [] result = [] # Creating an array of users numbers for i in range(1,num+1): a = int(input("Enter value" + str(i) + " : ")) storage.append(a) # user enter # Sorting the array for m in range(len(storage)): b =...
0fe66fdb33a676e263a0d3a3c869a13b4d629e63
Sinjebos/EcUtbildningDevOps
/Linux and Script Languages/Python/Self Studies/FunctionsIntro/factorial_function.py
257
3.921875
4
def factorial(number: int) -> None: result = 0 for index in range(number + 1): if index == 0: result = 1 print(index, result) else: result *= index print(index, result) factorial(35)
ef477e2924536d47dc8d20b4d548c1a9aa574e3b
yichong-sabrina/learn-python
/Chap4 Functional Programming/4_1_3 Sorted.py
578
4.09375
4
num = [36, 5, -12, 9, -21] print(sorted(num)) print(sorted(num, key=abs)) print(sorted(num, key=abs, reverse=True)) s = ['bob', 'about', 'Zoo', 'Credit'] print(sorted(s)) print(sorted(s, key=str.lower)) # 用一组tuple表示学生名字和成绩, 用sorted()对其分别按名字和成绩排序 def by_name(t): return t[0] def by_grade(t): ...
65729e6e834ed23c41e4e17ccc45f37c1efbf5bf
Swastik2561/LinkedList
/linkedlist.py
453
3.96875
4
class linkedlist: def __init__(self,headvalue): self.headvalue = headvalue self.nextnode = None def printing(self): printvalue = self while printvalue is not None: print(printvalue.headvalue) printvalue = printvalue.nextnode x = linkedlist("UmarAbdullah")...
773cbf51e889dd4bfe44a4526388c91a5e952136
weston-bailey/algorithms
/practice-problems/python/cracking_strings.py
8,285
4.25
4
''' 1.1 Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? ''' test_cases_1_1 = ['abc1frgt', 'abcdefghijklmnop', 'aaaaaa', 'bcdefaaght', 'ythbuioh'] # no external datatypes def unique_chars(s: str) -> bool: for i in range(len(s)):...
de3d81cba4066d43c553f6520b1034ae862d89e0
cpeixin/leetcode-bbbbrent
/geekAlgorithm010/Week08/merge_sort_1.py
993
4.03125
4
def merge(a_list, b_list): # 所要利用的额外空间 result = [] a_index, b_index = 0, 0 # index从0开始,所以 < 号 while a_index < len(a_list) and b_index < len(b_list): if a_list[a_index] < b_list[b_index]: result.append(a_list[a_index]) a_index += 1 else: result.appe...
0cd083db1a346725b1d274345692543348c29129
zileyue/python3_study
/sum1.py
488
3.859375
4
#! /usr/bin/python #coding=utf-8 print("Type integers,each follow by enter,or just enter to exit.") total = 0 count = 0 while True: line = input("Input integers: ") if line: try: number = int(line) total += number count += 1 except ValueErro...
3dd47a26a5ab85d875a2e5d30ef8634b72fb2642
verilyDA/DojoRepo
/DojoAssignments/Python/assignments/multiples.py
493
4.375
4
''' multiples write code that prints all numbers from 1 to 1000. use a for loop Create another program that prints all the multiples of 5 from 5 to 1,000,000. ''' ''' for count in range(1, 1000): if count % 2 == 1: print(count) for count in range(5, 1000000): if count % 5 == 0: print(count) '''...
f6b1b6795d8c34e92be73e61d489b9e7f2a4178f
QiWang-SJTU/AID1906
/Part1 Python base/01Python_basic/03Exercise_code/Day07/exercise06.py
342
3.875
4
# 列表解析式嵌套,全排列 list01 = ["香蕉", "苹果", "哈密瓜"] list02 = ["雪碧", "可乐", "牛奶"] list_result = [] for i in list01: for j in list02: list_result.append(i + j) print(list_result) list_result_1 = [i + j for i in list01 for j in list02] print(list_result_1)
2f98c223576a7272969a7efe38f549ebd96ad75c
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 2/Ex055.py
270
3.828125
4
## maior e menor peso maior = 0 menor = 1000 for x in range(1, 7, 1): peso = int(input('Qual o seu peso?')) if peso>maior: maior = peso if peso<menor: menor = peso print('O menor peso foi de {} e o maior peso foi de {}.'.format(menor, maior))
02beeae5c74319cedbe8d5cad533357e7cd87359
Vith-MCB/Phyton---Curso-em-Video
/Cursoemvideo/Exercícios UFV/Lista 6/exer04 - N no vetor.py
157
3.578125
4
vet = [int(input()) for i in range(5)] n = int(input()) if n in vet: print(f'O numero {n} está na posição {vet.index(n)+1}') else: print('Erro!')
843b0e3acdca676aa5cb82aed08b5a12b2449d66
morrisoncd31/BeginnersScripts
/Loops.py
212
4.15625
4
upper_bound = input("Choose the range upper bound --> ") upper_bound = int(input("Choose the range upper bound --> ")) for x in range(1, upper_bound): print("The next number in line is {}".format(exit(x)))
9632933a109ff171dc261c492c53fd317e354664
junzhougriffith/test
/PyLab/W136.py
1,489
4.125
4
##////////////////////////////// PROBLEM STATEMENT ///////////////////////////// ## Write Python code that reads a boolean and an integer from the keyboard. // ## If the boolean is True and the integer is in the range 1. . 100 OR if // ## the boolean is False and the integer is not in the range 1..100 and the ...
ee3088d262f6e56e601f1906827c96928d6672e7
isaranto/CKY-algorithm
/Parser.py
1,877
3.671875
4
import re class Rule: def __init__(self, line): """ Rule is being parsed like this: eg. "S -> NP VP" will become an object Rule with non-terminal = S, first = NP and second VP :param line: :return: """ start = re.split(" -> ", line.strip('\n'))[0] en...
22e044b454ac2a56bdc0db4be0199318f8da5f79
AnupamKP/py-coding
/array/add_one_num.py
550
4.125
4
''' Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is at the head of the list. Example: If the vector has [1, 2, 3] the returned vector should be [1, 2, 4] as 123 + 1 ...
64700219c90352da7ac9e9694225032e41be4f6e
trevorbillwaite/Week-Two-Assignment
/temp.py
798
4.375
4
__author__ = 'trevorbillwaite' # Introduction to Computer Science # temp.py # Program will compute and print a table of Celsius temperatures and the Fahrenheit equivalents every 10 degrees from 0C to 100C # Declare Magic Numbers and Constants # LOOPCOUNTER = 2 # name = "bob" # Write program code here # ask user ...
58b781ec9727b3e44a4a58050d23b640e9c1731d
wbigal/FATEC-ALP
/lista_1/04_totais_positivos_negativos.py
418
4.125
4
#coding: utf-8 numero = -1 positivo = 0 negativo = 0 while(numero != 0): numero = int(input("Digite um número inteiro (zero para sair): ")) if (numero > 0): print("{} é positivo").format(numero) positivo += numero elif (numero < 0): print("{} é negativo").format(numero) negativo += numero print...
545f6113e1771aa3e0c28e2fd068a0fb8755c1e1
francliu/mmseg
/core/quantifier.py
670
3.5625
4
import re from Dictionary import Dictionary from Dictionary.digital import is_chinese_number number_pattern = u'[0-9]+[*?]*' def combine_quantifier(words): pos = 0 words_length = len(words) result = [] while pos < words_length: word1 = words[pos] if (re.match('^%s$' % number_pattern, ...
03c0bae65e89fa04a3a1de8f49e07635897e56c5
JoshuaAppleby/ProjectEuler
/ProjectEuler006.py
935
3.6875
4
#Project Euler, Problem 6 #Sum square difference #The sum of the squares of the first ten natural numbers is, # 1**2 + 2**2 + ... + 10**2 = 385 #The square of the sum of the first ten natural numbers is, # (1+2+...+10)**2 = 55**2 = 3025 #Hence the difference between the sum of the squares of the first ten natur...
33b2297c72b078002963aeaf258b90a7a907b442
Esala-Senarathna/Python-Ex
/DSA Labs/Lab 7/Question 1.py
270
3.984375
4
def bubbleSort(arr): n = len(arr) for i in range(n - 1): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] l =[] for i in range(8): l.append(int(input())) bubbleSort(l) print(l)
6f72e573ebabc68a71625596ae8c91c7aac77506
majaharkot/gitrepo
/python/tabliczka_mnozenia.py
528
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # tabliczka_mnozenia.py # def tabliczka(a, b): for kolumna in range(1, a + 1): #pętla zewnętrzna for wiersz in range(1, b + 1): #pętla wewnętrzna print("{:>3} ".format(wiersz*kolumna), end='') print() def main(args): a = int(input(...
76f1d0362e949a052594b36944c3133eddb809ce
blukke/Python
/Funcoes/Exercicios/Coiso 4.py
266
3.78125
4
# Turma B # Exercício número 4 por Juan Lucas Melo de Borba def area(w, h): area = w * h # w= largura e h= altura t = area / 2 print('Area de {} '.format(t)) w = int(input('digite a largura do negocio: ')) h = int(input('Digite a altura do negocio: ')) area(w, h)
66f7428753e059054aad34e979a01814f17555a3
NARESHSWAMI199/python
/python/dictnary/more.py
605
4.3125
4
# access the value form a dict names = { 'presion1' : {'name' : 'naresh','age' :24}, 'presion2' : {'name' : 'nsh','age' :14}, } # you can't store a list or tuple or dict in a dict whitout his key print ([names[name]['name'] for name in names]) # find the max score using max() function students = { 'nar...
9c000e40e2a43eadc5465c47d4dfbe9fef8feac7
Rajatkhatri7/Project-Milap
/DataStructure and algorithms/LinkedList/reverseLL.py
1,837
4.25
4
#!/usr/bin/env python3 class Node: def __init__(self,data): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def appending(self,data): if self.head is None: new_node = Node(data) self.head = new_node ...
f8bfb8e771eda351736c7d85fda378fe279bff96
himabinduU/Python
/bank_account.py
2,736
4.03125
4
# Title : Bank_account for multiple users. import math list = [] #Bank_account fields dict = {'name':'none', 'balance':0, 'account_no': 0} g = 0 #Creating an account def make_account(name, account): seq = ('name', 'balance', 'account_no') list.append(dict.fromkeys(seq)) global g list[g]['account_no'] = account ...
ae7745125e3efb617e6050b3e9b799b0873c6c03
xioner/TileTraveller
/tiletraveller.py
3,859
4.125
4
# Player starts at pos 1,1 # Depending on position, the player can either move north, south, west or east. # Ask for direction, convert to lowercase. # If invalid direction is entered error handle + give user a chance to redeem themselves # east and west are on x axis # south and north are on y axis # If valid directio...
86311e1988b63d841c5f3a3264c9d68657ecc567
jordangerdin/Capstone-Lab-7
/coinprice.py
1,041
3.765625
4
import requests import pprint def main(): dollars = get_bitcoin_ammount() converted = convert_bitcoin_to_dollars(dollars) display_result(dollars, converted) def get_bitcoin_ammount(): while True: try: return float(input(f'Enter bitcoin to convert: ')) except: pr...
79fe64cb4e46bf28500de4061f8d62e46911ed6d
beajmnz/IEDSbootcamp
/theory/02a-Data Types and Variables/DTV4.py
205
4.15625
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ Created on Tue May 4 17:05:42 2021 @author: Bea Jimenez <bea.jimenez@alumni.ie.edu> """ text = input("please write some text: ") print("\nthe length of the text is:",len(text))
d026ba76da4eb16e843971a63503136b42972dae
heitorchang/learn-code
/checkio/home/pawn_brotherhood.py
1,220
3.609375
4
def coordToGrid(coord): col = ord(coord[0]) - ord('a') row = int(coord[1]) - 1 return (col, row) def inBounds(coord): return 0 <= coord[0] <= 7 and 0 <= coord[1] <= 7 def safe_pawns(pawns): board = [[0 for _ in range(8)] for _ in range(8)] # place pawns for pawn in pawns: gridCoo...
41b27cf462d4797fd99b187e13ad2b383c87090d
ixaxaar/seq2seq-dnc
/src/scripts/index_corpus.py
855
3.703125
4
#!/usr/bin/env python3 import argparse from util import * def index_corpus(name, corpus): '''Index a corpus to form a dictionary Arguments: name {string} -- Name of this language / corpus corpus {string} -- Path to the text corpus to index ''' l = Lang(name) with open(corpus) as ...
4e7896157f721045c361812f1f9bbb78e5960321
matheusmpereira/tecnicas-de-programacao
/atividade.n1.py
1,697
3.765625
4
from random import randint movimentos= 0 casa = 1 venceu = 0 jogada= 0 while venceu == 0: if movimentos >= 6: print("Você atingiu o limite de movimentos!") break; else: while casa == 1 and movimentos <7: print("Você esta na casa: ",casa) print("Você ainda tem", 7-movimentos,"movimentos") ...
e749dab1950110418c36005e5907388f7026eb4a
aloha45/python_control_lab
/fruits.py
365
4.0625
4
prices = { 'banana': 4, 'apple': 2, 'orange': 1.5, 'pear': 3 } stock = { 'banana': 4, 'apple': 5, 'orange': 6, 'pear': 7 } for price in prices: print(f'{price}') print(f'Price: {prices[price]}') print(f'Stock: {stock}') total = 0 for price in prices: inventory = prices[price] * stock[price] ...
ebcb30f8a743ecb48b0f5a6bb8eb097a39631b19
freitasSystemOutPrint/Python3
/pythonteste - aulas/aula08a.py
351
4.21875
4
import math num = int(input('Digite um número: ')) raiz = math.sqrt(num) print('A raiz de {} é igual a {:.2f}'.format(num, raiz)) ''' Para arredondar para cima use o ceil e para baixo florr e para casas decimais dentro dos '{}' use ':' dois pontos {:.2f} em vez de '%' print('A raiz de {} é igual a {}'.format(...
5b748cdacdcfd35ec0a04e32d19a1c232a7d6965
thaisNY/GuanabaraPy
/30.py
123
4.03125
4
num = int(input('Digite um número')) if num % 2 == 0 : print('O numero é par') else : print('O némero é impar')
4b9307392c50072fd4b11de15f4595919d0334ce
theChad/ThinkPython
/chap12/reducible.py
3,351
4.0625
4
# Exercise 12.4 # complecting <-- largest reducible word in words.txt # Using the hints.. # 12.4.4 # A bit backwards, but doing this first so we have the memo variable as global known = dict() # 12.4.1 def find_children(words, word): """Find all children of a word, i.e. words that are revealed by dropping a...
59fc62450c7d1a60ebdd369ec22c02233038f7cb
Aquariuscsx/python
/homework/day18/duojiceng.py
1,975
3.9375
4
# # class A: # # pass # # # # class B(A): # # pass # # # # class C: # # pass # # # # class D(C): # # pass # # # # class E( B, D): # # pass # class Person(object): # def __init__(self, name, age, height): # self.name = name # self.age = age # self._height = height # # # cl...
9c63d6032f0cc504bc40c668e715d0aa7ec2204d
mjh-sakh/python-project-lvl1
/brain_games/games/gcd.py
821
3.84375
4
# noqa: D100 import random RULE = 'Find the greatest common divisor of given numbers.' def find_gcd(number1: int, number2: int) -> int: """ Find GCD for two numbers. Args: number1: int number2: int Returns: gcd: """ if number2 > number1: return find_gcd(numb...
ae5403397b4d71d9650467d874aed9c4c44b00c7
itay-feldman/a3c-continuous-action-space
/bullet_minitaur/lib/experience.py
6,459
3.59375
4
import numpy as np import random from collections import namedtuple import gym from collections import deque # Simple named tuple that stores Experience Experience = namedtuple('Experience', ['state', 'action', 'reward', 'done']) class ExperienceSource: """ Class that creates an iterable experience sour...
b9568096be39dd3ec10d0e600945f5d9721dec64
BillionsRichard/pycharmWorkspace
/leetcode/easy/find_learned_words_len/srcs/a.py
861
3.75
4
# encoding: utf-8 """ @version: v1.0 @author: Richard @license: Apache Licence @contact: billions.richard@qq.com @site: @software: PyCharm @time: 2019/9/13 22:43 """ from pprint import pprint as pp class Solution: def countCharacters(self, words, chars): word_cnt = len(words) word_cab_l...