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
f3aea77de5dd9e1669127c5f0c44f715174ebf7f
pyung/start
/bible/bible.py
2,881
3.859375
4
import json import sys def init_bible(username="your") : print("opening " + username + " bible") bible_json = open("bible/bible.json", 'r') bible = json.load(bible_json) load_books(bible) def load_books(bible) : sn = 1 print("\n Old Testament \n") for books in bible : ...
c209a322486bef0d2e43b23e4456a9f7c1f62059
AlexanderFrancoletti/GameJam20161008
/scene.py
1,559
3.84375
4
import tkinter as tk ''' Scene is the top half of the window that shows the background and has slots to place chacters. ''' class Scene(tk.Frame): def __init__(self, master = None, initBackground = None, scale=0.5): tk.Frame.__init__(self, master) self.scene = tk.Canvas(self, width=scale*1920, he...
74fb79167e2f3046972e93856c59c1eeaa34d888
Michalju/week2_day5_homework
/classes/room.py
808
3.671875
4
class Room: def __init__(self, name): self.name = name self._guests = [] self._songs = [] # This method return guest by name def find_guest_by_name(self,name): for guest in self._guests: if guest.name==name: return guest # This method check...
62baded0917e1aa99f57419595de62bd516558c0
leramorozova/Classwork2017-18
/Class4.py
3,149
3.703125
4
# Придумать любой словарь, например, Страна -> (столица, население) или Имя -> (город проживания, возраст). # Распечатать словарь, используя форматирование с %. def percents(): d={} for key in range(3): key=input('Enter any name: ') d[key]=int(input('Enter his or her age: ')) row='%s\t\t\t%...
f720eac06885e9defedac9e51a34bad1febf6a49
Aleksandr-vid/ryt
/Yes_or_No.py
614
3.734375
4
#программа которая отвечает на любой вопрос да или нет from random import choice ответ=["да","нет"] вопрос=['На марсе живут марсеане?', 'Попугаи умеют говорить?', 'Чебурашка существует?', 'Дед мороз существует?', 'Солнце - это звезда?', 'Существует ли внеземная жизнь?', 'На южном полюсе тепло?'] def speak(q): re...
57d53c6f5c3c71db4a9cc018e0150b56d575aeb7
Sergio-Dobrianskiy/Python-Sideprojects
/01 - MultiplyLines.py
357
3.65625
4
# This takes every line of the first .txt file and creates a second file in which it # repeats the line 'c' times with open('file.txt', 'r') as originalFile: with open('file2.txt', 'w') as secondFile: for line in originalFile: c = 0 while c < 2: secondFi...
5c267a5620aa7a658ccdb79e677f3998207756a3
sciencefixion/HelloPython
/Hello - Basics of Python/sliceback.py
857
4.28125
4
letters = "abcdefghijklmnopqrstuvwxyz" backwards = letters[25:0:-1] print(backwards) backwards2 = letters[25::-1] print(backwards2) # with a negative step the start and stop defaults are reversed backwards3 = letters[::-1] print(backwards3) # Challenge: Using the letters string add some code to create the following ...
74f29d71d51572c1eca6922608eab508f62311ba
shinespark/code
/d/D023.py
129
3.75
4
# -*- coding: UTF-8 -*- import collections string = raw_input() count_dict = collections.Counter(string) print(count_dict['A'])
22786dcb0c59c06724512c6b5698e69afb29c1d7
shinespark/code
/d/D008.py
94
3.796875
4
# coding: utf-8 a = int(raw_input()) if a % 2 == 0: print('even') else: print('odd')
f38c96c083a7193c66fbfa822c48d0da4df9081d
shinespark/code
/c/C019.py
632
3.546875
4
# coding: utf-8 import sys lines = [x.strip() for x in sys.stdin.readlines()] num_count = int(lines[0]) target_lines = lines[1: 1 + num_count] def getDivisior(num): l = [1] for i in range(2, num + 1 // 2): if num % i == 0: l.append(i) return l def checkPerfectNumber(num): divis...
0367d329c5e1d17d4eb72c6f8039333e512fe9ef
shinespark/code
/c/C010.py
504
3.546875
4
# coding: utf-8 import sys lines = sys.stdin.readlines() first_line = lines[0].split() base_x = int(first_line[0]) base_y = int(first_line[1]) base_r = int(first_line[2]) square_r = pow(base_r, 2) tree_num = int(lines[1]) trees = lines[2: 2 + tree_num] for tree in trees: splited_line = tree.split() tree_x =...
814041a033f8758d1966235f21a061607dc49dc1
nada5un/Sorting_Algorithm
/Sort.py
2,383
3.796875
4
#선택 정렬 def select_sort(): arr = [7,5,9,0,3,1,6,2,4,8] for i in range(len(arr)): #앞으로 보낼 자리 인덱스 min_index = i for j in range(i+1,len(arr)): if arr[min_index]>arr[j]: #가장 작은 원소 min_index=j arr[i],arr[min_index] = arr[min_index],arr[i] print("선택 정렬: ",arr) #삽입 정렬 def inser...
e0eddfb70ad4ddb811dee6cefac99b82e8868611
dthomas-eng/Data_Structures_Implementations
/stack.py
4,980
4.0625
4
'''A simple stack implementation in python using 3 approaches 1) List Stack: O(1) for pops and pushes. 2) Deque Stack: O(1) for pops and pushes. 3) Linked-List Stack: O(1) for pops and pushes. A note about performance: List and Deque stacks perform similarly and are faster than the Linked-List version...
9bcdcc6b798e39ee0b14e5ee0bb0daf09c63f6a2
kimiranran/find_largest_k
/find_k_largest.py
876
3.578125
4
from min_heap import MinHeap from heapq import heappush, heappop import sys def findMaxK(vals, k): minHeap = MinHeap(k) for n in vals: if minHeap.get_size() < k: minHeap.push(n) elif minHeap.peek() < n: minHeap.pop() minHeap.push(n) while minHeap.get_size...
7c8dbadad479ee78e612ef6bff56ccf584937272
arblancaflor/LIS161
/PycharmProjects/Ch 10 Ex 2.py
793
4.0625
4
# This program counts the distribution of the hour of the day for each of the messages. You can pull the hour # from the "From" line by finding the time string and then splitting that string into parts using the colon character. # Once you have accumulated the counts for each hour, print out the counts, one per line, s...
c07c5881c38cc4994f3ef76ac05f90081b04482b
arblancaflor/LIS161
/PycharmProjects/Ch 3 Ex 2.py
457
4
4
# Rewrite your pay program using try and except so that your program handles non-numeric input gracefully. import sys x= input("Enter Hours: ") y= input("Enter Rate: ") try: x=float(x) except ValueError: print("Error, please enter numeric input") sys.exit() try: y=float(y) except ValueError: pri...
3d3108c007d9a67e5c257a28329b4effe701d322
ngssss/xuewei
/utils/getAngel.py
1,145
4.28125
4
import math class Point: """ 2D坐标点 """ def __init__(self, x, y): self.X = x self.Y = y class Line: def __init__(self, point1, point2): """ 初始化包含两个端点 :param point1: :param point2: """ self.Point1 = point1 se...
53ebe73f904c90b05f59bf9fb20da5d1a7f48f5b
a29585817/turtle_create_snake_game
/score.py
1,244
3.65625
4
from turtle import Turtle alignment = "center" font =("Courier", 15, "normal") with open ("hight_score.text", mode="r") as f: hight_score = int(f.read()) class Score(Turtle): def __init__(self): super().__init__() self.count_score = 0 self.hight_score = hight_score self.hideturt...
34ba5d7961036bc197071aa2f1d724925de6c9dd
eche10n/PythonFirstTasks
/tictactoe.py
4,173
3.984375
4
import random as rnd """ВЫВОД ПОЛЯ""" def showPlayBoard(board): for i in range(3): print(board[i]) """ОРГАНИЗАЦИЯ ОЧЕРЕДИ ХОДА""" def showTurn(turn, player1, player2): if turn == 0: print("Ход игрока: ", str(player1)) else: print("Ход игрока: ", str(player2)) print("...
4b1b47754908d1408d23be833869d656231ec113
casanova98/Project-201501
/Practical one/q1_fahrenheit_to_celsius.py
232
4.21875
4
#q1_fahrenheit_to_celsius.py answer = input("Enter the temperature you want in Celsius!") x = float(answer) celsius = round((5/9) * (x - 32), 1) print("The temperature from Fahrenheit to Celsius to 1 decimal place is", celsius)
9d2ef8e3764b1709b9dfcbf68bb4af5bd4b64eae
casanova98/Project-201501
/Practical two/q08_top2_scores.py
552
4.125
4
students = int(input("Enter number of students: ")) names = [] score = [] while students != 0: names.append(str(input("Enter your name: "))) score.append(int(input("Enter your score: "))) students -= 1 highest = max(score) print("Student with highest score is:", names[score.index(highest)], "with ...
80253d0aaf24716f15b4c6c6ebbaeb973d46a2c3
rshanker779/orm
/orm/data_structures/data_types.py
404
3.546875
4
from enum import Enum class ColumnTypes(Enum): Int = 0 String = 1 def to_sql_type(self) -> str: if self == ColumnTypes.Int: return "Int" elif self == ColumnTypes.String: return "Varchar" def to_python_type(self) -> type: if self == ColumnTypes.Int: ...
70f8a666535168b65bf877281b4a50e879e04be3
cleantechsim/evchargers
/python-flask-reactjs-map/geo_utils.py
2,016
3.625
4
from haversine import haversine def validate_latitude(latitude): if latitude > 90.000000001: raise Exception('latitude > 90') if latitude < -90.000000001: raise Exception('latitude < -90') def validate_longitude(longitude): if longitude > 180.00000001: raise Exception('longitu...
783d04424384829bec20a0b6d4dddca93f46e3ae
Smily-Pirate/100DaysOfCode
/Day1.py
971
4.125
4
# Day1 of 100 days of coding. # Starting from list. # Accessing Values in Lists. list1 = ['hi', 'there', 18, 1] list2 = [1, 2, 3, 4, 5, 6, 7, 8] print(list1[0]) print(list2[2]) # Updating list list1[0] = 'ghanshyam' list1[1] = 'joshi' list2[7] = 'hi' print(list1) print(list2) list1.append('10') print(list1) # Delet...
b7f31b1d6e83c0b75bd5fe87ae57d009cf0626a5
Smily-Pirate/100DaysOfCode
/Day4.py
836
3.8125
4
n = int(input("Enter the number")) for i in range(0, n): for j in range(0, i + 1): print("* ", end="") print("\r") def pypart(n): myList = [] for i in range(1, n + 1): myList.append("*" * i) print("\n".join(myList)) pypart(n) # 180 degree rotation def funfun(n): # number o...
e120ebeb3edc1e279ee2aff9d8348eab499589e0
uberj/lcg_value
/gcd.py
266
3.6875
4
import sys big = int(sys.argv[1]) small = int(sys.argv[2]) def divide(big, small): whole_count = 0 while True: whole_count += 1 big = big - small if big < 0: return whole_count - 1, big + small print divide(big, small)
a12fb0a9f244e6c77d9dcff328ad2e96f8409cd4
DanaOwens/SpaceInvadersGame
/SI.py
1,043
3.953125
4
#Space Invaders import turtle import os #Setting up the screen window=turtle.Screen() window.bgcolor("black") window.title("Space Invaders") #Draw Border border_pen = turtle.Turtle() border_pen.speed(0) border_pen.color("white") border_pen.penup() border_pen.setposition(-300,-300) border_pen.pendown() border_pen.pen...
82dca717dd4e8c4368f17b30d23bbb1463daa57c
COSIMA/access-om2
/tools/calc_input_checksum.py
1,119
3.5
4
import sys import os import tempfile import tarfile import hashlib import argparse def calc_checksum(dirname): """ Calculate the checksum of a whole directory. This is done but tarring the directory first to make sure that file names and other metadata are included in the checksum. FIXME: this d...
e767984ccebc87f748c026f0e1b6f64ea1a963a3
anemptyarchive/Suyama-Bayes
/code/Python/ch3_5.py
15,963
3.59375
4
# ch3.5 線形回帰の例 #%% # 3.5節で利用ライブラリ import numpy as np import matplotlib.pyplot as plt #%% ## ch3.5.1 モデルの構築 # {x^(m-1)}ベクトル作成関数を定義 def x_vector(x_n, M): # 受け皿を作成 x_nm = np.zeros(shape=(len(x_n), M)) # m乗を計算 for m in range(M): x_nm[:, m] = np.power(x_n, m) return x_nm #%% # 真の次元数を指...
c13585f8d6f5b3d53f4fcebeb7a9703acf3db953
maskan19/PYTHON
/HELLOPYTHON/day01/mytest05.py
161
3.515625
4
# input("단수를 넣으세요") 2 # 2단을 출력 dan = input("단수를 넣으세요") for i in range(1, 10) : print( dan," * ",i, " = " , int(dan)*i )
e52c4419f40e70364a5504fc9ded3917cefb56b2
Akshay-Chandelkar/PythonTraining2019
/Ex44_GCD.py
362
4.09375
4
def GCD(N1, N2): while (N1 != N2): if N1 > N2: N1 = N1 - N2 else: N2 = N2 - N1 return N1 def main(): N1, N2 = eval(input("Enter two numbers to find the GCD :: ")) res = GCD(N1, N2) print("The GCD for {} and {} is :: {}".format(N1, N2, res)) ...
1477f881644208f1623068e0b584ecef97794173
Akshay-Chandelkar/PythonTraining2019
/Ex32_ValidTime.py
521
4.0625
4
def ValidTime(hh,mm,ss): if hh >= 0 and hh < 25: if mm >= 0 and mm < 60: if ss > 0 and ss < 60: print("The time {}:{}:{} is valid.".format(hh,mm,ss)) else: print("ss %d is invalid." %ss) else: print("mm %d is invalid." %mm...
a940e3ee0f9ffe27508d8dc83a0b1da3f9b841d6
Akshay-Chandelkar/PythonTraining2019
/EX66_CompareDict.py
712
3.796875
4
def CompareDict(D1, D2): retval = True if type(D1) != dict or type(D2) != dict: retval = False elif len(D1) != len(D2): retval = False else: for key in D1: if key in D2 and D1[key] == D2[key]: continue retval = False ...
e3674d5c9b97fc3f1d6b84bbfc33ad2b1926bc7c
Akshay-Chandelkar/PythonTraining2019
/Ex4_FirstChar.py
294
3.78125
4
def FirstChar(S1): S2 = 'T' if S1[0] == S2: return True else: return False if __name__ == '__main__': S1 = input("Enter a string to verify first char :: ") res = FirstChar(S1) print("The entered string starts with 'T' is {}".format(res))
49ba616fc87d3f9287ef22e444a7b872839f1aa7
Akshay-Chandelkar/PythonTraining2019
/Ex21_Arthimetic.py
1,458
4.125
4
print("Free fall code to begin") def add(num1,num2): sum = num1 + num2 print("The sum of two numbers is : ", sum) def sub(num1,num2): sub = num2 - num1 print("The difference between the two numbers is : ", sub) def mul(num1,num2): mul = num1 * num2 print("The multiplication of t...
3815c9d07dc4207f69488305b24b0216ca716dbd
Akshay-Chandelkar/PythonTraining2019
/Ex60_Own_FromKeys.py
1,133
3.90625
4
def OwnFromKeys(D1,V1=None): if type(D1)!= dict: print("{} is not a dictionary.".format(D1)) result_dict = {} if type(V1) == list or type(V1) == tuple: i = 0 length = len(D1.keys()) for key in D1.keys(): if i+1 == length and i+1 != len(V1): ...
c57f2c473a90a15353b101a8bd2e6b8f4031ceb3
Akshay-Chandelkar/PythonTraining2019
/Ex64_Stack_List.py
2,492
4.125
4
def IsStackFull(L1): if IsStackEmpty(L1): print("\nThe stack is empty.\n") elif len(L1) >= 6: return True else: print("\nThe stack is not full.\n") def IsStackEmpty(L1): if L1 == []: return True else: return False def Push(L1): if not IsSt...
8f5f2fb429eec857e22579194b589c0e688097a7
Akshay-Chandelkar/PythonTraining2019
/Ex46_SumOfCubes.py
394
3.9375
4
def SumOfCubes(N1): rem = 0 S1 = 0 while(N1!=0): rem = N1 % 10 N1 = int(N1//10) S1 = S1 + rem**3 return S1 def main(): N1 = eval(input("Enter a number to get sum of cubes of digits :: ")) #res = SumOfCubes(N1) print("The sum of cubes of digits for {} is...
c42bb1b9d5daed197d897b7deaa9ba7c9361fa8a
Akshay-Chandelkar/PythonTraining2019
/Ex52_CompareList.py
1,310
4
4
def CompareList(L1, L2): if type(L1) != list or type(L2) != list: #print("L1 or L2 is not a list. ") return 0 if len(L1) != len(L2): #print("The given {} and {} lists are not same.".format(L1, L2)) return 0 L1.sort() L2.sort() i = 0 j = 0 while i ...
1503da2ada492faad659632edfea7a4c73d59726
phreic/NetworkExtractionFromImages
/osx_build/nefi2_osx_amd64_xcode_2015/bin/nefi2/model/algorithms/guo_hall.py
8,269
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Thinning is the operation that takes a binary image and contracts the foreground until only single-pixel wide lines remain. It is also known as skeletonization. The algorithm below was taken from NEFI1. It uses thinning C module written by `Adrian Neumann <https://bit...
8be8eaedfa3e62a94638d3cf8072efd1e2cd4e99
marleygf/327final
/front/inputVerification.py
1,637
3.578125
4
''' Class containing legality and validity of user input against defined requirements and logical restrictions. ''' ''' Checks if a given service number is legally correct according to specification. @Param service: given service number ''' def isLegalServiceNumber(service): return (service[0] != '0' and...
723acb0d8bd95477faaace0d51c72c3b6363ab06
jaj2610/SeminarSearch
/timeregex.py
2,014
3.53125
4
import re from datetime import datetime def validate_hour(hour): return hour >= 0 and hour <= 23 def validate_minute(minute): return minute >= 0 and minute <= 59 def get_time(text): """Get first time from text, and return index of that time""" m = re.match(r'.*?(' + r'(\d\d?)' + ...
758bc9790d22a8082bf66b0db1a704da20ee9af7
vonnenaut/coursera_python
/3 of 7 -- Principles of Computing 1/wk4 -- Combinatorics, generators, and debugging/gen_all_holds.py
3,091
3.96875
4
""" Function to generate permutations of outcomes Repetition of outcomes not allowed """ def get_outcomes(num_die_sides): """ Compute and return a list of possible outcomes (die values) based on the number of sides on a die. """ outcomes = [] for value in range(1, num_die_sides + 1): outcom...
e1d1e3e64d938d04ede1ccb0270d5e8eb4170ac6
vonnenaut/coursera_python
/4 of 7 -- Principles of Computing 2/wk4 -- modeling/solve_row0_tile.py
2,208
3.71875
4
def solve_row0_tile(self, target_col): """ Solve the tile in row zero at the specified column Updates puzzle and returns a move string """ clone = self.clone() clone.update_target_tile(0, target_col) clone.get_zero_pos() ttile = clone.curr...
d8dc56075b59c4790ef758177723e44a2b09bf8f
vonnenaut/coursera_python
/7 of 7 --Capstone Exam/probability.py
854
4.21875
4
# Fundamentals of Computing Capstone Exam # Question 12 def probability(outcomes): """ takes a list of numbers as input (where each number must be between 1 and 6 inclusive) and computes the probability of getting the given sequence of outcomes from rolling the unfair die. Assume the die is rolled exactly the number o...
56555a338b03786e7de3d8cd5546f8d3b5f65158
vonnenaut/coursera_python
/7 of 7 --Capstone Exam/pick_a_number.py
1,280
4.15625
4
# Fundamentals of Computing Capstone Exam # Question 17 scores = [0,0] player = 0 def pick_a_number(board): """ recursively takes a list representing the game board and returns a tuple that is the score of the game if both players play optimally by choosing the highest number of the two at the far left and right edg...
dcceddfae83a164aeae8bfa0fdb6177fad4b90de
vonnenaut/coursera_python
/2 of 7 -- Intro to Interactive Programming with Python 2/wk 6/quiz_6b_num8.py
2,021
4.34375
4
""" We can use loops to simulate natural processes over time. Write a program that calculates the populations of two kinds of “wumpuses” over time. At the beginning of year 1, there are 1000 slow wumpuses and 1 fast wumpus. This one fast wumpus is a new mutation. Not surprisingly, being fast gives it an advantage, as...
fd41816f1c1f69490f834fa6fa6611feefbbe33e
vonnenaut/coursera_python
/4 of 7 -- Principles of Computing 2/wk2 -- Recursion/word_wrangler_owltest.py
9,390
4.09375
4
""" Student code for Word Wrangler game Should not use set, sorted, or sort. Important: None of these functions should mutate their inputs. You must leave the inputs as they are and return new lists. """ import urllib2 import codeskulptor import poc_wrangler_provided as provided # import poc_simpletest # REST_STRIN...
3420f254824b309441ccf48f7debec103c6861fe
varshinidevi17/pythonDAY1
/DAY1 assignment/try to add string and interger.py
356
3.953125
4
x = "I need some water" #string is declared y = 2 #integer is declared print(x + y) # it gives #'''Traceback (most recent call last): #File "C:/Users/Sharmila S/Desktop/varshini/let'supgrate/DAY1 assignment/try to add string and interger.py", line 6, in <module> #print(x + y) #TypeError: can only con...
0d0dfad034d74aa4d59becf560bffa035cf225cc
sourjyar7/IFogStorR
/graphs4.py
583
3.5625
4
import matplotlib.pyplot as plt # x-coordinates of left sides of bars left = [4, 8, 12] # heights of bars height = [34.8, 90.4, 368.8] # labels for bars tick_label = ['iFogStor(4)', 'iFogStor(8)', 'iFogStor(12)'] # plotting a bar chart plt.bar(left, height, tick_label=tick_label, width=0.8, c...
80e25d516fd2ce48e108fef088923778be661c2c
Jack-lee-ss/-Python-
/正则表达式/006.py
14,729
3.640625
4
# 生活不会突变,你要做的只是耐心和积累。人这一辈子没法做太多的事情,所以每一件尽力而为。 # -*- coding: utf-8 -*- import re str1 = 'def factorial()' str2 = 'a/b(division) + c%d(#modulo) - (e+(j/k-3)*4)' str3 = 'Hi there(greeting). Nice day(a(b)' remove_parentheses_1 = re.compile(r'\(\)') ##### add your solution here print(remove_parentheses_1.sub('', str1)) ...
9c20fc2b6c49e4fa6d8d4a1d2740804c0a348503
Jack-lee-ss/-Python-
/函数/0012参数扩展.py
7,209
4.25
4
# -*- coding: utf-8 -*- ### 参数扩展 ## 参数设置默认参数 def f(name,age=0): print(f'name={name},age={age}') f('老王',19) f('小李') def f(a,b,c=0,d=1): ## 默认值只能从后向前设置 print(f'{a},{b},{c},{d}') f(1,2,4,6) # 都有值的原样打印 f(1,2,3) # 没有的用默认值填充 f(1,2) print('==================') ## 关键词参数 def f(a,b=4,c=9): print(a,b,c,'\n') f(12,c=6) ...
aa5871dd4bbce912f857459061f931b2b5d0901f
Jack-lee-ss/-Python-
/数据分析/006.py
9,877
3.65625
4
##================ pandas ====================== from pandas import Series,DataFrame import pandas as pd import numpy as np a=pd.Series([1,2,3,4]) ## 与numpy类似,不同在于可以输出索引 print(a) print(a.values) #获取值 print(a.index) #获取索引初始值 ## 创建索引类型 a=pd.Series([1,2,3,4],index=['a','b','c','d']) print(a) print(a['c']) # 通过索引值获取相应数值 p...
47bef184daa142f3b7fc054eda443472643c6578
Jack-lee-ss/-Python-
/函数/try,with.....py
1,028
3.921875
4
# 生活不会突变,你要做的只是耐心和积累。人这一辈子没法做太多的事情,所以每一件尽力而为。 # -*- coding: utf-8 -*- ### try....except.....finally 语句中,含有 return的,执行顺序 ## 存在 finally 语句时,代码一定会执行该语句,raise KeyError 时,程序进入 except 捕获 ## 打印 key error,由于存在 finally ,会直接 返回 return 4 结束函数 ## 不存在 finally ,会返回 return 2 def exe_try(): try: print('code start') raise Key...
73d67754ee2493014810adac152bb2341df2f0b9
Jack-lee-ss/-Python-
/函数/推导式及相关函数.py
16,585
3.625
4
# 生活不会突变,你要做的只是耐心和积累。人这一辈子没法做太多的事情,所以每一件尽力而为。 # -*- coding: utf-8 -*- ''' ## 列表的创建 a=[] b=list() c=[1,2,3] print([i for i in range(1,11)]) # 表达式创建 print([i for i in range(1,10) if i % 2==0]) # 表达式+判断的列表 print(list('a,gb h')) # 字符串转化为列表 print('==============') a=[1,2,3,4,58,5] # 列表分片:[左边界,右边界,步长] print(a[1:]) p...
e880ca8a127567e14e405f182c96402e1e214f54
amresh199/AI-and-ML
/4 June Assignment.py
950
3.6875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np # In[2]: #1 a=np.array([12,13,14,15, 16 ,17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37]) print(a) print(a[::-1]) # In[3]: #2 Question m=int(input("enter the number of rows")) n=int(input("enter the number o...
38db8bd4558318c37c21ea59444d50b6e526ddbd
andreodendaal/100DaysOfCode
/datesFromLogs_d2.py
1,358
3.546875
4
'''Extract datetimes from log entries and calculate the time between the first and last shutdown events''' from datetime import datetime, timedelta import os import urllib.request SHUTDOWN_EVENT = 'Shutdown initiated' # prep: read in the logfile logfile = os.path.join('/tmp', 'log') urllib.request.urlretrieve('ht...
217860d7d5348e8e4dbeca760a9f082011fa92cd
pkpavlov/SoftUni-Basic-Python
/Conditional Statements - More Exercises/04. Transport Price.py
401
3.875
4
kilometers = int(input()) part_of_the_day = input() if kilometers < 20: if part_of_the_day == "day": price = 0.7 + kilometers * 0.79 print(f"{price:.2f}") else : price = 0.7 + kilometers * 0.9 print(f"{price:.2f}") elif 20 <= kilometers <100: price = kilometers * 0.09 pr...
9f5dd640befe110d07b4c3402c4642361a664934
pkpavlov/SoftUni-Basic-Python
/Conditional Statements - More Exercises/03. Harvest.py
650
3.734375
4
import math area_vineyard = int(input()) #X grapes = float(input()) #Y needed_liters_wine = int(input()) #Z number_workers = int(input()) total_grapes = area_vineyard * grapes *0.4 wine = total_grapes / 2.5 if wine >= needed_liters_wine: left_wine = wine - needed_liters_wine print(f"Good harvest this year! ...
ce79e741324646ff9385fcfb2325182a6fe59e56
pkpavlov/SoftUni-Basic-Python
/Conditional Statements - Exercise/04. Metric Converter.py
677
4.09375
4
number = float(input()) input_unit = input() output_unit = input() if input_unit == "m" and output_unit == "cm": number = number * 100 print(f"{number:.3f}") elif input_unit == "m" and output_unit == "mm": number = number * 1000 print(f"{number:.3f}") elif input_unit == "cm" and output_unit == "m": ...
ed1666a86b6665cfb966ad5f5e2770d41245f55e
jackhealey/Various
/Project - Royal Mail/Depot_framework.py
15,673
3.515625
4
import math import numpy as np import matplotlib.pyplot as plt # use LaTeX fonts in the plot plt.rc('text', usetex=True) plt.rc('font', family='serif') ######################################### def Dies_annual_cost(total_miles_Dies, area, price_litre): litres_anum = total_miles_Dies * fuel_efficiency(area) # total...
b50a78c3acba0086cdb51ddccaa109d55cdeadbc
amitrajhello/ProjectEulerPractise
/saurav's problem.py
87
3.921875
4
N = int(input("enter a number: ")) x = 0 while x < N: print(x * x) x += 1
6f32b6401746e7261c630ade04be52281f38e0ef
brahimmade/Voice-Assistant
/pomodoro.py
1,472
3.5625
4
import time from lns import get_audio, speak def timer(minutes): """ Function to implement a timer. """ tim = 0 while tim != minutes: time.sleep(60) tim += 1 return tim def pomodoro(): """ Function that implements the pomodoro technique in which one focuses for a while...
6df66f23c2d7c8872e46fee7a56d0dfbabb05cf0
chyser/bin
/ascii.py
1,042
3.6875
4
#!/bin/env python """ usage: ascii [options] Shows the ascii character set Options: -h | --hex : show hex (default) -d | --decimal : show decimal -o | --octal : show octal """ import pylib.osscripts as oss #------------------------------------------------------------------------------- def...
67fa09f0b971d949b8a9ea81ac2225a8c963a1d9
cf-zhang/design_pattern_python
/null_object_pattern.py
884
3.9375
4
class AbstractCustomer: def __init__(self): self.name = '' def isNil(self): pass def get_name(self): pass class RealCustomer(AbstractCustomer) : def __init__(self, name: 'str'): self.name = name def get_name(self): return self.name def isNil(self): ...
62135bdc311893da2bb411e88a2c1ca760b4a03c
cf-zhang/design_pattern_python
/interpreter_pattern.py
1,185
3.65625
4
class Expression: def interpret(self, context: 'str'): pass class TerminalExpression(Expression): def __init__(self, data: 'str'): self.data = data def interpret(self, context: 'str'): return context.__contains__(self.data) class OrExpression(Expression): def __init__(self, ex...
b2a078e83d1c5c00805d3acefdce050b04085ea0
WkBqVN/FunnyPython
/b03-btvn.py
1,943
3.609375
4
""" BÀI TẬP VỀ NHÀ BUỔI 03 - String Bài 01: Viết chương trình thay thế tất cả các ký tự giống ký tự đầu tiên của một Chuỗi thành $. Bài 02: Viết chương trình để xóa bỏ ký tự thứ m trong chuỗi không rỗng, với m là số không âm, nhập từ bàn phím. Bài 03: Viết chương trình để xóa bỏ các ký tự có chỉ số là số lẻ trong một c...
e691cd60ec7b223821b86cae7c4541c4965016ec
dasamerica/ct208
/aula_2805_maior_elemento/ct208_maior_menor_segundo_elemento_DCM.py
6,113
3.703125
4
# Programa phyton para dado um numero gera uma lista de suas permutações # Utiliza divide and conquer e memoization # Verifica quantas iterações necessárias para achar o maior elemento, menor elemento, o segundo maior elemento, e segundo menor elemento da lista # Daniela América da Silva # Disciplina: ct208 # Importa...
c9d3d1735eadee86c6601193da7690ed39d6e472
777shipra/dailypython
/assignment_acadview/question_9.py
255
4.125
4
sentence=raw_input("enter your sentence :") uppercase_letters=0 lowercase_letters=0 for x in sentence: if x.isupper(): uppercase_letters +=1 elif x.islower(): lowercase_letters +=1 print uppercase_letters print lowercase_letters
b67904bd5415cde5c5ddc1a4e1cb121c47778274
777shipra/dailypython
/enumerate.py
261
4.25
4
choices=['pizza','ice','nachos','trigger'] for i,item in enumerate(choices): print i,choices #prints the whole list print i,item #prints the content of the list for i,items in enumerate (choices,1): print i,items #begins the itteration from index 1
d05f53fed23e21ed62934aa96e210c0c637f016d
777shipra/dailypython
/guessinggame.py
475
4.0625
4
print "let's play" print "so, this is what it's all about" print "i choosed a number from 1 to 10 and u have to guess it " print "but u just have 2 turns" user = [1,2] for a in user : a=raw_input("enter your guessed number or type exit for quitting") if (a>7 or a<3) : print "u are going away" if (a...
de052416708f8418dab2e81f46f0f9a0002c41ea
celinexuzhang/importFlatfilewithpd
/getWorkDirectory.py
426
3.5
4
#to explore your current working directory. You can also do this natively in Python using the library os, which consists of miscellaneous operating system interfaces. #The first line of the following code imports the library os, the second line stores the name of the current directory in a string called wd and the thir...
7173b5ccaf209fa4cae9a77f99f7a8e6b2324aa0
rubengr16/Python4BeginnersMS
/2_using_print/2_ask_for_input.py
167
4.09375
4
# input function name = input("Please enter your name: ") # input with message print("Enter your age: ") age = input() # simple input print(name, "your age is", age)
438b6f912896da5c326f3a217c793b0671bb8c1c
wamiquem/cmpe255-spring19-lab2
/Friends.py
840
3.84375
4
import numpy num_friends=[100, 49, 41, 40, 25, 10, 5, 4, 7, 20, 60] def mean_num_friends(x): count_friends = len(x) sum = 0 for each_x in x: sum = sum + each_x mean = sum/count_friends print("mean = %f" %mean) mean_numpy = numpy.mean(x) print("mean using python's num...
64996d4367640f79b4ea403865fa8379380fb4fe
praseedpai/MathOrientedStuff
/MLCourse/DayOne/TOLOCAL/vmean.py
445
3.90625
4
# vector mean from numpy import array from numpy import mean # define vector v = array([1,2,3,4,5,6]) print(v) # calculate mean result = mean(v) print(result) #--------------------------- Program 2 # matrix means from numpy import array from numpy import mean # define matrix M = array([ [1,2,3,4,5,6], [1,2,3,4,5,6]])...
7c8ce6e98cf2895fc30d3c39b70b6addab722822
222010301049/coding-skills
/sample.py
148
4.25
4
num=int(input("enter a number ")) if(num%2) == 0: print("{0}is even number".format(num)) else: print("{0}is odd number".format(num))
017f33b0761ed952b88fd0d53cd5186ad361782c
conz27/crypto-test-vectors
/ecc.py
25,920
3.609375
4
from types import * from random import * from hashlib import * # # Bit operations # # bitLen() returns a length of the number in bits def bitLen(int_type): length = 0 while (int_type): int_type >>= 1 length += 1 return(length) # testBit() returns a nonzero result, 2**offset, if the bit at...
fdc59e51e36ae1b38f9a3ca2ff231a156f0005e4
j2towers/exercism.io-python
/series/series.py
438
3.5
4
def slices(stringin, slength): listout = list() if slength > len(stringin) or slength == 0: raise ValueError else: for index, num in enumerate(stringin): liststring = list() if index + slength <= len(stringin): for a in range(slength): ...
0db9cc4180d1351475db8e577c1269ccabf5e779
j2towers/exercism.io-python
/armstrong-numbers/armstrong_numbers.py
541
3.734375
4
import math def finddigits(numberin): if numberin > 0: digits = int(math.log10(numberin))+1 elif numberin == 0: digits = 0 else: digits = int(math.log10(-numberin))+1 return digits def get_digit(numberin, digit): return numberin // 10**digit % 10 def is_armstrong(number...
acb2cbddf9dcf6591dd6150994d91be0cbe143b7
j2towers/exercism.io-python
/pangram/pangram.py
167
3.8125
4
import string def is_pangram(test): for letteritem in string.ascii_lowercase: if letteritem not in test.lower(): return False return True
f7b1341b660ee9e93076327720610821bc54fd84
GoharE/Projects
/Person_customer.py
1,277
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 16 23:05:58 2018 @author: gohar """ from exceptionClass import ShoppingError class Person: def __init__(self, personName, age): self.personName = personName self.age = age class Customer(Person): def __init__(s...
f1cb180e813e2a48281bb0699ad9f28e51b4ebe0
scottgreenup/desktop
/bin/btcm
682
3.65625
4
#!/usr/bin/env python import argparse parser = argparse.ArgumentParser( description='Calculate how much CC you need to buy.') parser.add_argument( '--price', type=float, help='The price of the currency') parser.add_argument( '--dollars', type=float, help='The dollars you want to spend') parser.add...
9cb2c1b54d76d02a1ab076471e7b4469807ae1aa
jaistarx/Hangman
/hangman.py
1,444
3.90625
4
# BE10105 Project S1 # Submitted by: # Akshay Raj PB # Gokul K # Reuben Thomas Peter # Teena Sabu import random print("HANGMAN Game") print("-------------------------------") def startGame(word, attempts, found): if attempts == 0: print("You Lost! The word is {0}".format(word)) ...
81ba0e7ed638e4c8b6ea894d55cc1ac8e9e89081
quantum-booty/advent-of-code-2020
/day7_tree(1st_part_working).py
5,872
3.90625
4
from typing import List import os print(os.getcwd()) os.chdir( '/home/henryw/Documents/Study/Computer_Programming_for_Data_Scientists/advent-of-code-2020/') """ Solution: This is a tree problem. Each bag can contain other types of bags. Build tree: find unique lines iterate these lines build list o...
fa5d696c5eaede47baf1d2ac408a5a30679d9fc7
quantum-booty/advent-of-code-2020
/day18_hacking_operators(by_strilanc).py
712
3.625
4
class T: def __init__(self, v): self.v = v def __add__(self, other): return T(self.v + other.v) def __sub__(self, other): return T(self.v * other.v) def __mul__(self, other): return T(self.v + other.v) def main(part2=True): with open("inputs/18.txt") as f: ...
8b5e6db864b4e43cb150f74c0f8e0117e598f348
quantum-booty/advent-of-code-2020
/day3.py
747
3.65625
4
from collections import namedtuple raw = """0011000000010001000100010000100100010100010101000110010001011000000101010000101000000001101100010001000110000101001000101""" width = 11 trees_tot = 0 for y in range(1, width): x = y * 3 % width pos = y * width + x trees_tot += int(raw[pos]) print(trees_tot) #...
06c921ba61a8893ec5a52de3567091741d3f4568
kkwietniewski/cdv
/programowanie_strukturalne/1_podstawy.py
1,531
3.71875
4
print("cdv") print("2") #-komentarz #potęga ''' potega = 2**10 print(potega) #pobieranie danych z klawatury imie = input("Podaj imie: ") #konkatenacja + print("Twoje imie podane z klawatury: " + imie) nazwisko = input("Podaj nazwisko: ") print("Twoje imie:" + imie + ", Twoje nazwisko: "+ nazwisko) dlugosc = len(naz...
1652f77c41ad5c0463d4aed8a4e2adb2545cf6ad
festevez1995/ThinkFast
/MeasureTime.py
1,154
3.5625
4
## @file MeasureTime.py # Brief doc for MeasureTime.py # # Detailed doc for MeasureTime.py # Implemented a timer in it's regular time mode. # # @author Fernando Estevez # # @copyright License Info # # @date January 24, 2021 # # @package MeasureTime # Brief doc for Measuring Time program section 3...
9b26449c371082057f49807226ed244eaccbe350
RodrigoJaar/Hello-World
/formatting.py
122
4
4
for i in range (1, 13): print("No. {0:2} squared is {1:^3} and cubed is {2:<4}" .format(i, i ** 2, i ** 3))
83757a54e0ca9d5c0acac7dbf949a800eac053ff
KudzanaiGomera/cs50_Projects
/cs50_web/Python/lopps.py
402
4.21875
4
# iterate through a list of numbers for i in [0,1,2,3,4,5,6]: print (f"iterate through a list of numbers: {i}") # iterate through a list of strings names = ["Kudzai", "Steve", "John", "Adam"] for name in names: print(f"iterate through a list of strings: {name}") # iterate through a string a print ech char ...
b6c9378a652ac7e48031e5e83753630d8a85f8dc
dreamer-1996/learning-python-total-novice
/while.py
197
3.953125
4
i = 0 while i<5: if i == 2: i =i+1 print ('I skipped here') continue elif i ==3: print ('Tada good bye') break print ('Hello World') i = i+1
c4a8f51c4a5ef1022971c71671e2c7478139bab7
vladdraql/ve1
/vlad2.py
196
3.703125
4
list_in = input("input: ") output = list_in.split(',') print(type(output)) output.sort() l = ','.join(output) print(l.upper()) output.sort(reverse=True) l = ','.join(output) print(l.lower())
59f0ef6b54bdf41eb053265c96d9f123b16246a3
aj3x/SudokuSolver
/SudokuSolver.py
4,917
4.09375
4
from Sudoku import Board from Square import Square from time import time class SudokuSolver: """ Attributes: decisions (BoardDecision): list of decisions for guesses made. """ def __init__(self, board=None): self.decisions = list() self.solved = False if board is not...
becdf7985610c0eb1c759c0e7a52c9274cc4c3e9
last-genius/gesture_recognition_game
/tree.py
2,369
3.96875
4
#!/usr/bin/env python3 """ Sultanov Andriy MIT License 2020 """ from node import Node from copy import deepcopy class Tree: """ Tree for the TicTacToe game, representing a set of possible turns and consequent game boards """ def __init__(self, starting_board, player="Player 1"): self._roo...
03f34c6d410dedc3cbcba44d59031923e16268e7
Bcdirito/algorithm_problems
/recursion/fibonacci/recursive.py
937
4.03125
4
# Runtime 32 ms, Memory Usage 11.7 MB class Solution(object): def fib(self, N): # declare a store list that will contain all of our fibonacci numbers store = [0, 1] # define a recursive function # the arguments will be our store list and a counter def recursive(lst,...
4fbefb354267d48c79e6f3bc9ebd69e837e20118
Bcdirito/algorithm_problems
/string_manipulation/keyboard_row/dictionary_solution.py
1,991
4.03125
4
# Runtime 20 ms, Memory Usage 11.8 MB def findWords(self, words): # define a dictionary where characters are the keys and their row is the value # the top row has a value of 1 # the mid row has a value of 2 # the bottom row has a value of 3 char_rows = { "q": 1, "w": 1, "e":...
d6e9bc96370e10c91605c2e76dffb7d70a21a2da
Bcdirito/algorithm_problems
/array_manipulation/halves_are_alike/basic.py
446
3.6875
4
def halvesAreAlike(s): mid_idx = int(len(s) / 2) first = s[0:mid_idx] second = s[mid_idx:] vowel_dict = {} first_vowels = 0 second_vowels = 0 for x in "aeiouAEIOU": vowel_dict[x] = "" for f in first: if f in vowel_dict: first_vowels += 1 for...
7362be4e5b6318a0229c5ae81a18f22de6e8480b
Bcdirito/algorithm_problems
/array_manipulation/tribonacci/basic.py
822
4.0625
4
# Runtime 20 ms, Memory Usage 12.9 MB class Solution: def tribonacci(self, n: int): # initialize a base tribonacci list trib_list = [0, 1, 1] # run the following logic n - 2 times # manipulate the value of the list to be the following (in order): # the value of the ...
c9ba9a5b92c493f0af2e85021b107526706d49e3
Bcdirito/algorithm_problems
/tree/average_of_levels_in_binary_tree/basic.py
1,660
3.890625
4
# Runtime 40 ms, Memory Usage 15.7 MB def averageOfLevels(root): # initialize two variables # the first is an empty dictionary, to hold all of the values by level # the second will be a list for all of the averages level_vals_dict = {} averages = [] # declare a helper method that takes in ...
9591e19b07c63edc6e85f172e3e51f3d2cabb25e
Bcdirito/algorithm_problems
/array_manipulation/best_time_to_buy_and_sell_stock/simple.py
861
3.625
4
# Runtime 100 ms, Memory Usage 12.6 MB class Solution(object): def maxProfit(self, prices): # declare variable stock = prices[0] # declare a profit variable # set profit to zero profit = 0 # iterate through the prices list for ...