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
183a7f2a4ed17abee62bb4e1bb2879469dbe126f
rickpaige/dc-cohort-week-one
/day3/lists-strings.py
435
4.1875
4
# List ['john', 'jane','sue'] greeting = "Hello" print(greeting[0]) # Prints H print(greeting[0::2]) # Prints Hlo # Converting print(greeting.lower()) print(greeting.upper()) # print(input("What is your name? ").lower()) # Split and Join hello = "Hello, my name is Josh".split(" ") # prints ['Hello', 'my', 'name',...
53ddcab9be956040254650d83daebb6a475b80b1
rickpaige/dc-cohort-week-one
/day2/Assignment/assignment1.py
439
4.0625
4
var_1 = input('First number = ') var_2 = input('What do you want to do? ') var_3 = input('Second number = ') if (var_2 == '+') : print(f'The answer is {int(var_1) + int(var_3)}') elif (var_2 == '-') : print(f'The answer is {int(var_1) - int(var_3)}') elif (var_2 == '*') : print(f'The answer is {int(var_1...
c69ffda84554533a4f3d8c9f0c5bb97fee29cde3
rickpaige/dc-cohort-week-one
/day3/loops.py
716
3.921875
4
#Loops names = ["John", "Jane", "Mary", "Mike"] for name in names: print(f'{name} Smith') def add(x, y): return x + y numbers_to_add = [[2, 3], [2 ,4], [2, 7], [1, 0], [2, 8], [2, 3]] for numbers in numbers_to_add: print(add(numbers[0], numbers[1])) for i in range(2, 100, 2): # range(start, stop, skip...
3a607132c17bfe3671ce8a3742dfe89bf8d879f8
morgan-monzingo/aoc-2020
/day16/day16.py
4,008
3.515625
4
with open("input.txt") as dayinput: puzzle_input_lines = [x for x in dayinput.readlines()] def create_boundaries(line, field_values): colon = line.strip().split(":") # print(colon) space_input = colon[1].strip().split(" ") # print(space_input) tup_1 = space_input[0].strip().split("-") # pri...
a46c93e67956208e6be4984a3663cb64a569689d
Sahar-Sheikhi/Social-Network
/json_functions.py
1,481
3.75
4
import json def read_json_file(path, key): """ This Function get a json file path and a key and return the value as a list path: represent a json file path key: represent a key in dict saved in json file return value of key which is a list """ try: with open(path) as handler: ...
d342dd1facaee18c2b8b72b35e7d6eae05d68714
Gilbert-Han/leetcode
/282.py
3,678
3.78125
4
# https://leetcode.com/problems/expression-add-operators/ ''' # Motivation/Strategy We need to find the recurrence between subproblems. Lets define terms as follows: Define number/NUM as [0-9] Define operator/OP as {+, -, *} Define expression/E...
92d7148fec81d087c21b2dbd29563f4e2cdfcae0
green-fox-academy/klentix
/Topic 8 Recursion & Fractal/max sum.py
333
3.96875
4
#Create a function called maxSum which expects an array of five integers # as an input parameter and returns the maximum values # that can be calculated by summing exactly four of the five integers. def listsum(numList): theSum = 0 for i in numList: theSum = theSum + i return theSum print(listsum(...
a79c0abad98bd68c1e9fe3cfc1e762635702b0f1
green-fox-academy/klentix
/Topic 10 Class and Object/ship.py
700
3.640625
4
import random from pirate import Pirates class Ship: def __init__(self): self.pirates = [] self.captain = None def fill_ship(self): if self.captain == None: captain = Pirates() self.captain = captain for i in range(1,random.randint(3,7)): pir...
d9c8c8a3df0f14ca628476838286a13762487cc5
green-fox-academy/klentix
/Topic 6 Drawing/purple step 3d.py
358
3.640625
4
from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() size = 10 # Reproduce this: # [https://github.com/green-fox-academy/teaching-materials/blob/master/workshop/drawing/assets/r4.png] def drawsquare (x,y,size): canvas.create_rectangle(x,y,x+size,y+size, fill='purple') ...
59411465b2b273b11446fa7cac2ddad93d1597be
green-fox-academy/klentix
/Topic 4 Function/print_param.py
286
3.96875
4
# - Create a function called `print_params` # which prints the input parameters # (can have multiple number of arguments) param = [(int(input("please input number: ")))] param2 = [(str(input("please input words: ")))] def print_params(): print (param + param2) print_params()
be154f3312dc868c2346ae368d6c7e21560f5a3a
green-fox-academy/klentix
/Topic 8 Recursion & Fractal/strings again.py
321
3.90625
4
#Given a string, # compute recursively a new string where # all the 'x' chars have been removed. def remove(char, mystr): if not mystr: return '' if char == mystr[0]: return remove(char, mystr[1:]) else: return mystr[0] + remove(char, mystr[1:]) print(remove('i','this is a sample')...
d1058e9ad466519a3af89658094f801e927390c7
green-fox-academy/klentix
/Topic 6 Drawing/four rectangles.py
532
3.515625
4
from tkinter import * import random root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() def random_color(): return random.randint(0,0x1000000) for x in range (0,4): color = '{:06x}'.format(random_color()) x1 = random.randint(10,300) y1 = random.randint(10,300) x2 = random.ra...
26b12a548e66dec8d7839bd35c78cf69b7ad7839
green-fox-academy/klentix
/Topic 3 Expression and Control Flow/print even.py
131
3.921875
4
# Create a program that prints all the even numbers between 0 and 500 for i in range(0,500,2): #if (i%2==0): print (i)
b886cea1351c85df755d67cab1c9fffd406b0437
green-fox-academy/klentix
/Topic 4 Function/factorial.py
133
3.859375
4
# - Create a function called `factorio` # that returns it's input's factorial def factorio(): print('factorial') (factorio())
9cba4b14e66c7d433ebbe392285ee68cedc61cfd
green-fox-academy/klentix
/Topic 11 Inheritance/garden/the_garden.py
1,849
3.75
4
class Flower: flower_absorb = 0.75 def __init__(self, color): self.color = color self.water = 0 class Tree: tree_absorb = 0.4 def __init__(self, color): self.color = color self.water = 0 class Garden: def __init__(self): self.plants = [] def add(sel...
3a7e5870dc242615ee553d0f00295ace995c470a
green-fox-academy/klentix
/Topic 5 Data Structure/List Introduction 1.py
810
4.5625
5
namelist = ['William'] namelist.extend(['Jony', 'Amanda']) # add on multiple items in the list print("No. of name", len(namelist)) # print total number of items print("Name list: ", namelist) # print out each element print("the 3rd name is:", namelist[2]) #iterate through a list and print out individual name for ...
400c567e0c17e71ac459cc633c43839f44ec41db
green-fox-academy/klentix
/Topic 3 Expression and Control Flow/hello users.py
187
4.125
4
# Modify this program to greet the user instead of the World! # The program should ask for the name of the user user_input = input("insert your name: ") print ("Hello,", user_input,"!")
6811ffa47a657d54f16a9ba09765341d36d72d5b
green-fox-academy/klentix
/Topic 6 Drawing/colored box.py
414
3.65625
4
from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() colorline1 = canvas.create_line(50,50,50,250,fill="red") colorline2 = canvas.create_line(50,50,250,50,fill="blue") colorline3 = canvas.create_line(250,250,250,50,fill='green') colorline4 = canvas.create_line(250,250,50,25...
656f4b9b7be0c6220592ebf1d7e942bbbe399959
burrav93/python-challenge
/PyBank/main.py
1,716
3.6875
4
import csv inputFile = "C:/Users/bvkka/Desktop/python-challenge/PyBank/budget_data.csv" outputFile = "C:/Users/bvkka/Desktop/python-challenge/PyBank/outputResult.txt" totalMonths = 0 totalAmount = 0 profitLosses = [] change = [] date =[] with open(inputFile) as budgetData: reader=csv.Di...
088daf35023165ca782cbde2f5a681d92c8a6bc7
luiscalva-lpsr/class-sample
/hw.py
230
3.546875
4
import turtle jeremy = turtle.Turtle() lines = 0 while lines < 3: jeremy.left(110) jeremy.forward(100) jeremy.left(110) jeremy.forward(100) jeremy.left(110) jeremey.forward(100) lines = lines + 1 turtle.exitonclick()
f8749a7b45858067b95779c74889a89b848b5fa1
mudgutco/monopoly-py
/Player.py
3,943
4.125
4
# Title: Monopoly - Players # Created by: Leighton Lauton # Date: 17/09/2019 # SUMMARY # This python file will set up each player with the required amount of cash # and the token selection. The Bot will also be setup based on the difficulty chosen by # the players. # Module Imports from random import randint import p...
d4fe51e51e9a707815f98e9fffb35d3dfbd5187b
kamal09rumba/hackerrank
/Algorithms/warmup/a-very-large-sum.py
531
3.875
4
#!/usr/bin/python ##Input Format #The first line of the input consists of an integer 'N'. The next line contains 'N' space-separated integers contained in the array. ##Output Format #Print a single value equal to the sum of the elements in the array. import sys def aVeryBigSum(n, ar): # Complete this function ...
fbbae51d5706084eb90a93512ed2287825fd2d3e
kamal09rumba/hackerrank
/30DaysOfCode/python/Day21-Sorting/answer.py
959
3.9375
4
#!/bin/python import sys n = int(raw_input().strip()) a = map(int, raw_input().strip().split(' ')) # Write Your Code Here class BubbleSort: def __init__(self): self.numSwaps = 0 self.array = [] def swap(self,n,a): arrayLength = len(a) lastUnsorted = arrayLength-1 isSor...
6d78206ea9b7730eb307f13d82bdd9a7a6973679
kamal09rumba/hackerrank
/Algorithms/warmup/plus-minus.py
500
3.515625
4
#!/usr/bin/python import sys def plusMinus(arr): p = 0 n = 0 z = 0 arr_len = float(len(arr)) for i in arr: if i > 0: p += 1 elif i < 0: n += 1 else: z += 1 fp = float(p) / arr_len fn = float(n) / arr_len fz = float(z) / arr_le...
ee9e8e0d45b1d7259a4d4c48a453beebecf12e6b
kamal09rumba/hackerrank
/30DaysOfCode/python/Day2-Data-Types/answer.py
281
3.515625
4
#!/usr/bin/python i = 4 d = 4.0 s = 'HackerRank' a=12 b=4.0 c=' is the best place to learn and practice coding!' a=int(raw_input('Enter a Integer Value: ')) b=float(raw_input('Enter a Float/double Value: ')) c=str(raw_input('Enter a String Value: ')) print i+a print d+b print s+c
4ff2d5e8effe887f72c055266dd095d3b9ce57e0
ravindra4ravi/user
/login/core/linked_stack.py
1,389
4.0625
4
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.top = None super(Stack, self).__init__() def push(self, node): if self.is_empty(): self.top = node self.top.next = None ...
ad1ca00f84c6c3100ba8fa0dfbc01e68d7d48035
cuzai/pythonStudy
/study/numpyTest.py
1,300
3.53125
4
import numpy as np li = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] array = np.array(li) # array() : 리스트를 행렬화한다. Dynamic typing : 리스트 내의 원소는 하나의 형으로 통일해야 함 print(array, '\n') print(array + 1) print(array.shape) # 행렬이 몇 콤마 몇인지 알려줌(앞이 더 큰 차원) print(array.ndim) # 행렬이 몇차원인지 print(array.size) # 행렬 내...
0aaa5cad21694f1f82c5e1d0a3dd4b70542dc319
cuzai/pythonStudy
/data/pythonDataStructure.py
3,432
4.09375
4
# a = 'hello' # # print(type(a)) # print(a[0]) # print(a[0 : 3]) # 앞에 인덱스 ~ 뒤에 인덱스-1 까지 호출 # print(a[-1]) # # for i in a : # print(i) # 리스트 자료형(순서o, 중복o, 수정o, 삭제o) # 선언 a = [] b = list() c =[0, 0, 1, 2] d = [0, 1, 'car', 'apple', 'apartment'] e = [0, 1, ['car', 'apple', 'apartment']] # 중첩 리스...
ce86046945bc3f35b226e37d29f8be3d4f36b893
PramitaPandit/Rock-Paper-Scissor
/main.py
2,492
4.4375
4
#Rock-Paper-Scissor game # import random #step1: Stating game instructions print('Rules of Rock-Paper-Scissor are as follows:\n Rock v/s Paper -> Paper wins \n Rock v/s Scissor -> Rock wins \n Scissor v/s Paper -> Scissor wins ') # Step2: Taking user input user = input('Enter your name: ') while True: player_cho...
fccdb7c9df6b1b947d507fb01e06cf7e588a4adc
qsong9527/sdet17
/Ding/runnian.py
476
3.921875
4
# 判断一个数字是否为基数 # 基数: 不能被2整除的数字 # 闰年 year = int(input("请输入一个年份:")) if year > 0: if (year % 4) == 0: if (year % 100)== 0: if (year % 400) == 0: print("{0} 是闰年") else: print("{0} 不是闰年") else: print("{0} 是闰年") else: prin...
00f972e2c7de7405cf07190049b1ae919b4803a8
qsong9527/sdet17
/Ding/demo_ifelse.py
176
4
4
a = int(input("请输入数字1:")) b = int(input("请输入数字2:")) if a > b: print(f"{a} > {b}") elif a < b: print(f"{a} < {b}") else: print(f"{a} = {b}")
c021c17bd271cc4350bec6ec872b6e200b5bde0e
qsong9527/sdet17
/lidezheng/while.py
76
3.953125
4
x = 1 while x <=10: print(f"{x}:hello") x += 1 print("打印完毕")
aeae1bf836acdb9f550373e22da09de1e81886d8
qsong9527/sdet17
/tianhao/demo2.py
169
3.6875
4
a=int(input("请输入一个年份")) if a%4==0 and a%100!=0: print(f"{a}是闰年") elif a%400==0: print(f"{a}是世纪闰年") else: print(f"{a}是平年")
ace70531be1bb512f429a056b986dc363101c3cc
qsong9527/sdet17
/fubo/demo/demo ifelse.py
173
4.0625
4
a = int(input("请输入一个数字")) b = int(input("请输入一个数字")) if (a<b): print(f"{a}<{b}") elif (a<b): print(f"{a}>{b}") else: print(f"{a}<{b}")
d4f9a5afccb212f296f23815839d2b5bb578bcd8
GucciTheCarpenter/CUSP
/5003_PUI/04/problem1.py
708
3.859375
4
def solveOnlyLists(inputList): uniqueList = [] for i in inputList: if not i in uniqueList: uniqueList.append(i) return uniqueList def solveDict(inputList): uniqueList = [] uniqueDict = {} for i in inputList: if not i in uniqueDict: uniqueDict[i] = i uniqueList.appe...
00c288427f362bf4795cac5b26596e82b23de4ea
GucciTheCarpenter/CUSP
/5003_PUI/04/problem2.py
1,269
3.90625
4
# Performs search in unsorted L. # L might not be sorted. Can't use sorting to solve this. def searchGreaterNotSorted(L, v): greater = 0 for i in L: if i > v: greater += 1 return greater # Performs search in sorted L (ascending order). # L is sorted. def searchGreaterSorted(L, v): greater = 0 for i...
3dfecdcc2e10e2a8726896802dbed82b8ceef96c
FX-Wood/python-intro
/name_length.py
291
4.375
4
# Exercise 3: # Write a script that asks for a name and prints out, "Your name is X characters in length." # Replace X with the length of the name without the spaces!!! name = input('Please enter your name: \n > ') print(f"Your name is {len(name.replace(' ', ''))} characters in length")
04a659e77718a85fad089298850585a77cdb9d00
FX-Wood/python-intro
/collections/print_names.py
246
4.40625
4
# Exercise 1 # Create a list named students containing some student names (strings). # Print out the second student's name. # Print out the last student's name. students = ["Fred", "Alice", "Bob", "Susie"] print(students[1]) print(students[-1])
717c325b58c4e4ffc3865dcad0e8aa2e5a0eee81
deepakkadarivel/python-programming
/pay_more_3_1.py
437
3.890625
4
hrs = input('Enter Hours:') rate = input('Enter Rate:') actual_work_hrs = 40 extra_hrs = 0 try : work_hrs = float(hrs) except: print('Error, please enter numeric input') try : work_rate = float(rate) except: print('Error, please enter numeric input') if work_hrs > actual_work_hrs: extra_hrs = wor...
c7dbc874de58b7713d58d422a399f09efebbe726
deepakkadarivel/python-programming
/7_file_processing/7_2_search_in_file.py
946
4.28125
4
""" “Write a program to prompt for a file name, and then read through the file and look for lines of the form: X-DSPAM-Confidence:0.8475” Pseudo code 1. Read file name from user 2. open file 3. Handle No file exception 4. Iterate through files for text and increment count 5. print total...
6f66c1c584bbd31f3bc9f561da2cb0e009b5486c
deepakkadarivel/python-programming
/12_network/12_05_beautiful_soup_links.py
407
3.5
4
""" Retrieve links using Beautiful soup lib """ import urllib.request import ssl from bs4 import BeautifulSoup ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter url: ') html = urllib.request.urlopen(url, context=ctx).read() soup = BeautifulSoup(htm...
f2d750dadce5e8cf3359b18e806ba763842042e9
deepakkadarivel/python-programming
/6_1_reverse_string.py
567
4.40625
4
""" Write a while loop that starts at the last character in the string and works it’s way through first character in the string, printing each letter in a separate line except backwards. TODO 1: Accept a string from io TODO 2: Find the length of the string TODO 3: decrement len and print charac...
8915bb5963f3b0accb33e02d68fba4a8c3bf7628
deepakkadarivel/python-programming
/6_2_letter_count.py
757
4.375
4
""" Find the count of a letter in a word. Encapsulate the code in a function named count, and generalize it so that it accepts the string and letter as an argument. TODO 1: Accept input for a word and letter to search for. TODO 2: Define a count function that accepts word and letter as parameter to cou...
d80b0aa7da20f44c16e7ecbaab2af8a995e69ebd
danbar/fglib
/fglib/edges.py
1,372
3.6875
4
"""Module for edges of factor graphs. This module contains classes for edges of factor graphs, which are used to build factor graphs. Classes: Edge: Class for edges. """ from . import nodes class Edge: """Edge. Base class for all edges. Each edge class contains a message attribute, which sto...
926459f21b4911ecf016735ba83af2c2a1c66311
Aayush977/nim-game
/nim_functions.py
3,038
3.9375
4
import random players = [] count = [] count_number = [] name = ['A','B','C'] asterisk = "*" # defining a player def player(): player1=input("Enter the name of the first player") players.append(player1) player2 = input("Enter the name of the next player") players.append(player2) # cre...
f788b258b7e4820673ca63bfb4293d34aef1ad8f
LuisaoStuff/Entrega-1
/Ejercicio 5.py
701
4.15625
4
# Escriba un programa que pregunte cuántos números se van a introducir, pida esos # números, y muestre un mensaje cada vez que un número no sea mayor que el primero. limite=int(input("\n ¿Cuántos números va a introducir? ")) # Validación while limite<=0: limite=int(input("\n ¡Eso es imposible!\n ¿Cuántos números...
5e746533aaaa2c7b62736997b7fc54ad0237b21d
wangyu6/book2
/chapter1/tkinter103.py
394
3.671875
4
from tkinter import * from tkinter.messagebox import showinfo def reply(name): showinfo(title= 'reply',message = 'hello %s ! ' %name) top = Tk() top.title('echo') top.iconbitmap('1.ico') Label(top,text = 'enter your name,').pack(side = TOP) ent = Entry(top) ent.pack(side = TOP) btn = Button(top,text = "subbmit"...
1283ab1649af4699246172c5d9677cc5fef8f1ad
shomoos-aldujaily/Library
/CreateTables.py
810
3.640625
4
import sqlite3 db=sqlite3.connect('library.db') try: cur =db.cursor() cur.execute('''CREATE TABLE BOOK ( BookID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT (120) NOT NULL, Description TEXT (300));''') cur.execute('''CREATE TABLE AUTHOR ( AuthorID INTEGER PRIMARY KEY AUTOINCREME...
25e3fa5f5c10a5ed50bdcc5f8b656b96d116d9cc
marisagross/Week-Two-Assignment
/Program2.py
231
3.890625
4
# __author__ = 'Marisa Gross' # CIS 125 # Program2 # # Converts Fahrenheit to Celsius F = eval(input("Please enter a temp in Fahrenheit: ")) C = (F - 32) * 5 / 9 print("The temp ", F, "in Fahrenheit is equal to ", C, " Celsius")
91ca1785abeaaca69bfc928e05dcccd7749d2d2c
HammadTheOne/Alignment-Tool
/Alignment Tool.py
621
3.90625
4
"""Alignment Tool""" import Bio SEQUENCE = '1' ALIGNMENT = '2' PHYLOGENY = '3' def prompt_filetype() -> str: filetype = input("""Choose the type of file you are dealing with: [1] - DNA or Protein Sequence [2] - Pairwise or Multiple Sequence Alignment [3] - Phylogenetic Tree \n """).stri...
a47642e696ea6cbd11dd3600b3697e8a9d29d002
ibooij/euler
/problem9.py
482
4.0625
4
#!/usr/bin/python """ Problem 9 25 January 2002 A Pythagorean triplet is a set of three natural numbers, a b c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ import operator import sys for a in ra...
c7afcaceed0d90da2ed5f8a5c6e5d0bf93709f35
baiochi/LetsCode_Projeto3
/source_joao/TestaEmprestimoBikes.py
10,648
3.875
4
# ambiente de testes unitários import unittest import math from my_class import * from datetime import datetime as dt """ Consulta rápida, apagar ao final. Method Equivalent to .assertEqual(a, b) a == b .assertTrue(x) bool(x) is True .assertFalse(x) bool(x) is False .assertIs(a, b)...
1e2291ef96bc58f47a1a3afd03731e5008fb4dce
WuLC/NowCoder
/剑指offer/数组中重复的数字.py
597
3.5
4
# -*- coding: utf-8 -*- # Created on Mon Mar 12 2018 10:2:54 # Author: WuLC # EMail: liangchaowu5@gmail.com # O(1) space class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, nums, duplication): for i in xrange(len(nums)): while nums[i] != i: ...
dfd1bb06dab5349b50337c08c158cc88d7e08d6a
WuLC/NowCoder
/剑指offer/合并两个排序的链表.py
962
3.609375
4
# -*- coding: utf-8 -*- # @Author: WuLC # @Date: 2017-04-26 19:50:12 # @Last modified by: WuLC # @Last Modified time: 2017-04-26 19:52:01 # @Email: liangchaowu5@gmail.com """ 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 """ # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self....
e48fd7d3b5dac804b6fb8b264d2ef000b996f073
WuLC/NowCoder
/剑指offer/字符流中第一个不重复的字符.py
634
3.703125
4
# -*- coding: utf-8 -*- # Created on Sat Mar 10 2018 9:10:12 # Author: WuLC # EMail: liangchaowu5@gmail.com # 可在插入任意时刻找到第一个只出现一次的字符 from collections import deque, defaultdict class Solution: def __init__(self): self.queue = deque() self.count = defaultdict(int) def FirstAppearingOnce(s...
a966019daa7dcb5858531ade89cb3c3d900f7621
WuLC/NowCoder
/剑指offer/矩形覆盖.py
576
3.640625
4
# -*- coding: utf-8 -*- # @Author: WuLC # @Date: 2017-04-23 19:32:26 # @Last modified by: WuLC # @Last Modified time: 2017-04-23 19:33:32 # @Email: liangchaowu5@gmail.com """ 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。 请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? """ # dp, similar to Fibonaci Array class Solution: def rectCover(s...
6a154af4ddbf024665295fdfab72fe4d6f828de8
Jrbrown09/Brown-Assignment5
/.vscode/exercise6.py
2,138
4.4375
4
from helpers import * ''' Exercise 6 Calories from Fat and Carbohydrates This program calculates the calories from fat and carbohydrates that the user consumed. The calorie amounts are calculated using the input from the user in carbohydrates and fat. ''' ''' Define the 'main' function ''' def main(): fat_gram...
32b144e97cd8f10500b1848ebd8af4599ae66d12
markvassell/Python
/test/multiplication_table.py
1,248
4.21875
4
import math print("This is test multiplication table: Still in progress") file_name = "Multiples.txt" try: #opens a file to write to mult_file = open(file_name, "w") while (True): try: inp_range = int(input("Please enter how many multiplication tables you would like to generate: ")) ...
62c4e4d4ef2447f1fccb4290ac553c88d3e40d95
markvassell/Python
/PaintJob/paintjob.py
1,938
4
4
# Paint Job Estimator # paintjob.py import math hourly_labor_cost = 42.50 # dollars per hour unit_of_wall_area = 125 # square feet requiring 1 gallon of paint hours_labor_per_unit = 8 # hours of labor per unit of wall area print ('Paint job cost estimator') do_estimate = True while(do_estimate): print ('...
b7a5497b2b6515cade12d76e04301f469aa0c116
Aollarve/Wallbreakers
/Week_1/hamming-distance.py
621
3.515625
4
class Solution: def hammingDistance(self, x: int, y: int) -> int: s_x = "" s_y = "" if x == 0: s_x = "0" if y == 0: s_y = "0" while(x): if x & 1 == 1: s_x = "1" + s_x else: s_x = "0" + s_x ...
63be8173d995fcc1f73506b2f29569892c84b4f3
pkage/perceptron
/gym.py
1,718
3.609375
4
#! /usr/bin/env python # Perceptron training gym # Patrick Kage 2015 import perceptron, random from graphics import * class Trainer(): inp = [] ans = 0; def __init__(self, x,y,ans): self.ans = ans; self.inp = [x,y,1]; # bias input built in class GraphLine(): def __init__(self, slope, yint): self.slope ...
d2cd07df5281f38035c6fef33b53096cb09a7164
thecodinghyrax/Bible_page_update
/secondpass.py
2,675
3.703125
4
# Run this file second only after the firstpass.py file is ran!!!! # The goal of the secondpass script is to convert the firstpassout.txt file into # a JSON file that can be used by later scripts. # Globals day = 1 total_lines_for_this_day = 1 currentLine = "Place holder" def secondFunc(leap): fI = open("firstp...
0529ff873bd7e0d6503543c9f77c51b6a9e6bd57
zumalsaggaf/rockProject2
/rockProject2.py
3,816
3.78125
4
import random moves = ['rock', 'paper', 'scissors'] class Player: def move(self): return 'rock' def learn(self, my_move, their_move): pass class RandomPlayer(Player): def move(self): result = random.choice(moves).lower() return result def learn(s...
c52dac3f89683c8ade4f3bc4f81b4a9ff350cc1d
surendhar-code/python_practice
/program1.py
306
4.3125
4
#python program to interchange first and last elements in a list. def firstlast(list1,n): beg=list1[0] end=list1[n] print("The first and last element of the list {0} is {1} and {2}\n".format(list1,beg,end)) list1=list(range(0,5)) print(list1) n=(len(list1))-1 firstlast(list1,n)
15760a8ab3ecfc4ad98636dbf06117752f256f15
rekonin332/playground
/loop.py
186
3.765625
4
# -*- encoding:utf-8 -*- L = ['Bart','Lisa','Adam'] for l in L: print("hello, %s"%l) i = 0; while True: print("hello,{}".format(L[i])) if i<len(L)-1: i = i + 1 else: break
25f048886c0a838e6a77aa5618b96d7188e51da1
alaakh42/DataStructure_and_Algorithms_inPython
/oop_examples.py
1,821
4
4
class creditCard: """A consumer credit card""" def __init__(self, customer, bank, account, limit): """Create a credit card instance""" # The initial balance is zero. # customer the name of the customer (e.g., John Bowman ) # bank:the name of the bank (e.g., California Savings ) # acnt:the acount identifi...
60b5cb899cef0911bd7d7a775cfbb7ea557aa01f
Robdowski/code-challenges
/running_sum_1d.py
739
4.125
4
""" This problem asks to keep a running total of the sum of a 1 dimensional array, and add that sum to each item in the array as we traverse. To do this, we can simply declare a variable, running sum, and add it to each item in the array as we traverse. We need to add the sum to the item in the array, while storing th...
9da766fbd85bcdd850ab9425b78c65e4af9e5bdc
mjmaurya/onemonth
/tip.py
547
4
4
bill=int(input("enter the bill Amount\n")) print("Coose one option from following list") print("1. 15%") print("2. 18%") print("3. 20%") print("4. More than given above\n") option=int(input()) if option==4: tip=input("Enter Tip amount\n") if '$' in list(tip): x=tip.replace('$','') x=int(x) ...
6054092ee19e466d0d0b3ad3da64f13f9e3f7bc9
Programacion-Algoritmos-18-2/2bim-clase-01-bryckstar
/ejercicio-clases/manejo-excepciones/main.py
373
4.0625
4
""" Ejemplos de Manejo de Excepciones """ try: edad=input("Ingrese su edad: ") edad=int(edad) print("Su edad es: %d"%(edad)) except ValueError as e: print("Existe un error(%s): %s!" % (e.__class__,e)) except NameError as e: print("Existe un error (%s): %s!" % (e.__class__, e)) """ except Exception as e: prin...
2d516c584352f0d835fc8f9f7dc076fd032e8af3
N0l1Na/Algorithms_Python
/PIL006/PIL006.py
1,306
4.25
4
""" PIL - The exercise is taken from the Pilshchikov's Pascal problem book Task 8.7 page 40 Regular types: vectors Using the Gender and Height arrays, determine: a) The name of the tallest man b) The average height of women Creator Mikhail Mun """ import random array = [] total_height_women = 0 amount_women = 0 ...
5ba44193db411ad903dea3bec44f6404d8c5b85d
N0l1Na/Algorithms_Python
/PIL001/point б.py
396
3.84375
4
""" PIL - задача взята с задачника Пильщикова по Паскаль Task 4.10 page 20 Operators Дано число x, необходимо напечатать в порядке возрастания: chx, 1+|x|, (1+x^2)^x """ from math import * x = int(input("Введите число x: ")) f = [cosh(x), 1+abs(x), pow((1+pow(x, 2)), x)] f.sort() print(f)
58ecd66187ab0868deab59bed38acf3d531cba91
sagarattuluri/Test1
/health.py
248
3.84375
4
def padding( return ): return.append([10,20,20]); print("values inside function is: ", return) return return = [5,5,5]; print("values outside function is", return) padding(return); print("values outside function is: ", return)
0b3cd04d9939a5024e2c7b22a2b98f1048ff9c76
rehomewebapp/REhome
/WebApp/models/building/geometry.py
1,100
3.671875
4
""" The geometry module is used to create and manipulate the geometry of a building. Output should consist of all opaque and transparent areas, their types (roof, outside_wall, window) and their orientations. """ from pyproj import Geod import csv data_path = "WebApp/models/building/data/" def area_from_geopolygone...
9b33f869fb7461248039c2ce556a7023cad0c483
LeonOram/Lists
/Dev 1.py
810
4
4
#Leon Oram #16-12-2014 #Dev task 1 import random def ask(select,caps,countr): country = countr[select] capital = caps[select] answ = input("The capital of {0} is ... ? ".format(country)) answ = answ.title() if answ == capital: print("That is correct!") else: pri...
f611690b094d2cbd4fa55cd341b26b986f52e2d8
StavC/TrainingReporter
/ExerciseArray.py
820
3.8125
4
class ExerciseArray(object): def __init__(self, name): self.name = name self.records_array = [] def add_record(self, Record): self.records_array.append(Record) def pop_record(self): self.records_array.pop() def print_array(self): for record in self.records_arr...
c2da9efa0ee554c97805b9dd4cda4e8e57e6ecf3
bmartin5263/Uno_Basic
/deck.py
1,188
3.640625
4
from card import Card import random class Deck(): ''''shuffle' (bool) : shuffle deck.''' colors = ('red', 'yellow', 'green', 'blue') values = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'R', '+2') def __init__(self, populate): '''Initializes proper deck of 108 Uno Cards.''' ...
eb07486de66e240a854d2ee273807868b9a518e5
DrJamesCoates/Mars-Rover
/mars_rover.py
8,010
4.1875
4
# import necessary libraries import sys def main(): # make rover class class Rover: def __init__(self, x, y, compass): self.x = x self.y = y self.compass = compass # list for instances of class rover and their final positions rover_end_pos = [] # c...
e5f2d41c117bbaf1d52e61a1c01a73746a539ce0
CorbinGraham/osrs-discord-trading-bot
/lib/analyzer.py
4,582
3.78125
4
import csv import math from datetime import datetime, timedelta # Date_today is left as a datetime object so we can do date calculations from it. date_today = datetime.date(datetime.now()) date_yesterday = str(date_today - timedelta(days=1)) date_two_days_ago = str(date_today - timedelta(days=2)) date_one_week_ago ...
71e1d2fb85f6b3a4aac4f65976507850290b94f2
hustbill/python-auto
/learn/hard-way/pow.py
126
3.78125
4
class Pow def power(x, n): while (n > 0) : y= *x n--; print("%d ", y) if _name_ == '_main_': power(x,n)
af8d0e1fd7bee085844eafe693bace7e4bdb510f
hustbill/python-auto
/learn/data-science-from-scratch/ch2-python-basic/generators_iterators.py
352
3.875
4
def lazy_range(n): """a lazy version of range""" i = 0 while i < n: yield i i += 1 for i in lazy_range(10): #do_something_iwth(i) print i def natural_numbers(): """returns 1, 2, 3, ...""" n = 1 while True: yield n n += 1 lazy_evens_below_20 = (i for i i...
ce019c6a7fbdd07579e5b9f589a75e0d1a6307bf
Atharv-Pareek7269/Beginner-Projects
/Faulty calculator.py
1,290
4.09375
4
#Faulty calculator security1 = 72698582 print("Enter your first number: ") num1 = int(input()) print("Enter your second number: ") num2 = int(input()) print("Enter Which operation you want: +, -, *, / ") num3 = input() print("If you want answer to question, first type security key. To type security key enter (y) ...
162a4cf742c3e73fd26783829f2dc60f1988e764
iamankitroy/Rosalind
/Bioinformatics_Stronghold/FIB-Rabbits_and_Recurrence_Relations.py
267
3.6875
4
import sys months, litterSize = int(sys.argv[1]), int(sys.argv[2]) def rabbits(month): if month == 0: return 0 elif month == 1: return 1 else: return rabbits(month - 1) + rabbits(month - 2)*litterSize print(rabbits(months)) # Ankit Roy # 16th April, 2021
c1546dbc5cb69f2aa8bffc7100d5782a546ca2e3
DavidDDai/HelloWorld
/hello.py
105
3.5
4
# -*- coding: utf-8 -*- import time if time.strftime("%H:%M")!="20:25": print("hello world!",end="")
f40ee436eb93d20437572358ee302b208d2d5686
heronyang/pychain
/chain.py
2,335
4.03125
4
""" Implementation of the simple and basic block chain objects. """ import hashlib from datetime import datetime DIFFICULTY = 4 class Block(): """ Block stores its own payload, the timestamp of creation, and the hash of the previous block. The hash of a block is calculated by considering all the prop...
5c19ac5b7a1b9706005fa20d79705a4159fb2b2d
S-GH/Keras_Basic
/keras13_ensemble2.py
3,844
3.640625
4
# 두개의 모델을 이어서 세개의 모델을 output import numpy as np x1= np.array([range(1,101),range(101,201),range(301,401)]) x2 = np.array([range(1001,1101),range(1101,1201),range(1301,1401)]) y1 = np.array([range(1,101), range(101,201), range(301,401)]) y2 = np.array([range(1001,1101), range(1101,1201), range(1301,1401)]) ...
f50be6f9e9ca26e9798ccae863182aae6a7a79a3
SashaJohnson123/introduction_to_python
/variables/user_input.py
234
3.84375
4
#User Input name = input("What is your name? ") print(name) age_prompt = f"Hi {name}, how old are you? " age = input(age_prompt) years_until_100 = 100 - int(age) print(f"Wow! {name}, you will be 100 in {years_until_100} years!")
3e4ce1aa7ffd6fc8365800767121069c313ff9b7
SashaJohnson123/introduction_to_python
/loops_exercises.py
1,566
4.25
4
# #Question 1 # add via append # my_list = [1, 4, 2, 1] # # while loop + # while len(my_list) < 5: # my_var = input("give me a number? ") # my_list.append(my_var) # print(my_var) # print(my_list) # print(my_list) #Question 2 #print each item in the list + amount: # pets = [ # ["Roary", "ro...
ab31adcd188b32b87a7d984ff966e53ae1cb2f4d
Doreen162/Python-Exercises
/Additional Exercise.py
223
3.53125
4
# salary employee = 0.295 other = 0.25 gross_monthly_salary = int(input("enter gross_monthly_salary: ")) price = float(input("enter the price of a laptops:R")) bonus = (price * 10) commission = (price * 3000 * price)
b20bbf873c12b58abbdeaaf938cc45daf3c98800
kamibarreto/Python_Exercicios
/WHILE/Progressão_Aritimedica3.0.py
319
3.96875
4
termo = int(input("Digite o primeiro termo da PA: ")) razão = int(input("Digite o valor da razão: ")) elementos = int(input("Quantos elementos deseja inserir na tela: ")) acumu = 0 pri = termo while acumu < elementos: print("{} - ".format(pri), end=" ") pri += razão acumu += 1 print("FIM")
17f3955cf5ba710849298563339ecf90b1b22a31
kamibarreto/Python_Exercicios
/WHILE/Maior_Menor_Valor.py
581
3.796875
4
decisão = "S" acumu = maior = todos = 0 menor = 90000000 while decisão not in "Nn": num = int(input("Digite um número: ")) decisão = str(input("Deseja Continuar? [S/N] ")) while decisão not in "SsNn": decisão =str(input("Opção invalida, Deseja continuar? [S/N] ")) if num > maior: ...
b2021a96569aa07b191481181536a871e8136dfb
kamibarreto/Python_Exercicios
/WHILE_PARADA/Par_Impar.py
920
3.59375
4
from random import randint print("=-" * 40) print("VAMOS JOGAR PAR OU ÍMPAR") print("-=" * 40) acumu = 0 while True: pc = randint(0, 10) valor = int(input("Diga um valor: ")) escolha = str(input("PAR ou Ímpar: [P/I]")).upper().strip() soma = valor + pc while escolha[0] not in 'PI': ...
b30a126f358be30e8ae86e55e730bdb9353f8c6d
kamibarreto/Python_Exercicios
/WHILE_PARADA/Tabuada3.0.py
659
4.03125
4
print(10 * "-") print("______TABUADA______") print(10 * "-") print("Digite um numero negativo para parar.") while True: print("-" * 40) valor = int(input("Quer ver a tabuada de qual valor? ")) print("-" * 40) valor2 = str(valor) if valor2[0] == "-": break acumu = 0 whil...
2ad89c28c458ba5ab307f35283d8e6cc2427e6cf
kamibarreto/Python_Exercicios
/FOR/Tabuada.py
181
3.953125
4
print("-----------Tabuada de 0 a 10-----------") tabu = int(input("Qual o valor da tabuada: ")) for i in range(0, 11,): print("{} x {:2} = {}".format(tabu, i, tabu * i))
14f0ef5618e1be952842259b1bedc5d512a1da5a
Dreed657/CS50
/Python&JavaScript Web/Python/Tests/classes.py
616
3.8125
4
class Flight(): def __init__(self, capacity): self.capacity = capacity self.passengers = [] def addPassager(self, name): if not self.openSeats(): return False self.passengers.append(name) return True def openSeats(self): return self.capa...
57c27259ecb108ea26e23acacf45ecefcb31b41d
prerna2055/investment-analysis
/Module.py
9,121
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[3]: import pandas as pd def drawdown(return_series: pd.Series): """ Takes a time series of asset returns and Computes and returns a DataFrame that contains: Wealth Index Previous peaks % Drawdowns """ wealth_index=1000*(1+return_series).cumprod(...
82776d626783ab6064c5a53c4bb77ec422c1548b
nguyenthanhthao1908/classpython_basic_online
/homework/bai_tap_buoi07/bai01.py
298
4
4
"""Bài 01: Viết hàm def max_min(*numbers) trả lại cả giá trị max, min của nhiều số được truyền vào""" def find_min_max(*numbers): print("Min numbers:", min(*numbers)) print("Max numbers:", max(*numbers)) print(find_min_max(56, 78, 8, 10, 200, -56, 1))
ec6e1871e6a55516a520a49b11dcd267d7dbb28a
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_resource_w/dictionary/bai9.py
235
4.3125
4
"""Write a Python program to iterate over dictionaries using for loops.""" D = {"Name": "Thao", "Age": 20, 19: 8} # for i in D.items(): # print(i) # solution 2: for key, value in D.items(): print(key, "is:", D[key])
bf7fc93dca484f582f674ee64e1e38dcc68a6392
nguyenthanhthao1908/classpython_basic_online
/homework/bai_tap_buoi02/baiso3.py
706
3.703125
4
""" Bài 3. Lập chương trình thực hiện các công việc sau: Nhập 1 số nguyên dương n bất kì (n<1000). Yêu cầu kiểm tra dữ liệu đầu vào, nếu sai yêu cầu nhập lại. Tính tổng các chữ số của số đó. Hiển thị kết qủa ra màn hình """ n = int(input("enter random number <1000, n =")) while True: if n > 0 and n < 1...
aa2b00e3bcd8cc17d08ef67e68ab65aaa64c0435
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_resource_w/dictionary/bai15.py
226
4.15625
4
"""Write a Python program to get the maximum and minimum value in a dictionary. """ D = {3: 30, 2: 20, 19: 8} print("Maximum:", max(D.keys(), key=(lambda k: D[k]))) print("Minimum:", min(D.keys(), key=(lambda k: D[k])))
b991fe2eac89c134fa70475509d968867e069ca4
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_inexample_g/find_the_largest_number.py
619
3.703125
4
class findnumber: #khoi tao class def __init__(self): #thuoc tinh print("enter three number:") #nhap so self.a = float(input("Number a: ")) self.b = float(input("Number b: ")) self.c = float(input("Numbe c: ")) def myfunc(self): #phuong thuc if ...