blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d0914424a1f4119a26b7a8ab66e6163c43ff0a1d
SS1908/30_days_of_python
/Day 15/many_exceptions.py
415
3.890625
4
""" You can define as many exception blocks as you want. e.g. if you want to execute a special block of code for a special kind of error """ try: print(x) except NameError as e: print("x is not defined") print(e) except ZeroDivisionError as e : print("you can not divide a number by z...
3e522f757a6a08bee99d98a1e5cdef8f06ddad56
SS1908/30_days_of_python
/Day 13/reduce_function.py
363
3.84375
4
from functools import reduce num = [5,87,3,46,14,89,66,7] #TODO find a even number from the list even =list( filter(lambda a : a%2==0,num)) print(even) print() #TODO double all the even number double = list(map(lambda n : n*2,even)) print(double) print() #TODO add all the avlues of double list sum ...
9d6e28084ff70545db5ed473b6ca361806566481
SS1908/30_days_of_python
/Day 6/Comparisons_of_set.py
406
4.25
4
# <, >, <=, >= , == operators Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"} Days2 = {"Monday", "Tuesday"} Days3 = {"Monday", "Tuesday", "Friday"} # Days1 is the superset of Days2 hence it will print true. print(Days1 > Days2) # prints false since Days1 is not the subset of Days2 print(Days1 < Days...
6a1f01bccda41e9216fc389162eaa758f241ac7d
SS1908/30_days_of_python
/Week 1/Day 1/Logical_operator.py
761
4.5625
5
#Logical operators are use to combine conditional statements. # Operator Description # and Returns True if both statements are true # or Returns True if one of the statements is true # not Reverse the result, returns False if the result is true pr...
f0e81dd8a2ae050a43b5ac6362f8ab2a71a58d31
SS1908/30_days_of_python
/Day 17/creating_a_class.py
667
4.09375
4
""" Python Classes/Objects Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. """ #to create a class,use keyword 'class' class computer: ...
f6e67804d73f4752211b4dbc74430294e70e9067
alx5246/remoteIntrepTutorial
/src/simple_tutorials/using_exceptions_to_break.py
947
3.953125
4
# A. Lons # Jan 2017 # # i AM TRYING TO figure out how to us exceptions to break out of stuff. Inside the CIFAR-10 eval, they use an Exception # to request the coordinator to stop. I am thinking this brings all things under the coordinator to a halt. So I am # going to see if this makes sense.... RESULT: the inside loo...
e78af3ec0d8e45c9ac48595b62f270cae06582a4
TakudzwaMakoni/trinkets
/pygrams/multigraph/multigraph.py
27,300
4.0625
4
from matplotlib.pyplot import plot import os, subprocess # the master function is the main function of the program # the main power in the master function is its ability # to run as many times as the user needs, creating as many files, # containing all data for a single country, as the user wishes in one # run of the...
5e419ddb7158756425a829a49e7af1d4c3c9915e
RitamAgrawal/leetcode-questions-using-ds-algo
/2. Add Two Numbers.py
1,600
3.75
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: ##### Method 2 carry = 0 l3_head_val = l1.val + l2.v...
bcb52daca7e053e7b69bb256087ad377fa76c140
RitamAgrawal/leetcode-questions-using-ds-algo
/1480. Running Sum of 1d Array.py
353
3.515625
4
class Solution(object): def runningSum(self, given_array): """ :type nums: List[int] :rtype: List[int] """ array_of_array = [given_array[0]] for j in range(1,len(given_array)): add = given_array[j] + array_of_array[j-1] array_of_array.append(ad...
00e99e6744f2170149fc74758fbfe160f3356000
Talendar/maze_solver
/maze.py
16,220
4.1875
4
""" Defines the structure and operations of a maze. This module contains the class that will represent a maze. The goal is to compare the efficiency of different pathfinding algorithms in solving mazes. @Author: Gabriel Nogueira (Talendar) """ from graphs.undirected_graph import Graph from graphs.pathfinding import ...
34133a627a028c0b89086bd79ab2928cdd85aa36
leoweller7139/111-Lab-1
/calc.py
1,299
4.15625
4
# Method on the top def seperator(): print(30 * '-') def menu(): print('\n') #\n is like pressing enter seperator() print(" Welcome to PyCalc") seperator() print('[1] - Add') print('[2] - Subtract') print('[3] - Multiply') print('[4] - Divide') print('[x] - Exit') ...
6da4339c3521af1c428daf6e051e9a93401d332a
Denise-Yang/rosg
/Player.py
6,494
3.53125
4
################################################################# # Player Class # Your Name:Denise Yang # Your Andrew ID: denisey # Your Section: C ################################################################# ''' framework taken from https://github.com/LBPeraza/Pygame-Asteroids/blob/master/Asteroids/Ship.py by L...
a702def327c51aaffac0b4b4a01c627f0dc1ba3a
suwinphyu/Tutorials
/python_tutorial/venv/Include/tuple.py
207
3.84375
4
list = ['Peter', 'Josep', 123 ,69.50] print(type(list)) print(list) tuple = ('Peter', 'Josep', 123 ,69.50) print(type(tuple)) print(tuple) list[0] = "Mathew" print(list) tuple[0] = "Mathew" print(tuple)
fd233640030707456e8dbb04b6ebfe17f586c376
suwinphyu/Tutorials
/python_tutorial/venv/controlFlow.py
371
3.84375
4
user_mark = int(input("Enter your marks :")) if user_mark < 40: print("You're failed with {} marks".format(user_mark)) elif 40 < user_mark <65 : print("You're passed with {} marks". format(user_mark)) elif 65 < user_mark <80 : print("You're modified with {} marks".format(user_mark)) else: print("You...
38f86cac3e70bd9a3ababcfc0bc6f8c14b70d4f3
WinThitiwat/TextAdventureGame_DS-for-Python
/Text-Adventure/text-adventure.py
20,370
4.0625
4
# created on: Oct 15, 2018 # Author: Win.thitiwat """ Text-Adventure-Game (This is an exercise from Python-for-DataScience Class) -- Purpose -- To demonstrate how to construct a structure-based on a game map -- Introduction -- In this game, there are 3 stages on our game's map. The map structure are her...
21d2010563accdfdc5b2a3883039e5b191405f87
kerenskybr/advanced_deep_learning
/fashion_mnist/fashion_mnist_cnn.py
3,459
3.8125
4
from keras.models import Sequential import keras # print(dir(keras.layers )) from keras.utils import to_categorical from keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization import numpy as np import pandas as pd import matplotlib.pyplot as plt # Where to grab the data http...
e88e04d4665e494781118dde77c3c8b432c7973a
gabe01feng/trinket
/Problem Set 6/secondMaximum.py
130
3.734375
4
a = 0 b = 1 c = 0 while b != 0: b = int(input()) if c < b: c = b if a < b: a, c = b, a print(c)
684a6f6049359c0f77b8d6e13e7780570a71f845
gabe01feng/trinket
/Python Quiz/dayAndWeekOfYear.py
959
4.1875
4
number = int(input("Pick a number from 1-365. ")) week = ((number + 4) // 7) + 1 day = (number + 3) % 7 ending = '' if day % 10 == 1 and day != 11: ending = 'st' elif day % 10 == 2 and day != 12: ending = 'nd' elif day % 10 == 3 and day != 13: ending = 'rd' else: ending = 'th' if week % 10 == 1 and we...
c13b08298eb161052851f000db07bdafc875f9bc
gabe01feng/trinket
/Problem Set 2/sumOfDigits.py
167
3.9375
4
a = str(input("Pick a number. ")) sum = 0 for n in range(0, len(a)): sum = sum + ((int(a) // (10 ** n)) % 10) print("The sum of all digits is " + str(sum) + ".")
7e6b12f049789a9333b9498340c7c887b25201c0
gabe01feng/trinket
/Problem Set 4/series1.py
148
3.921875
4
a = int(input("Pick a start number. ")) b = int(input("Pick an end number greater than your start number.")) for i in range(a, b + 1): print(i)
d3c4ac955ae2aa9b5f38a63441289bad5965d090
gabe01feng/trinket
/Problem Set 3/signCheck.py
173
4.125
4
a = int(input("Pick any real number. ")) if a > 0: print("The number is positive.") elif a < 0: print("The number is negative.") else: print("The number is 0.")
707460b8007c0c0671ba6958e351ef929a59cc9d
gabe01feng/trinket
/Problem Set 3/bishopMove.py
351
4.0625
4
x1 = int(input("What column did the bishop start in? ")) y1 = int(input("What row did the bishop start in? ")) x2 = int(input("What column did the bishop stop in? ")) y2 = int(input("What row did the bishop stop in? ")) if abs(x1 - x2) == abs(y1 - y2): print("Yes, the bishop can move there.") else: print("No, ...
c3b4e2f580b13b04739c2b47b7dd47def850947e
gabe01feng/trinket
/Python Quiz/poolVolume.py
1,108
4.1875
4
import math name = input("What is your name? ") pool = input("What shape is your pool, " + name + "? (Use RP for rectangular prism, C for cube, or CY for a cylindrical pool) ") if pool == "RP": length = float(input("What is the length of the pool in feet? ")) width = float(input("What is the width of the pool...
bc5ec8e7db5586a6a03121695112e25523fb2140
viniciussm07/simulador-de-dados
/dados.py
1,849
3.796875
4
from random import randint def main(): nd = obter_numero_de_dados() nl = definir_numero_de_lados(nd) for i in nl: n = randint(1, i) print(n) def obter_numero_de_dados(): # Obter inputs do usuário while True: n = input("Número de dados: ") # Verificar se n é um dígito if not n.isdigit(): con...
8a3ad768290694ccda71e6f6bf78479ecb27e696
laraib-sidd/Prom-Bot
/db/functions/db_func.py
1,550
3.6875
4
import sqlite3 import os # Setting up database def set_up_database(): conn = sqlite3.connect("cab_data.sqlite") cur = conn.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS DATA(user_id INTEGER UNIQUE, Name TEXT,Phone INTEGER,Age INTEGER, City TEXT, Region TEXT, PromoCode T...
cb2db286b37f338d89b960379cca2e858f74cbb2
YifanC86/hrinf-development
/2020-2021/DEV2/Chapter 3/BA06.py
159
3.859375
4
def count(a, b): if a > b: return '' else: partial = count(a, b - 1) ret = partial + str(b) return ret a = 2 b = 5 s = count(a, b) print()
2f9c52a17d661683e5fc6926fcee0e4c96fbfa9e
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 5/BA26.py
88
3.625
4
n = 5 print() sigma = 0 i = n while i > 0: sigma = sigma + i i = i - 1 print()
05ce00ad3452e0ab5b4f4b496cfff8a5929e42f1
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 7/BA10.py
355
3.90625
4
height = 3 s = '' row = 0 temp = height while row < height: col = 0 while col < temp - 1: s = s + ' ' col = col + 1 while col < height + row: s = s + '*' col = col + 1 while col - height < height - 1: s = s + ' ' col = col + 1 s = s + '\n' row = r...
8c10cb8b04a6e52079cff3a2a4ba1376c17cd3c1
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 4/BA14.py
201
4
4
number = 8 divisor = 4 print() if (number % divisor == 0): output = str(number) + ' is divisible by ' + str(divisor) else: output = str(number) + ' is NOT divisible by ' + str(divisor) print()
dc41ad19a97467fc5daccddaaf70905c2c1a1907
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 5/BA27.py
153
4.1875
4
n = 27 print() isPrime = True if n <= 1 or n % 1 > 0: isPrime = False for i in range(2, n // 2): if n % i == 0: isPrime = False print()
e863e8da3385866bf22f9662c7410fd83761a33b
YifanC86/hrinf-development
/2020-2021/DEV2/Chapter 3/BA01.py
130
3.6875
4
def sumUpTo(n): if n <= 0: return 0 else: temp = sumUpTo(n - 1) return temp + n a = 5 result = sumUpTo(a) print()
69aa6356882bc6551655510f36619360474a11d7
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 4/BA4.py
119
3.828125
4
x = 55 y = 60 if x > y: s = 'Max is x.' elif y > x: s = 'Max is y.' else: s = 'Numbers are equal.' print()
cf7e0da5b7e18f917c5ef4adeb8b2a0757ebdf82
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 6/BA3.py
172
4.0625
4
x = 0 while x < 12: x = x + 1 if x == 5: s = '*** 5 is odd ***' elif x % 2 == 0: s = f"{x} is even" else: s = f"{x} is odd" print()
4d4a10288de9808d18ccc4151802907e523ffec8
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 5/BA19.py
240
3.828125
4
number1 = 10 number2 = 40 if number1 < number2: smallestNumber = number1 else: smallestNumber = number2 n = 1 gcd = 1 while n <= smallestNumber: if number1 % n == 0 and number2 % n == 0: gcd = n n = n + 1 print()
4da508b1486aaa2f332f4e93f8b0357e2f18708e
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 5/BA4.py
85
3.671875
4
start = 0 end = 5 incr = 1 print() i = start while i < end: i = i + incr print()
888fb506b431404b5297f335e1591cab7ebb3477
YifanC86/hrinf-development
/2020-2021/DEV2/Chapter 3/BA02.py
149
3.65625
4
def repeatStar(n): if n <= 0: return '' else: temp = repeatStar(n - 1) s = '*' + temp return s a = 4 res = repeatStar(a) print()
e078909443bb124140a73f1510c3558cbabea527
YifanC86/hrinf-development
/2020-2021/DEV1/Chapter 5/BA21.py
173
3.84375
4
number = 9 print() numberAsBinary = '' num = number while num != 0: remainder = num % 2 num = num // 2 numberAsBinary = str(remainder) + numberAsBinary print()
08cc22faa966337e968aafe7447ce3af38d9a1c4
YifanC86/hrinf-development
/2020-2021/DEV2/Chapter 3/BA07.py
205
3.78125
4
def count(a, b): if a > b: return '' elif a == b: return str(a) else: partial = count(a + 1, b - 1) ret = str(a) + partial + str(b) return ret a = 0 b = 6 s = count(a, b) print()
012086242df6f343708b07f9dd03710ee7ffc2fb
elarbee/euler
/23/23.py
1,097
3.796875
4
#find every number that is a sum of two abundant numbers under 28123 #Returns the sum of the proper divisors of n def d(n): l = range(1,(n/2)+1) l = filter(lambda x: n%x==0,l) return sum(l) #def perfect(n): # return d(n) == n # #def deficient(n): # return d(n)<n def abundant(n): return d(n)>n #return a distinc...
29b59615adf2069988a4e84989840118886faf05
TushinIE/cource-work
/Курсовая работа по программированию/31 Задача (2 часть курсовой)/example_29.py
1,119
4.1875
4
#имя проекта: numpy-example #номер версии: 1.0 #имя файла: example_29.py #автор и его учебная группа: И.Тушин, ЭУ-142 #дата создания: 20.05.2019 # дата последней модификации: 20.05.2019 #связанные файлы: пакеты numpy, matplotlib # описание: Создать прямоугольную матрицу A, имеющую N строк и M столбцов со # случ...
726edd78dab141ca239759642d86a4312b7c92af
TushinIE/cource-work
/Курсовая работа по программированию/31 Задача (2 часть курсовой)/example_17.py
1,110
4.28125
4
#имя проекта: numpy-example #номер версии: 1.0 #имя файла: example_17.py #автор и его учебная группа: И.Тушин, ЭУ-142 #дата создания: 11.05.2019 # дата последней модификации: 11.05.2019 #связанные файлы: пакеты numpy, matplotlib # описание: Создать прямоугольную матрицу A, имеющую N строк и M столбцов со # случ...
d68f4b523b209f3a42cea58cafd8b153eeba6ba2
Mukosame/learn_python_the_hard_way
/ex25.py
1,380
4.4375
4
def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word...
2aa078dc068d59306dd016ccd5f61591fc6c1214
aselvais/PythonOOPexample
/libs/animals/AnimalArmy.py
1,246
4.1875
4
""" Class for creating an army of animal """ from libs.animals.Dog import Dog from libs.animals.Duck import Duck class AnimalArmy: """Generates an army of animals Args: animal_type (str, optional): duck or dog. Defaults to 'duck'. army_size (int, optional): Number of animal in the army. Defau...
8cf46b2ac5a7755f161bd11ed631ef8d84de3e95
ctralie/SSMTW
/Jigsaw.py
7,704
3.640625
4
""" Programmer: Chris Tralie Purpose: To provide functions for loading paths from SVG files and using them to make simple jigsaw puzzle pieces """ import numpy as np import matplotlib.pyplot as plt from svg.path import parse_path import xml.etree.ElementTree as ET def loadSVGPaths(filename = "paths.svg"): """ ...
9a8358b254d8fce36d832f3a4cc4323800913f57
goalkeeperfyc/leetcode_practice
/Q7_Reverse_Integer.py
1,189
3.796875
4
# The first version, high memory usage and high runtime def reverse(x): x_str = str(x) length = len(x_str) new_str_list = [] if x_str[0] == "-": new_str_list.append("-") length -= 1 for num in (range(length)): new_str_list.append(x_str[-num - 1]) new_num = int("".join(ne...
40de35ef837de6beed9ec2b9087199def90b1b5f
habibamariam/python-practice-programs
/turtle1.py
729
3.828125
4
import turtle def draw_shapes(): windows = turtle.Screen() windows.bgcolor("Red") draw_square() draw_circle() draw_triangle() def draw_square(): habi= turtle.Turtle() habi.shape("turtle") habi.color("violet","green") habi.speed(2) for i in range(1,5): ...
a280f45f234a12daacc34a829d2ab4cd6a264318
eugenechernykh/coursera_python
/week7_phone_numbers.py
3,080
4.125
4
''' https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/iw02h/tieliefonnyie-nomiera Телефонные номера в адресной книге мобильного телефона имеют один из следующих форматов: +7<код><номер> 8<код><номер> <номер> где <номер> — это семь цифр, а <код> — это три цифры или три цифры в круглых скобках. Е...
0c3c06453422447a8b2b2ac2bb2520b72ca9db64
eugenechernykh/coursera_python
/week4_min_odd.py
1,085
3.78125
4
''' Выведите значение наименьшего нечетного элемента списка, гарантируется, что хотя бы один нечётный элемент в списке есть. 3 решения с таймингами ''' import time as t # print('123 '*10000) intList = list(map(int, input().split())) # first solution tic = t.time() def isOdd(a): for i in range(len(a)): ...
10783a6e8a9330f6c9d9a9f3204707db62a98d51
eugenechernykh/coursera_python
/week8_null_or_not.py
671
4.03125
4
''' https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/9uqay/nol-ili-nie-nol Проверьте, есть ли среди данных N чисел нули. Формат ввода Вводится число N, а затем N чисел. Формат вывода Выведите True, если среди введенных чисел есть хотя бы один нуль, или False в противном случае. ''' print( ...
c03a59b358488f6cb46ab744badbe7ee2208c0c6
jiedawang/machine-learning-python
/user_lib/old_version/regression_old.py
22,574
3.546875
4
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt from user_lib.data_prep import DataPreprocessing class LinearRegression: #线性回归模型:theta0*1+theta1*x1+theta2*x2+... #theta:参数向量,Series类型,theta[i]对应thetai #x:特征矩阵,DataFrame类型,column[i]对应xi,row对应每一条数据记录 def ...
cd48a3959f0b3b6c5573e75f47d433a813e04e4d
cotyb/coding-interviews
/codes-coding-interviews.py
29,836
3.609375
4
""" File name : codes-coding-interviews Description : implement the codes in coding interviews Author: cotyb Change Activity: cotyb establish this file in 1/31 2016 -------------------------------------------------------- """ #coding=utf-8 import time import Queue import gc import copy import heapq class Queue_Wi...
12c57cd12526bedccc93757f942321810ad38a29
me-smishra27/100-days-of-Python-Code-Challenge
/Day 4/Day4_practice.py
1,621
4.03125
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 14 23:30:12 2021 @author: smwin """ #RANDOMISATION '''It is important when program have a degree of unpredictibility e.g. games #Python has an inbuilt random module ''' import random random_integer = random.randint(1,10) print(random_integer) random_fl...
a5a1cdc6eb33ecd2af4612eeaf37e0841522aa31
JACustodioD/python-crud
/personas.py
305
3.90625
4
class Person: def __init__(self,name,age): self.name = name self.age = age def say_hello(self): print('Hello. My name is {} and i am {} years old'.format(self.name,self.age)) if __name__ == '__main__': person = Person('JACD','21') print('Age: {}'.format(person.age)) person.say_hello()
f9bb22eed2d6a6906786283cfcc8e40a875c7b80
Aaronphilip2003/Random-Password-Generator-GUI
/Password_Generator.py
1,143
3.703125
4
import random from tkinter import * def generatePassword(): length = e1.get() length = int(length) lowerCase = "abcdefghijklmnopqrstuvwxyz" upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" num = "0123456789" spec_char = "!@#$%^&*" all = lowerCase + upperCase + num + spec_char passw...
0fb49af318186cdb8673efe0658c2f6a4fe8abc7
bdjilka/dataStructure
/week4/phoneBook.py
2,478
3.65625
4
# python3 import datetime class Query: def __init__(self, query): self.type = query[0] self.number = int(query[1]) if self.type == 'add': self.name = query[2] def read_queries(): n = int(input()) return [Query(input().split()) for i in range(n)] def write_responses(...
540596d542d8f347791453f675fc0db468555096
miguelfAndrade/mancala_game_iart
/src/test.py
4,525
3.671875
4
import sys import math import time import mancala import ai def player_vs_pc(board, level): mancala.print_board_cmd_line(board) player = 0 winner = 0 moves = [] while(not mancala.game_over(board)): if(player == 0): print("Player " + str(player + 1) + " turn!") try...
26cc0a4cd013bf63b4a99e90bd6b83d364c10e05
samisosa20/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
534
3.96875
4
#!/usr/bin/python3 """ 2-read_lines.py """ def read_lines(filename="", nb_lines=0): """read x lines of a file Keyword Arguments: filename {str} -- file's name (default: {""}) nb_lines {int} -- how many lines to read (default: {0}) """ with open(filename, mode='r', encoding="UTF8") as...
88766907c535dd10aadf3686140abd31476c3c23
saigyouyou/leetcode
/71. Simplify Path.py
396
3.609375
4
#-- coding:utf-8-- # 注意,这个方法只适用于绝对路径 class Solution(object): def simplifyPath(self, path): path = path.split("/") ret = [] for i, j in enumerate(path): if j == '..': if len(ret)>0: ret.pop() elif j != '.' and j!='': ...
0d2ab0fbf9e391dcbbbc41165425ceb882fcbca9
saigyouyou/leetcode
/75. Sort Colors.py
673
3.515625
4
#-- coding:utf-8-- # 实际上就是数区块的数量,可以扫一遍写一遍 # 但是有个更巧妙的写法,扫的同时写数据 class Solution(object): def sortColors(self, nums): i = -1 j = -1 k = -1 n = len(nums) for x in xrange(n): if nums[x] == 0: k += 1 j += 1 i += 1 ...
5d59a99421b5985ae2222e77a172a32ca7c58f2f
MuhamadNawzad/Beginner-projects
/Ballout Counting.py
630
4.03125
4
polls = ["a", "a", "b", "b", "b", "b", "c", "a", "c", "c", "c"] candidates = [] votes = [] for member in polls: if member not in candidates: candidates.append(member) votes.append(1) else: votes[candidates.index(member)] += 1 max_candidate = [] max_vote = 0 for i in range(le...
25a25c2a06e44ec42b7ee622682840a2f42ecfe8
MuhamadNawzad/Beginner-projects
/Multiplication Table.py
349
3.5
4
for i in range(1, 10): table_row = '' for j in range(1, 10): table_row += str(i) + "*" + str(j) + "=" + str(i * j) + '\t' print(table_row) print() for i in range(1, 10): table = [] for j in range(1, 10): k = str(i) + '*' + str(j) + '=' + str(i * j) table.append(k) ...
de2c4ccd6f3aa4be47535efc592a766c544f6f4b
Wonixz/CodeWars_Python
/7KYU/Sum_of_two_lowest_positive_integers.py
146
3.53125
4
def sum_two_smallest_numbers(numbers): numbers.sort(reverse=True) low1 = numbers.pop() low2 = numbers.pop() return low1 + low2
3547274ddbf940fa11aa42a12baa2fe39c936eb3
Wonixz/CodeWars_Python
/5KYU/Write_out_numbers.py
1,151
3.609375
4
def number2words(n): d = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: '...
34985ea1fd28b326c4a0e59175e24cfab5e8906f
Wonixz/CodeWars_Python
/8KYU/What's_the_real_floor.py
128
3.546875
4
def get_real_floor(n): if n <= 0: return n elif n >= 13: return n-2 else: return n - 1
103cd3296f7eb80ddb70093cd24136b573339423
panhongsheng-eng/Python-study
/14.py
533
3.875
4
""" 类型转换 Version: 0.1 Author: 潘宏声 Date: 2021-10-11 """ a = 100 b = str(a) c = 12.345 d = str(c) e = '123' f = int(e) g = '123.456' h = float(g) i = False j = str(i) k = 'hello' m = bool(k) print(a) print(type(a)) print(b) print(type(b)) print(c) print(type(c)) print(d) print(type(d)) print(e...
c3102ca81f107494c8479b0ecf60af4889522c7c
emws0415/program_basics_python
/Chapter 1/20174067, 강범수, 1장 과제, 2번.py
2,039
4.1875
4
#컴퓨터공학과, 20174067, 강범수 print("컴퓨터공학과, 20174067, 강범수") from random import randint while True: print("ㅡㅡㅡㅡㅡMENUㅡㅡㅡㅡㅡ") print("1. UP & DOWN") print("2. Bulls and Cows") print("3. Exit") choose = int(input("> ")) # UP & DOWN if choose == 1 : print("\nㅡㅡㅡUP & DOWN!ㅡㅡㅡ")...
711578b3cddbf907b9fd6864a7d08391d0c497b0
XURUI89/package
/我的模块01.py
446
3.90625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 包含一个学生类,一个sayhello,一个打印语句 class Student(): def __init__(self,name="noname",age=18): self.name=name self.age=age def say(self): print("My name is {0}".format(self.name)) #记得空一行 def sayhello(): print("Hi,hello!") print("我是模块呀") ''' 三个平级...
93a4efcc14cc52ef105888f5987349fb30f94abc
afarahi/tatter
/tatter/TST_estimators.py
17,018
4.03125
4
""" Two-sample hypothesis test with Maximum Mean Discrepancy (MMD) method. Introduction: ------------- TATTER (Two-sAmple TesT EstimatoR) is a tool to perform two-sample hypothesis test. The two-sample hypothesis test is concerned with whether distributions p(x) and q(x) are different on the basis of finite samples dr...
ab9212a0d906ed58d995e8a1972536bf0cd755ae
AleMancilla/Juez-Patito-con-Python-3.7
/Problem_1058_ordenando_números.py
1,709
3.671875
4
# Descripción # Te diré varios números, y quiero que los imprimas ordenados ascendentemente. (el menor se imprime primero, y el mayor se imprime último). # Entrada # En una línea, se te dará un número entero 1≤n≤50 indicando la cantidad de casos de prueba. # En la siguiente línea, se te dará un número entero 1≤a≤50, ...
55f0f18cffaf015d19c427666f5763974eca848b
AleMancilla/Juez-Patito-con-Python-3.7
/Problem_1900_Series_reto_2.py
939
3.546875
4
# Problem I: Series Reto 02 # Time Limit: 1 Sec Memory Limit: 128 MB # Enviar: 9 Resuelto: 6 # [Enviar][Estado][Foro] # Descripción # Se te pide que para un N dado generes las N elementos de la siguiente serie: # # 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 5, 5, 8, 8, 13, 13, 21, 21, 34... # # Entrada # S...
3807e45d09f23244239ad8db2bdd786c0badc56e
Kota-N/python-exercises
/ex6StringLists.py
350
4.125
4
# An exercise from http://www.practicepython.org/ #6 String Lists import math word = input("Enter a word: ") middleIndex = math.floor(len(word)/2) firstHalf = word[0:middleIndex] lastHalf = word[middleIndex+1:] if firstHalf[::-1] == lastHalf: print(word, ": Your word is palindrome!") else: print(word, ": Y...
55498ebe82a87ab4ac9af4acf8f1f8a3f039df14
Kota-N/python-exercises
/ex9GuessingGameOne.py
982
3.953125
4
# An exercise from http://www.practicepython.org/ #9 Guessing Game One from random import randint def guessing_game(): answer = randint(1, 9) guess_count = 0 print('(Type "exit" to exit)') pick_a_number(answer, guess_count) def pick_a_number(answer, guess_count): user_guess = input("Please...
3417093c208c946b11d7e5ba67f33250f593d4dc
flanker-d/coursera_python
/course_1/week04/str.py
286
3.578125
4
class User: def __init__(self, name, email): self.name = name self.email = email def __str__(self): return '{} <{}>'.format(self.name, self.email) def _main(): jane = User('Jane Doe', 'janedoe@example.com') print(jane) if __name__ == "__main__": _main()
1ecc09cc2585246503b176356d14967d9d60b7d5
williangl/GECA
/Kama-sutra-0.1.py
826
3.75
4
#!/usr/bin/python3.4 import signal a = "abcdefghijklm" b = "nopqrstuvxwyz" c = list (input("Digite aqui o seu texto limpo: ")) #converte a string em lista para melhor funcionalidade no IF alfaA = "àáãäâ" alfaE = "èéẽëê" alfaI = "ìíĩïî" alfaO = "òóõöô" alfaU = "ùúũüû" for x in range(0, len(c)): #debug para alguns...
dec4603aa97c062e5bf02bc28554c7ed171b2bc7
wender0307/LearningPython
/Aula em video-desafio 30(Simulando cálculo de um radar de multas).py
192
3.78125
4
vcarro = float(input("você passou no radar a quantos kms?")) if vcarro >= 80: print("Você foi multado em {:.2f} R$!".format((vcarro-80)*7)) else: print("Você não foi multado!")
d71db487817a2fec22a537d41cae952aed2351be
elunacado/FISICA_FUERZA
/F/main.py
1,381
4.21875
4
def calculo(): ul = ["a = asceleracion", "m = masa", "f = fuerza"] print(ul) peticion=input("que quieres calcular?") def fuerza(): m = float(input("dime el valor de la m ")) a = float(input("dime el valor de la a ")) result=m * a print(result) aga...
da961da834c23c271cdb4c0eb716c89e5aaa7709
varmarakesh/aws-hadoop
/aws_hadoop/logger.py
1,179
3.734375
4
import logging import logging.handlers import os class Logger(object): """ logger class encapsulates functionality to create a logger that has formatter and handler defined. """ def __init__(self, log_file, log_dir=None): self.log_dir = log_dir self.log_file = log_file def _g...
e6b5214ba4a1cac14f573b2a33b3d59c9166c079
webintellectual/Python-Learning-Repo
/add_program.py
129
3.796875
4
a = input("Enter first number: ") a = int(a) b = input("Enter second number: ") b = int(b) print("Sum of these numbers is: ",a+b)
d33c8f62ef2ae5b2e594ec16bc1210e6f2d22c39
webintellectual/Python-Learning-Repo
/chap8_prob4_sumOfnviaFxn.py
121
3.703125
4
def sumOfn(n): if n==1: return 1 return n + sumOfn(n-1) n = int(input("Enter Number: ")) print(sumOfn(n))
997937c11ac334b1c965815765e64af576d94251
vollov/py-lab
/py-pos/dq/pos.py
541
3.65625
4
def discount(price): return 0.9 * price from trans.log import * items = ["DONUT", "LATTE", "FILTER", "MUFFIN"] prices = [1.50, 2.0, 1.80, 1.20] running = True while running: option = 1 for choice in items: print(str(option) + ". " + choice) option = option + 1 print(str(option) + ". Quit") cho...
580ba1936b745d92aa712977336ed0553b3c2055
vollov/py-lab
/src/exception/__init__.py
480
3.5625
4
class InvalidTokenError(Exception): pass mapx = {'a':3,'b':4} def print_key(x): if not mapx.has_key(x): raise InvalidTokenError('print_key():' + x + ' is not available in the token') else: print mapx[x] def test_all(): item_list = ['a','c'] try: for item in item_list: ...
2ad51299236a815232cca2df1de8eaa22603a0e3
vollov/py-lab
/src/json_test/test_json.py
1,974
3.65625
4
#!/usr/bin/python import json, unittest """Test json method dumps(object) -- translate obj to a JSON formatted str loads(str) -- translate a JSON str a Python object """ class Project: def __init__(self, oid=None, name=None): self.id = oid self.name = name def dict(self): return {...
966d2b74dc1fddc2dd5c96e056f8e21dc408e49f
vollov/py-lab
/src/pc/computer.py
1,129
3.96875
4
#!/usr/bin/python class Computer: def __init__(self, name, cpu): self.name = name self.cpu = cpu def setCpu(self,cpu): self.cpu = cpu def getCpu(self): return self.cpu class Cpu: def setSpeed(self, speed): self.speed = speed def g...
906289d11e5d2e0cb23ed09ed268916674ae689f
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/Hacker Chapter--Files/ex.04.py
2,959
4.25
4
'''Here is a file called labdata.txt that contains some sample data from a lab experiment. 44 71 79 37 78 24 41 76 19 12 19 32 28 36 22 58 89 92 91 6 53 7 27 80 14 34 8 81 80 19 46 72 83 96 88 18 96 48 77 67 Interpret the data file labdata.txt such that each line contains a an x,y coordinate pair. Write a function c...
eaedab6cec968ff2daf1313210d0713a8a397653
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 3/ex.04.py
1,137
4.375
4
'''Football Scores Suppose you’ve written the program below. The given program asks the user to input the number of touchdowns and field goals scored by a (American) football team, and prints out the team’s score. (We assume that for each touchdown, the team always makes the extra point.) The European Union has decid...
8751ce643df7e321eaf0f354e4e2d03641f56778
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 2/ex.08.py
326
4.28125
4
'''Write a program that will compute the area of a rectangle. Prompt the user to enter the width and height of the rectangle. Print a nice message with the answer. ''' ## question 9 solution width = int(input("Width? ")) height = int(input("Height? ")) area = width * height print("The area of the rectangle is", ...
cd9e9cf99f39ffab5a59d013375ebe2016503dae
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 11/Problem Set--Crypto/commandline.py
1,150
4.53125
5
''' commandline.py Jeff Ondich, 21 April 2009 This program gives a brief illustration of the use of command-line arguments in Python. The program accepts a file name from the command line, opens the file, and counts the lines in the file. ''' import sys # If the user types too few or too ma...
05c3c369328be9e64edb5f212b6083fea42048d9
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 8/how many times a substring occurs in a string.py
288
3.8125
4
def my_count(string, substring): string_size = len(string) substring_size = len(substring) count = 0 for i in range(0,string_size-substring_size+1): if string[i:i+substring_size] == substring: count+=1 return count print(my_count("aaaaaa", "aaa"))
a6ce568b9272c46fa98631deb2f70c759d9ecf43
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 11/list Type Conversion Function.py
181
3.65625
4
'''Python has a built-in type conversion function called list that tries to turn whatever you give it into a list. For example, try the following: ''' xs = list("Crunchy Frog") print(xs)
98bafea18532df29f7960c183211d9ceedee16ba
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 5/chapter 5 exercise.py
6,171
4.125
4
'''chapter 5 exercise 1''' import turtle def drawSquare(t, sz): """Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) t.left(90) wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("lightgreen") alex = turtle.Turtle() # create alex al...
f81af3b3ee07daecb713502882d235f0b62e0fca
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 11/List Comprehensions.py
628
4.5
4
'''The previous example creates a list from a sequence of values based on some selection criteria. An easy way to do this type of processing in Python is to use a list comprehension. List comprehensions are concise ways to create lists. The general syntax is: [<expression> for <item> in <sequence> if <condition>] wh...
287ebb477093fc937d854062a695a6d2bccce62d
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/Turtle/Add 100 color .py
488
3.875
4
''' how to put the loop code in for an RGB color that runs 100 different colors. ''' import turtle turtle.setup(width=600, height=500) turtle.bgcolor("blue") turtle.reset() turtle.hideturtle() turtle.speed(0) for i in range(1000): turtle.forward(i) turtle.right(98) turtle.exitonclick() ''' import colorsys #tu...
182984da17eef3f3203f67717a18d7d381fe8c82
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 12/Crypto/vigenere/Vigenere04.py
2,452
3.953125
4
#########################Vigenere密码######################### letter_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # 字母表 # 根据输入的key生成key列表 def Get_KeyList(key): key_list = [] for ch in key: key_list.append(ord(ch.upper()) - 65) return key_list # 加密函数 def Encrypt(plaintext, key_list): ciphertext = "" ...
b1b9abda174eecee080e0bc8b1fa8b424104ea3e
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 11/Problem Set--Crypto/strings2.py
442
4.15625
4
'''strings2.py Jeff Ondich, 2 April 2009 This sample program will introduce you to "iteration" or "looping" over the characters in a string. ''' s = 'two kudus and a newt' # What happens here? print('The first loop') for ch in s: print (ch) print() # And here? print( 'The second loop') k = 0 while k ...
6b49356fb32eee0f79ad56e806a41b549b7fc847
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 6/ex.08.py
337
4.28125
4
'''Now write the function is_odd(n) that returns True when n is odd and False otherwise. ''' from test import testEqual def is_odd(n): # your code here if n % 2 == 0: return False else: return True testEqual(is_odd(10), False) testEqual(is_odd(5), True) testEqual(is_odd(1), True) testEqual(...
5cb673fea5025758715006e4d11ceab8b3433456
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/Hacker Chapter-- Recursion/ex.04.py
298
4.09375
4
'''Find or invent an algorithm for drawing a fractal mountain. Hint: One approach to this uses triangles again. ''' def fibonacci_rec(n): if n == 0 or n == 1: return n else: return fibonacci_rec(n - 1) + fibonacci_rec(n - 2) print(fibonacci_rec(5)) print(fibonacci_rec(10))
1122da139c723e93234aba0ae35e3ec62f7504b6
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 11/Nested Lists.py
776
4.53125
5
'''A nested list is a list that appears as an element in another list. In this list, the element with index 3 is a nested list. If we print(nested[3]), we get [10, 20]. To extract an element from the nested list, we can proceed in two steps. First, extract the nested list, then extract the item of interest. It is ...
322a823e1b7f25b9f66594dab04f493bb8425123
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 9/ex.05.py
557
4.09375
4
'''Write a function that recognizes palindromes. (Hint: use your reverse function to make this easy!). ''' from test import testEqual def reverse(mystr): reversed = '' for char in mystr: reversed = char + reversed return reversed def is_palindrome(myStr): if myStr in reverse(myStr): re...
90826904bcc93f4f873b01354dd1dde2c201d0a3
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 11/ex.09.py
1,273
3.78125
4
'''Write a function replace(s, old, new) that replaces all occurences of old with new in a string s: test(replace('Mississippi', 'i', 'I'), 'MIssIssIppI') s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!' test(replace(s, 'om', 'am'), 'I love spam! Spam is my favorite food. Spam, spam, spa...
cbb24873533a63b0842920b265efe25987dca3f3
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 14/ex.06.py
1,691
4.125
4
''') (GRADED) Write a new method in the Rectangle class to test if a Point falls within the rectangle. For this exercise, assume that a rectangle at (0,0) with width 10 and height 5 has open upper bounds on the width and height, i.e. it stretches in the x direction from [0 to 10), where 0 is included but 10 is exclude...