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
32c43a9bea62ee96f47d252e7be232f6474aebad
hiratekatayama/math_puzzle
/leet/Flatten_Binary_Tree_to_Linked_List.py
791
3.71875
4
class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def flatten(self, root): def flat(root): print(root.val) if not root: return f...
ed83b585f13d84ddfdaee0598fc4e0e782af9b23
hiratekatayama/math_puzzle
/leet/middleoftheLinkedList.py
371
3.765625
4
class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def middleNode(self, head): A = [head] while A[-1].next: A.append(A[-1].next) return A[len(A)/2] if __name__ == '__main__': num = [1,2,3,4,5] li_node = LinstNode() ...
8675a475536a982cc48d6f07b964db69d5e8da59
hiratekatayama/math_puzzle
/leet/length_of_Longest_substring.py
571
3.578125
4
class Solution(object): def lengthOfLongestSubstring(self, s): max_len = 0 hash_lst = [] for i in s: hash_num = hash(i) if hash_num in hash_lst: if max_len < len(hash_lst): max_len = len(hash_lst) hash_lst = [] ...
1866685ebd775a278a6c198475bcdeb606d57aac
hiratekatayama/math_puzzle
/leet/LRU_Cache.py
3,679
3.65625
4
from collections import deque, OrderedDict class ListNode: def __init__(self, val): self.val = val self.next = None self.prev = None class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self....
81c532ef585d3a5749250a3b1d604d90e4c438e7
albertsuwandhi/Python-for-NE
/Misc/docstring_example.py
368
3.640625
4
def print_name(name): print(f"Your name is {name}") def print_age(age): ''' Print Age passed to the print_age() function ''' print(f"Your age is {age}") print_name.__doc__ = "Print name passed to the print_name() function" print(help(print_name)) print(help(print_age)) # For more detail info : ht...
df6c709986d91d8d96b4a67e1e20307e05a09521
albertsuwandhi/Python-for-NE
/Week2/Tuples.py
329
4.1875
4
#!/usr/bin/env python3 # Tuples are immutables my_tuple = (1, 'whatever',0.5) print("Type of my_tuples : ", type(my_tuple)) for i in my_tuple: print(i) #convert tuples to list my_list = list(my_tuple) print("Type of my_list : ", type(my_list)) for i in my_list: print(i) #list element can be changed my_list[0] =...
6c91a582d2d44d5e62b54cf0c82f7766d9c6a95e
albertsuwandhi/Python-for-NE
/Week5/Function2.py
875
3.921875
4
#!/usr/bin/env python3 my_list = ['192.168.10.10','admin','admin123'] my_dict ={ 'ip':'172.16.1.1', 'username':'admin', 'password':'Juniper123', } def print_ip(ip, username = 'albert', password = 'admin'): print("My IP : {} Username : {} Password : {}".format(ip, username, password)) # * pass list val...
07669066a5ce7a1561da978fc173c710f3ec7e3a
neonblueflame/upitdc-python
/homeworks/day2_business.py
1,836
4.21875
4
""" Programming in Business. Mark, a businessman, would like to purchase commodities necessary for his own sari-sari store. He would like to determine what commodity is the cheapest one for each type of products. You will help Mark by creating a program that processes a list of 5 strings. The format will be the na...
075b1414d4905077553ef1273963c6ab5aebf165
GBobzin/python-challenge
/PyPoll/main BAK.py
1,973
3.5625
4
import os import csv # Path to collect data from the Resources folder# #budget_csv = os.path.join( "./Resources", "election_data.csv") csv_path = "./Resources/election_data.csv" # Open file with open(csv_path) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # skip the first line as it contains...
cc6f6e0ab86138c3c3e06b64e9408c1ff1f5ca8b
ldocao/dataiku_census
/learning/visualize.py
1,866
3.71875
4
##function which project onto a 2D plane with name of two axis as arguments to plot the difference between prediction and validation import pandas as pd import numpy as np from constants import * import utils import matplotlib.pyplot as plt import ipdb import seaborn as sns def _map_categorical(x): """Return a ...
c73691ceccfb8bccf5d90d93c2e2b1a4eb809341
rsyamil/graph-search-algorithms
/bfsClass.py
2,859
3.734375
4
from collections import deque import pickle class BFS: def __init__(self, name=[], graph=0, start_id=0, end_id=0): self.name = name self.graph = graph self.start_id = start_id self.end_id = end_id self.found_flag = False def run_bfs(self): ########...
ec6176dddf843095ee3a4a40b8893ffcd6378561
mOeztuerk/LearnPythonTheHardWay
/ex19/ex19.py
1,125
4.03125
4
# define the function def cheese_and_crackers(cheese_count, boxes_of_crackers): print("You have {} cheeses!".format(cheese_count)) print("You have {} boxes of crackers".format(boxes_of_crackers)) print("Man that is enough for a party") print("Get a blanket.\n") # give arguments as numbers print("We can...
cdc3ed9862e362dc21b899ef3b059a6a9889d6ee
RobSullivan/cookbook-recipes
/iterating_in_reverse.py
938
4.53125
5
# -*- coding: utf-8 -*- """ This is a quote from the book: Reversed iteration only works if the object in question has a size that can be determined or if the object implements a __reversed__() special method. If neither of these can be satisfied, you’ll have to convert the object into a list first. Be aware th...
153b34e26caee2220ceccc6d84ae0f3079618978
10352769/dbs
/calculator/calculatorUI.py
3,399
4
4
#Student No.: 10352769 #Course: Programming for Big Data #Module: B8IT105 #Assignment: Continuous Assessment 1 '''Importing all defined scientific functions from calculator.py''' from calculator import * #Defining User Interface Menu for user to select which function to they want to user def show...
865a60ddfe79eef286f579281c9dd0d6db210069
MightyPhoenix/python-assgn
/Python Assingments/assgn1/ass1.11.py
432
3.53125
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 22:00:14 2019 @author: agnib """ sum = 0 GROCERY = {"Water" : 500, "Air" : 960, "Food" : 1700, "Shelter" : 30000, "Internet" : 20 } print("The Items with their Prices : \n") print(GROCERY) sum = GROCERY["Wa...
c387c83f6b6fa3238b7f4f571f86b747117cafa8
MightyPhoenix/python-assgn
/Python Assingments/assgn3/ass3.10.py
229
3.8125
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 11 22:07:29 2019 @author: agnib """ def rev(n): if n<10: return n else: return int(str(n%10) + str(rev(n//10))) n=int(input("Enter a number: ")) print(rev(n))
e80e0e8e5c72725cd2c23bab584474a0f7011207
MightyPhoenix/python-assgn
/Python Assingments/assgn4/ass4.10.py
277
3.875
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 12 15:36:58 2019 @author: agnib """ def pstv(num): if(num>=0): return 1 else: return 0 list1=[-1,2,3,-5,-8,10] print("Original list: ",list1) list2=list(filter(pstv,list1)) print("Filtered list: ",list2)
daf558c667ef71b8ede4b0e268b101b8078f5c5b
MightyPhoenix/python-assgn
/Python Assingments/assgn2/ass2.2.py
309
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 20:36:13 2019 @author: agnib """ lolim = int(input("Enter Lower Limit : ")) uplim = int(input("Enter Upper Limit : ")) for x in range(lolim,uplim+1): if(x%2==0): print(str(x)," -- Even Number!") else: print(str(x)," -- Odd Number!")
7bbee34d48d151d3ca49957555f2bb9f82237075
MightyPhoenix/python-assgn
/Python Assingments/assgn1/ass1.4.py
183
3.9375
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 1 16:31:13 2019 @author: agnib """ a = int(input("Enter a : ")) b = int(input("Enter b : ")) exp = a**b print("Result : "+str(exp))
6d3c019114b33d18bccf61d5ab9138fa6c583eb5
MightyPhoenix/python-assgn
/Python Assingments/assgn2/ass2.10.py
342
4.03125
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 23:05:23 2019 @author: agnib """ lst = [] while True: num = input("Enter List Value : ") if(num=="STOP"): break else: lst.append(int(num)) print(lst) largest = 0 for x in lst: if(x>largest): largest=x print("\nLarge...
1c6783776c96a39a4329f39c34855330c55e43cb
MightyPhoenix/python-assgn
/Python Assingments/assgn4/ass4.11.py
202
3.953125
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 12 15:39:23 2019 @author: agnib """ def sqr(num): return num**2 l=[1,2,3,4,5,6] print("Original list: ",l) l2=list(map(sqr,l)) print("New list: ",l2)
d3e99dccaa4741c5e116c5dc8926583483a4caa2
hk199915/258375dailycommits
/first.py
2,742
4
4
print("Hello World") print("Second Commit") print(None) ages={"Dave":24,"Marry":42,"Jhon":58} print(ages["Dave"]) print(ages["Marry"]) squares=[0,1,4,9,16,25,36,49,64,81] print(squares[2:6]) print(squares[3:8]) print(squares[0:1]) #string formatting nums=[4,5,6] msg="Numbers:{0} {1} {2}".format(nums[0],nums[1],nums...
bf18880348eb02f0b961b7f53babab9ed7d3951b
shmyaka/learn
/errors-exceptions/error-2.py
1,209
3.9375
4
# https://stepik.org/lesson/24463/step/9?unit=6771 # Реализуйте класс PositiveList, отнаследовав его от класса list, # для хранения положительных целых чисел. # Также реализуйте новое исключение NonPositiveError. # # В классе PositiveList переопределите метод append(self, x) таким образом, # чтобы при попытке добавить...
6c954d8fe48c14d2bb0947790c553ec0bd285996
jayxqt/xadminStudy
/xadminStudy/zuHeDemo.py
419
3.84375
4
class Turtle: def __init__(self, x): self.num = x class Fish: def __init__(self, x): self.num = x class Pool: def __init__(self, x, y): self.turtle = Turtle(x) self.fish = Fish(y) def printNum(self): print("水池里公有乌龟 %d 只,小鱼 %d 条" % (self.turtle.num, self.fish.nu...
b4ff9851641f8baea2c54f7dd16f206db16827de
isachard/console_text
/web.py
1,633
4.34375
4
"""Make a program that takes a user inputed website and turn it into console text. Like if they were to take a blog post what would show up is the text on the post Differents Links examples: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world https://www.stereogum.com/2025831/frou-frou-reu...
30757fe3f6adda7f06109a546e29aa2fa40f0123
SylarBurns/CodingTestPrep
/FullSearch/카펫.py
498
3.703125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 21 16:34:37 2021 @author: sokon """ def solution(brown, yellow): answer = [] for width in range(yellow, 0, -1): if yellow % width != 0: continue else: height = int(yellow / width) new_brown = (width+he...
ad05662ba53a84f5f5330dabfb78b4b491c03f98
SylarBurns/CodingTestPrep
/Heap/이중우선순위큐.py
586
3.90625
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 20 15:40:15 2021 @author: sokon """ def solution(operations): Q = [] for operation in operations: op = operation[:1] num = int(operation[2:]) if op == "I": Q.append(num) Q.sort() elif num == 1...
ed63e579a58c1b6ce8fb1b0c0ed7a7a723dba2b4
SylarBurns/CodingTestPrep
/Sort/H-Index.py
354
3.875
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 21 00:08:48 2021 @author: sokon """ def solution(citations): citations.sort(reverse=True) answer = 0 for c in citations: answer+=1 if c < answer: answer-=1 break return answer citations = [3, 0, 6,...
25fa2469a8ae999cba3256ec0de3d8b4bdff164c
kevinelong/intro_2020_07_20
/pizza.py
1,645
3.90625
4
""" Nouns Class/Objects (IS_A, HAS_A) Restaurant Menu Standard Pizzas Meat Lover, Veggie Delight, Custom Custom Pizza Topping, Cheese, Crust Drinks Order LineItem Pizza Choices Toppings ...
9a4b198020ef950b1405fbb6fda67587c5b9fac3
nsimonov0/DataStructures
/DataStructures/binarysearchtree.py
2,404
4.03125
4
import unittest class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None class BinarySearchTree(object): def __init__(self): self.root = None def get_root(self): return self.root def return_size(self): return self.get_size(self.root) def get_size(self, root)...
e977b5a52a1a466c7cc099a8aa8ee7c328a3dab3
sam-621/Platzi
/Python/enumeracion.py
275
3.984375
4
objective = int(input('Choose an int ')) response = 0 while response**2 < objective: response += 1 if response**2 == objective: print(f'La raiz cuadrada de {objective} is {response}') else: print(f'{objective} no tiene una raiz cuadrada exacta')
37f1971a1497b90c0108132651a41d0942f813fc
sam-621/Platzi
/Python/functions.py
1,211
3.953125
4
objective = int(input('Digite un numero que desea encontrar: ')) print('') print('1. Busqueda binaria') print('2. enumeracion exhaustiva') print('3. aproximacion') action = int(input('Digite la opcion por la cual desea buscar: ')) def binarySerarch(): times = 0 left = 0.0 right = max(1.0, objective) a...
2e93979e45cce6f13b4edcd52aa862783d7126ae
berlywu/qianchen
/resum.py
450
3.625
4
# 获取1-100中被6整除的数 # a_list = [] # for i in range(1,101): # if i % 6 == 0: # a_list.append(i) # print(a_list[-3:]) # 取出字符串出现一次最前面的字符 a = "abeecaf" list1 = [] for i in a: b = a.count(i) if b == 1: c = a.index(i) print(c) list1.append(c) str = sorted(list1) print(a[str[0]])...
e25c70ec9947a4cba488ad435b386b62b19dd765
redheavenliu/mbtk_work
/Python/PythonDemo/src/Python基础教程/S3.py
3,439
3.578125
4
# coding:utf-8=True def demo1(): # 字符串格式化 formats = '%% Hello,%s.%s enough for you? pi = %.3f' from math import pi values = ('world', 'Hot', pi) # values 只能为无组或字典 print formats % values # % Hello,world.Hot enough for you? pi = 3.142 print 'PI = %.5f' % pi # PI = 3.14159 from...
503d6a85d4dab907a9c0ea73cb14f4da2fed6174
brandonforster/PopDoxa
/python_scripts/read_files.py
5,338
3.75
4
def read_users(cursor): print("Reading in users.txt") users_file = list(open("users.txt")) for user_list in users_file: user = [x.strip().lower() for x in user_list.split(',')] username = user[0] + "_" + user[1] password = "userbot" user.insert(2, username) user.insert(3, password) query = """ INS...
d89df8cc1bffb63dd1f867650b54c55e141602ed
yuch7/CSC384-Artificial-Intelligence
/display_nonogram.py
2,535
4.125
4
from tkinter import Tk, Canvas def create_board_canvas(board): """ Create a Tkinter Canvas for displaying a Nogogram solution. Return an instance of Tk filled as a grid. board: list of lists of {0, 1} """ canvas = Tk() LARGER_SIZE = 600 # dynamically set the size of each square base...
a3c17359d356719af1dc71d78e0a3907c6ec2cfc
Cheereus/PythonMemory
/LaoJiu/20200723.py
503
3.84375
4
''' @Description: @Author: 陈十一 @Date: 2020-07-23 09:47:50 @LastEditTime: 2020-07-23 10:16:31 @LastEditors: 陈十一 ''' print("请输入m:") m = int(input()) # 数学推导可得奇数范围,然后生成对应列表 nums = [i for i in range(m * m - m + 1, m * m + m + 1, 2)] # 平平无奇的字符串拼接 output = str(m) + "*" + str(m) + "*" + str(m) + "\n=" + str(m*m*m) + "\n=" f...
d87b863e4f3e62a0c0dd4d36384e1eff429b49d9
Cheereus/PythonMemory
/LaoJiu/20200731.py
780
3.984375
4
''' @Description: @Author: 陈十一 @Date: 2020-07-31 10:06:23 LastEditTime: 2020-08-03 11:04:54 LastEditors: 陈十一 ''' # 想到 7 月 20 号作业也是关于因子的问题,于是借鉴了该作业的内容进行了修改 # 通过遍历检查整除来获得 n 的 m 以内全部因子数目,并输出其奇偶性 def factors(n, m): fNum = 0 # 因子数 for i in range(1, m + 1): # 遍历整除 if n % i == 0: fNum = fNum + 1 continue...
323a38ae00404712c8b05a95df6fcf1ae78a4917
troyand/timetable_jan
/timetable/university/utils.py
799
3.609375
4
def collapse_weeks(week_list, academic_term): def format_weeks(start, end): if start == end: return '%d' % start else: return '%d-%d' % ( start, end, ) result_list = [] tmp_start = None tmp_end = None for week in sor...
8efe7f71abfd23ab5de7337f5ab2d44d1ffaa1b3
ck-unifr/hackerrank-algorithms
/warmup/diagonal-difference.py
656
3.875
4
#https://www.hackerrank.com/challenges/diagonal-difference/problem #!/bin/python3 import os import sys # # Complete the diagonalDifference function below. # def diagonalDifference(a): length = len(a[0]) sum1 = 0 for i in range(length): sum1 += a[i][i] sum2 = 0 for i in range(length): ...
536210d6becb631a7e73e8a74f1f9752e491397c
sscreation143/projectGitAugust
/p.py
544
3.640625
4
# def sum(items): # for i in items: # i+=1 # return i # n = int(input("Enter the size of the list ")) # print("\n") # num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())[:n] # # print("User list: ", num_list) # sum(num_list) # x=0 # y=1 # x=y=...
b39efaac24491187306882183da77d9112a4849e
sscreation143/projectGitAugust
/SecondLargestinList.py
155
3.875
4
a=str(input("enter the comma sepreated value")) b=a.split(",") e=list() for i in b: d=e.append(int(i)) # s=set(e) # p=sorted(s)[-2] # print(p) print(e)
c797190e371c55781ce8be8e043fa1acee9ec065
MarikinPaulina/pw_pwzn_z2019
/lab_2/tasks/task_4.py
836
3.859375
4
def count_letters(msg): """ Zwraca pare (znak, liczba zliczeń) dla najczęściej występującego znaku w wiadomości. W przypadku równości zliczeń wartości sortowane są alfabetycznie. :param msg: Message to count chars in. :type msg: str :return: Most frequent pair char - count in message. :rtyp...
b53cec167a2b62a43edb6a2be171d39df1a1079c
NikitaNar/Learn-Python
/project/lesson1/lists.py
426
3.890625
4
a=[3,5,7,9,10/5] print(a, 'созданный список') b='python' a.append(b) print(a,'добавлен новый элемент') print(len(a), 'количество элементов') print(a[:1], 'первый элемент') с=len(a)-1 print(a[с:], 'последний элемент') print(a[1:5], 'со 2 по 4 элемент') a.remove('python') print(a, 'удалён элемент python')
031a92ddd66ee51c56b3b26c12c8e5a2cfbb43e6
NikitaNar/Learn-Python
/project/lesson1/hello.py
171
3.515625
4
print("Привет мир!") print("Привет программист!") print(2+2) b=10/3 b=int(b) print(b, 'целое') print(10/3) name='Nikita' print(name)
9d7c458469e1303571f12dfa15fa71133c5d2355
suterm0/Assignment9
/Assignment10.py
1,439
4.34375
4
# Michael Suter # Assignment 9 & 10 - checking to see if a string is the same reversable # 3/31/20 def choice(): answer = int(input("1 to check for a palindrome, 2 to exit!>")) while answer != 1 and 2: choice() if answer == 1: punc_string = input("enter your string>") return punc_s...
85a27b3a65aad4f22b23ceca5762bb7be5e8fc9e
happyjun190/machine-learning-py
/recursion.py
326
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def recursion(n=10): print("===>", n) if n < 1: return 0 if n == 1: return 1 return n * recursion(n-1) def recursion2(n, m): if n<1: return 0 if n==1: return m return recursion2(n-1, n*m) print(recursion2(1000,...
abfb42e156ea3e6efa97e2c9a973a227adc30f8d
liberbell/py34
/basic/variables.py
121
3.71875
4
a = 3 print(a) b = 10 b = 30 print(b) price_bread = 100 tax = 0.1 print(price_bread * tax) name = "elton" print(name)
0f185d16ad186bc44dca5dd7d7dc338c2243f583
chng3/Python_work
/第五章练习题/5-2.py
703
4.15625
4
#5-1 条件测试 myday = 'Thursday' print("Is mayday == 'Thursday'? I predict True.") print(myday == 'Thursday') print("\nIs myday == 'Sunday'? I predict False.") print(myday == 'Sunday') print("\n") #5-2 year_0 = 12 year_1 = 13 print(year_0 == year_1) print(year_0 != year_1) print(year_0 > year_1) print(year_0 < year_1)...
b7fee1d7ea34b207170d279f972f3d1be3d7a71d
chng3/Python_work
/第四章练习题/4-9.py
358
3.96875
4
#4-9练习 #4-3 for value in range(1,21): print(value) #4-6 values = [] for value in range(1,21,2): values.append(value) print(values) #4-7 for value in range(3,31,3): print(value) #4-8 cubes = [] for cube in range(1,11): cubes.append(cube**3) print(cubes) #4-9 #使用列表解析 cubes = [cube**3 for cube in rang...
d05d27efc2fbc6075cb185e263430d513a20841e
chng3/Python_work
/Chapter_4_Working with Lists/dimensions_2.py
480
3.90625
4
#遍历元组中的所有值 dimensions = (200, 50) for dimension in dimensions: #像列表一样,使用for循环来遍历元组中的所有值 print(dimension) #修改元组变量 #虽然元组元素比可以直接修改,但可以重新定义整个元组 print("Original dimensions:") for dimension in dimensions: print(dimension) dimensions = (400, 100) #重新定义元组 print("\nModified dimensions:") for dimension in dimensi...
c876c4cd192aca9ce096e2c8165bbedf258d7f1d
chng3/Python_work
/第五章练习题/5-7.py
1,869
3.765625
4
# 5-3 外星人颜色1 #第一个版本 alien_color = 'green' if alien_color == 'green': print("玩家获得5个点") #第二个版本 if alien_color == 'red': print("") # 5-4外星人颜色2 # 第一个版本 alien_color = 'green' if alien_color == 'green': print("你因射杀该外星人获得了5个点") else: print("你获得10个点") # 第二个版本 alien_color = 'red' if alien_color =...
3c3bbefb54ddf8e30798a9115ba4de97aca0d396
chng3/Python_work
/第四章练习题/4-12.py
719
4.46875
4
#4-10 my_foods = ['pizza', 'falafel', 'carrot cake', 'chocolate'] print("The first three items in the list are:") print(my_foods[:3]) print("Three items from the middle of the list are:") print(my_foods[1:3]) print("The last items in the list are:") print(my_foods[-3:]) #4-11 你的披萨和我的披萨 pizzas = ['tomato', 'banana'...
42239a3ba558e6770d0d8a9f7670e55730db3bdb
chng3/Python_work
/Chapter_4_Working with Lists/dimensions.py
427
3.71875
4
#元组 #定义元组:不可修改的值成为不可变的,而不可变的列表被称为元组 dimensions = (200, 50) #创建一个大小不可改变的矩形,存储其不可以改变的长度和宽度 print(dimensions[0]) #打印元组的第一个元素 print(dimensions[1]) #打印元组的第二个元素 #尝试修改元组的元素,体验其不可改变的性质,程序将报错 dimensions[0] = 250
3add6ccef6caaad5fd5985bf304bda3f45624c58
chng3/Python_work
/第七章练习题/7-1-3.py
458
3.8125
4
# 7-1 汽车租赁 car_name = input("What car do you want? ") print("Let me see if I can find you a " + car_name + ".") # 7-2 餐馆订位 number = input("一共有多少人用餐?") number = int(number) if number > 8: print("没有空桌") else: print("有空桌") # 7-3 10的整数倍 number = input("请输入数字: ") if int(number) % 10: print("该数字不是10的整数倍。...
3f57b82c183f6253829a686a7cfd50f3f77fbb99
KhaydarovaDiana/Tehnikum_HWs
/hw_1/problem3.py
600
4.03125
4
print('Problem 3') print('Hi! I`m Mahmud! First of all, let`s check your age!') age=int(input()) if age>=18: print('Are you a boy or a girl?') else: print('Sorry, we can`t continue our conversation:(') gender=input() a=('girl') if gender==a: print('Welcome! I can help you with math! Choose two numbers!') else: ...
37b1d93aa5b914f5c32a92b10f947825c8e8664f
Mohamed2del/Computer-Vision
/Types of features and Image segmentation/K-means/kmeans.py
2,082
3.53125
4
import numpy as np import matplotlib.pyplot as plt import cv2 ### -----------------------------Import resources and display image---------------------------- # Read in the image ## TODO: Check out the images directory to see other images you can work with # And select one! image = cv2.imread('monarch.jpg') # Change ...
087b74fe13142373dce932bc552da1ceed7d5096
Mohamed2del/Computer-Vision
/Image Representation and Classification/RGB2GRAY/rgb2gray.py
338
3.90625
4
import cv2 #RGB mat for storing RGB image RGB = cv2.imread('tom.jpg') #Gray mat for storing result of conversion from RGB to Gray Gray = cv2.cvtColor(RGB,cv2.COLOR_BGR2GRAY) #to display an image in window cv2.imshow('Gray Image',Gray) #waits for a pressed key k = cv2.waitKey(0) #Esc key to stop if k == 27: cv2.de...
bf7e090dbf827fb208657382a29fb6377617c511
NicolasSepulveda98/NSepulveda_repoSoluciones
/Laboratorios/Proyecto.py
824
3.921875
4
import random def comprueba_numero(numero, intento): if(numero==intento): print() print("Felicitaciones!") return True elif(numero>intento): print("El numero ingresado es Menor") print() return False else: print() print("El numero i...
5c715520c2211599cdd7e5467985dddec4680105
abpauwel/Memoire2020
/code/Usefull_function.py
8,999
3.703125
4
__author__ = "Jérôme Dewandre" import pandas as pd import numpy as np import os from datetime import datetime, timedelta,date ''' This fuction handle the '1A2A3' fromat to usefull features for the machine learning algorithm and split the cell into a certain number of column equals to the number_of_diffrerent_r...
9e248e933c8438b80e1aeb3c72ff31bb7228b0c1
abpauwel/Memoire2020
/code/Mostimportantfeature.py
6,163
3.6875
4
import numpy as np import pandas as pd from sklearn import tree from sklearn.metrics import balanced_accuracy_score from sklearn.model_selection import train_test_split # Python code to merge dict using a single # expression def Merge(dict1, dict2): res = {**dict1, **dict2} return res '''Find in a string a d...
366da947801913afff60f221c28bef300c73613c
estebanfallasf/massexec
/source/8.5/user_20110415.py
918
3.65625
4
import getpass import os, sys class userClass: l_username = "" l_userpassword1 = "" l_userpassword2 = "" def get_user(self): self.l_username = os.getlogin() pr = "Enter your username ["+self.l_username+"]: " print("press ctrl+c to exit.") try: l_user = raw_input(pr) l_user = l_user.strip() if...
86e74e6b83be3976ba48f90728a50334811df18a
cycho04/python-automation
/game-inventory.py
1,879
4.3125
4
# You are creating a fantasy video game. # The data structure to model the player’s inventory will be a dictionary where the keys are string values # describing the item in the inventory and the value is an integer value detailing how many of that item the player has. # For example, the dictionary value {'rope': 1, ...
18703f4090f0a4bcd91b2ff0c9ab5159bf6fc90b
rootuseralpha/pyplay
/Code Fights/Arcade/The Core/05 - List Forest Edge/42 - Make Array Consecutive 2.py
350
3.546875
4
def makeArrayConsecutive2(statues): statues.sort() print(statues) count = 0 for i in range(len(statues)-1): j = statues[i] while j+1 < statues[i + 1]: count += 1 j += 1 return count # smarter: '''def makeArrayConsecutive2(statues): return max(statues)-m...
4873920927033d1dede416ec0b0a713565a01686
rootuseralpha/pyplay
/Code Fights/Arcade/Intro/6 - Rains of Reason/26 - evenDigitsOnly.py
429
3.546875
4
def evenDigitsOnly(n): st = str(n) for i in st: if not int(i) % 2 == 0: return False return True print(evenDigitsOnly(248622)) print(evenDigitsOnly(642386)) print(evenDigitsOnly(248842)) print(evenDigitsOnly(1)) print(evenDigitsOnly(8)) print(evenDigitsOnly(2462487)) print(evenDigitsO...
8727f53c89034d681eee871d3b9d0131564676b7
rootuseralpha/pyplay
/Code Fights/Arcade/The Core/05 - List Forest Edge/40 - Is Smooth.py
219
3.65625
4
def isSmooth(arr): mid = len(arr)//2 if len(arr) % 2 == 0: middle_value = arr[mid] + arr[mid - 1] else: middle_value = arr[mid] return arr[0] == middle_value and arr[-1] == middle_value
44513e0baefe17788d831e5495c5426f0a1cae9e
petered/artemis
/artemis/general/time_parser.py
796
3.96875
4
import re from datetime import timedelta regex = re.compile(r'^((?P<days>[\.\d]+?)d)?((?P<hours>[\.\d]+?)h)?((?P<minutes>[\.\d]+?)m)?((?P<seconds>[\.\d]+?)s)?$') def parse_time(time_str): """ Parse a time string e.g. (2h13m) into a timedelta object. Modified from virhilo's answer at https://stackover...
b038e74b22da1b60c2c9caff29c4bae2a6541b9b
Mit3238/Information-Security
/Hill-Cipher.py
1,664
3.609375
4
def multipy(arr1, arr2): c = [0 for i in range(3)] for i in range(3): for j in range(1): for k in range(3): c[i] += (int(arr1[i][k]) * int(arr2[k][j])) c[i] = c[i] % 26 return c def encript(string, key): string = string.upper().replace(' ', '') abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if len(string) % 3...
fc68579b36277493e624b0401ac7be7fdf1b4f5c
AdityaKuranjekarMYCAPTAIN/Python-Project-2-PART-1-
/Fibonacci.py
253
4.125
4
n = int(input("How many numbers of fibonacci series do you want to see?: ")) x = 0 y = 1 z = 0 i = 1 while (n >= i): print (z) x = y y = z z = x+y i += 1 #>>>>>>>>>>>>>>>>>>.................HAPPY CODING....................<<<<<<<<<<<<<<<<<<<<<<<
33ab47df2e329a0b93be1a133f91f1df66b848f3
docmarionum1/py65c
/tests/files/fib.py
326
3.53125
4
#Allocate list for output 0-9 o = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0] i = 2 while i < 10: o[i] = o[i-1] + o[i-2] i = i + 1 #TODO: Add More implemnations of fib (i.e. o = list(10), i+=1 and function for fib) def fib(n): if n < 2: return 1 else: return fib(n-1) + fib(n-2) a = ...
759d0018a3189533afe8067bd7176e4a5f959016
andreasdjokic/piratize
/piratize.py
1,195
3.53125
4
from piratize_translate import * class PartyRepelledError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class NoTreasureError(Exception): def __init__(self, value): self.value = value def __str__(self): ...
ff91e96f14eb8dcd4f28f521b8f5f89344f60b86
ohwowitsjit/WK_3
/2.py
245
3.59375
4
start_num = int(input("Enter the number n:")); end_num = int(input("Enter the number n:")); file = open("perfect_squares.txt", "a") file.write("\n\n"); for i in range(1, end_num+1): file.write(str(i+start_num) + "\n") file.close();
fcdef4fa15673593c53bf302b0cddf9eb9545a27
rajmohanram/PyLearn
/004-Functions/03_function.py
2,380
3.90625
4
# functions: Positional argument import ipaddress from pprint import pprint # Input to functions - arguments - parameters within the brackets/paranthesis # - positional argument - required argument # func(ipaddr, pfx_len) - 2 arguments MUST be passed while calling this function # - keyword argument # ...
a11d5793dcab552a17f1e809708b23bffe29c544
rajmohanram/PyLearn
/900-parallelism/00-basics.py
636
3.875
4
import multiprocessing print("Number of cpu : ", multiprocessing.cpu_count()) """ Classes for building parallel program Process Queue Lock Process class set up another python process provide it to run code a way for the parent application to control execution functions sta...
70a3ee1c969065898bdb77d2aa0b8004a0364fbf
rajmohanram/PyLearn
/003_Conditional_Loop/06_for_loop_dict.py
582
4.5
4
# let's look at an examples of for loop # - using a dictionary # define an interfaces dictionary - items: interface names interface = {'name': 'GigabitEthernet0/2', 'mode': 'trunk', 'vlan': [10, 20, 30], 'portfast_enabled': False} # let's check the items() method for dictionary interface_items = interface.items() p...
0cd762b867fbd84b8319eeb89b10c0fcb73675ef
rajmohanram/PyLearn
/004-Functions/01_function_intro.py
758
4.46875
4
""" Functions: - Allows reuse of code - To create modular program - DRY - Don't Repeat Yourselves """ # def: keyword to define a function # hello_func(): name of the function - Prints a string when called # () - used to get the parameters: No parameters / arguments used in this function def hello_func(): ...
d09b435a69542f7e424f9fe050c29447f5379e7b
rajmohanram/PyLearn
/004-Functions/02_function.py
1,658
4.0625
4
# functions: Positional argument import ipaddress from pprint import pprint # use this function whenever an IP address needs to be analyzed - Code Reuse # positional arguments # - IP address # - Prefix Length # Process the Inputs given and find the following # - Netmask / Network / IP Address Type def analyze_i...
4b8ac89f0e48125d88e2b0d050d1fd1cef291976
rajmohanram/PyLearn
/002_Data_Types/09_challenge_01_smart.py
802
3.921875
4
""" Challenge - 01 Given input: ip_address = "192.168.0.1" subnet_mask = "255.255.255.0" Required output: ip_address_cidr = "192.168.0.1/24" """ # write down your code here and try to get the output required !!! # Code Logic: # use built-in module ipaddr to achie...
baca96e1f48f199cebec358ae1b478374a58a649
NamrataBakre/Data-Intensive-Computing
/Assignment2/Code and Output/Part3/Reducer.py
778
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 13 22:37:31 2020 @author: namratabakre """ import sys import os import re import fileinput d={} def preprocessing(word): word = word.lower() alphanumeric = "" for character in word: if character.isalnum(): ...
f68f8394274202943bc76da8f5f599ea7774561f
YuliaAzarova/13122020
/swap шифр.py
285
3.703125
4
s = 'етивафла в ми еынжолоповиторп ан ястюянем ывкуб шабта ерфиш в' for key in range(1,27): ans = '' for elem in s: x = ord(elem) - key if x < ord('a'): x += 26 ans += chr(x) print(ans)
fc1ef04a6e7b3e4f984c8d04f154d57e5a400bd4
LukeB98/Coding-share
/Coding/Python/Derivative.py
830
4.03125
4
from fractions import Fraction while True: list_quadratic = list(input('>')) #form F(x) = ax^c #Magnitude position = list_quadratic.index('x') try: if list_quadratic[0] == 'x': a = 1 else: a = Fraction(list_quadratic[position - 1]) except: ...
d8d9a875d2a71f214c7041c2df0b0fcf298e4c8b
jda5/scratch-neural-network
/activation.py
2,158
4.21875
4
import numpy as np class ReLU: def __init__(self): self.next = None self.prev = None def forward(self, inputs): """ Implements Rectified Linear Unit (ReLU) function - all input values less than zero are replaced with zero. Finally it sets two new attributes: (1) the i...
46ae73ce02028c21d462c8d091624f5a290601e9
BigNianNGS/AI
/python_high/iterator1.py
642
3.734375
4
# -*- coding: utf-8 -*- # @Time :2018/3/1 下午5:08 # @Author :李二狗 # @Site : # @File :iterator1.py # @Software :PyCharm #迭代器: 排列组合 笛卡尔积 串联迭代器 import itertools x = range(1,5) # 排列 从四个里面选三个 com1 = itertools.combinations(x,3) # for i in com1: # print(i) #组合 com2 = itertools.permutations(x,3) # for i i...
807fc1754a933a1ea51911dea30147c384a6a987
BigNianNGS/AI
/python_base/class_python.py
189
3.5625
4
from collections import OrderedDict order1 = OrderedDict() order1['name'] = 'lichan' order1['age'] = 18 print(order1) for name,age in order1.items(): print(name + ' and ' + str(age))
ad0394942b9f519406945e58c72e7da25dda27eb
BigNianNGS/AI
/python_base/class2.py
1,562
4.3125
4
class Dog(): """构造方法""" def __init__(self,name,age,weight=5): self.name = name self.age = age self.weight = weight # ~ return self 不需要,程序已经内设 def set_weight(self,weight): self.weight = weight def eat_bone(self): print(self.name + 'is eating bone') def bark(self): print(self.name+' is ba...
eeb07d2c1c4c617feef73101d99f9093483d9a6d
MachineLearningIsEasy/python_lesson_5
/my_math_module.py
585
3.984375
4
def my_add(x,y): return x+y def my_sub(x,y): return x-y def my_mul(x,y): return x*y def my_div(x,y): return a/b # Числа Фибоначчи # f_n = f_{n-1} + f_{n-2} # 1, 1, 2, 3, 5, 8, 13 def fib_num(n): if n == 1: return 1 elif n == 2:return 1 else: return fib_num(n-1) + fib_num(n-2) fib_num_l = l...
6cfc4a7f3fceaaed1e0b99f22071ee07706a78f8
RuninaAnastasiia/pygame_project
/snake.py
6,413
3.640625
4
import pygame from random import randrange # задаем размер рабочего поля и единичного отрезка змейки, а также размер печеньки RES = 600 SIZE = 50 def load_image(name, colorkey=None): fullname = name # если файл не существует, то выходим try: image = pygame.image.load(fullname) except pygame.e...
0e025176331ea401c905e6906c0c5238d46ca399
jbert/advent-of-code-2018
/day13.py
6,214
3.6875
4
#!/usr/bin/python3 import re import os from collections import deque import time def main(): lines = r"""/->-\ | | /----\ | /-+--+-\ | | | | | v | \-+-/ \-+--/ \------/ """.split('\n') with open("day13-input.txt") as f: lines = f.readlines() runner = Runner(lines) part1(run...
72e430dc063b5a6fdb6df5813e1d39aff035e759
jbert/advent-of-code-2018
/day5.py
1,329
3.59375
4
#!/usr/bin/python3 import string def main(): with open("day5-input.txt") as f: polymer = f.readline() # polymer = polymer = 'dabAcCaCBAcCcaDA\n' polymer = polymer.rstrip('\n') polymer = list(polymer) # part1(polymer) part2(polymer) def part1(polymer): polymer = fully_reduce(polymer...
b1758c63e9f9f7ce25c8fea2170ee59f37cf57ef
qkrthdus605/Algorithm_Study
/step_3/2739.py
96
3.640625
4
N = int(input()) for i in range(1, 10): result = N*i print(N, "*", i, "=", result) i += i
7b1ddf990d3b7bc218965d2d78c6f8bc592074b7
mytree/test_code
/ex_python/two_point_distance.py
380
3.515625
4
import math class Point2D: def __init__(self, x, y): self.x = x self.y = y p1 = Point2D(x=30,y=20) # 점 1 p2 = Point2D(x=60,y=50) # 점 2 a = p2.x - p1.x # 선 a의 길이 b = p2.y - p1.y # 선 b의 길이 c = math.sqrt((a * a) + (b * b)) # (a*a)+(b*b)의 제곱근을 구함 print(c) ...
529d3601c91fa839b3082c027e1d3eb9a27d31bd
NaryTang/python-challenge
/PyPoll/main.py
1,683
3.546875
4
import os import csv import operator #import to use "max" csvpath = os.path.join('Resources', 'election_data.csv') #starting vote counter Total_votes = 0 #creating dictionary mydictionary ={} #open csv file with open(csvpath, encoding='utf8', newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') ...
be4afef43c17f13a19b9e25ff242b517256d6fd8
MORVf/Lessons_python_part2
/Lesson_26.py
711
3.875
4
"""Текст задания. Вам дана последовательность строк. В каждой строке замените первое вхождение слова, состоящего только из латинских букв "a" (регистр не важен), на слово "argh". Sample Input: There’ll be no more "Aaaaaaaaaaaaaaa" AaAaAaA AaAaAaA Sample Output: There’ll be no more "argh" argh AaAaAaA """ __versio...
e085cf73c13c7aacefaef38d73d1642bd77314a8
rystills/OpSys-Project2
/Process.py
1,857
4.09375
4
""" The Process class represents a single process on our CPU """ class Process(): """ Process contructor: creates a new process with the specified properties @param pid: the string ID given to the process by the input file; used for tie-breaking @param memSize: the number of memory frames required by th...
e5c04d5c2654a654f2672726e76ca2da4aaeddc5
codes-books/python-scientific-calculation
/16/swig_numpy/test.py
383
3.5
4
# -*- coding: utf-8 -*- import numpy as np import demo print "----- ARGOUT_ARRAY1, DIM1 -----" print demo.drange(10) print "----- ARGOUT_ARRAY2[3][3] -----" print demo.rot2d(np.pi/4) print "----- IN_ARRAY1, DIM1 -----" print demo.sum_power([1,2,3]) x = np.arange(10) print demo.sum_power(x[::2]) print "----- INPLACE...
594edacffdac059e2f6b34a514d402659b9ed4a1
leon-lei/learning-materials
/binary-search/recursive_binary_search.py
929
4.1875
4
# Returns index of x in arr if present, else -1 def binarySearch(arr, left, right, x): # Check base case if right >= left: mid = int(left + (right - left)/2) # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid...
9fa3a5f81a84dfba1f365082069f180aeb545692
leon-lei/learning-materials
/basics/pickle_practice.py
534
3.796875
4
import pickle # create a dictionary object for pickling example_dict = {1:'curry', 2:'ramen', 3:'nikuman'} # create a pickle file with write binary pickle_out = open('dict.pickle','wb') # dump the object into the pickle file pickle.dump(example_dict, pickle_out) # close the pickle fi...
a371321ea433f31655476ee489f7603cd494acc9
leon-lei/learning-materials
/data_science/pandas_tutorials/pandas_practice7_operations.py
1,249
3.78125
4
import pandas as pd df = pd.DataFrame({'col1':[1,2,3,4],'col2':[444,555,666,444],'col3':['abc','def','ghi','xyz']}) print(df.head()) # Returns all unique values in the column # array([444, 555, 666]) print('\ndf["col2"].unique()') print(df['col2'].unique()) # Returns number of unique values in the column # 3 print(...
9ec09f195c013e5f91ddc583c22eda944c0b2f17
leon-lei/learning-materials
/data_science/matplotlib_tutorials/matplotlib_practice1.py
4,712
4.28125
4
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 11) y = x ** 2 print('X\n', x) print('Y\n', y) # Plot out the x and y coordinates plt.plot(x, y, 'r') # 'r' is the color red plt.xlabel('X Axis Title') plt.ylabel('Y Axis Title') plt.title('String Title') plt.show() # creating multiplots on sa...
fd0024154e71b74836f53e3e0d734849f356ed99
leon-lei/learning-materials
/data_science/pandas_tutorials/pandas_practice3_quandl_api_html.py
698
3.53125
4
import quandl import pandas as pd # use the api key from the account to access a Freddie Mac database through quandl api # assign the dataset to a data frame for viewing api_key = '' df = quandl.get('FMAC/HPI_AK', authtoken=api_key) print(df.head()) # fiddy_states is a list of data frames fiddy_states = pd.read_html(...