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
2bcc8e632ec8e36f1a63ab95315ee433f4bbc5c2
skdls-/Python
/Week0/Week0-2/Count_Words_test.py
745
3.765625
4
import unittest from Count_Words import count_words class count_words_test(unittest.TestCase): def test_empty_count_words(self): self.assertEqual({}, count_words([])) def test_count_words(self): self.assertEqual(count_words(['apple', 'banana', 'apple', 'pie']), {'app...
d26ed51f6764a373bbd04991ed657f3b6c86a1b1
skdls-/Python
/Week0/Week0-3/pizza(bez load).py
1,977
3.640625
4
import os import sys from time import time from datetime import datetime orders = {} def pizza(): while True: last_command = "" command = input("Enter command>") if command == "finish": if last_command != "save": print ( "You haven't saved ...
34b4be9725c79b1a9fe2870698afba52e675f2ba
ToxicRabbittt/CodeForces
/Beautiful Year 271A.py
176
3.5
4
y = int(input()) x = y+1 while True: for i in range(0,10): if str(x).count(str(i)) > 1: x+=1 break else: print(x) break
13008c7d7af1c8bc5971aba5acbf6107c4920791
ToxicRabbittt/CodeForces
/Bit++ 282A.py
140
3.8125
4
x = 0 for _ in range(int(input())): string = input() if "++" in string: x+=1 elif "--" in string: x-=1 print(x)
edca001ae4dd97c5081f1c6421a457eec39f4ff4
yasab27/HelpOthers
/ps7twoD/ps7pr2.py
1,179
4.25
4
# # ps7pr2.py (Problem Set 7, Problem 2) # # 2-D Lists # # Computer Science 111 # # If you worked with a partner, put his or her contact info below: # partner's name: # partner's email: # # IMPORTANT: This file is for your solutions to Problem 2. # Your solutions to problem 3 should go in ps7pr3.py instead. import r...
ced9cbdba99059814749f6d751a7fd59e6f755ab
dpostal/giapy
/earth_tools/earth_two_d.py
16,765
3.75
4
import numpy as np import cPickle as pickle def _list2UT(l, N): """Return a list of the rows of an NxN upper triangular""" mat = [] start = 0 for i in range(N): mat.append(l[start:start+N-i]) start += N-i return mat def _UT2list(m): """Return the elements of an NxN upper triang...
27405132fda5c606c8c4857545166912d769361e
pictexam/cl3new
/d3.py
1,128
3.671875
4
import hashlib import random def check_prime(a): if(a<2): return False elif(a==2): return True else: count = 0 for x in range(3,a): if(a%x==0): count+=1 if(count>0): return False return True def Check_p_q(p,q): if(not check_prime(p)): print("P is not prime") return False ...
af54c271eeb1bca299aeeaf466be02c8137fc6e2
HaxorKris/Hackbright
/coursework/Ex06/wordcount.py
946
3.578125
4
from sys import argv script, filename = argv source_file = open(filename, "r") text = source_file.read() # gives a giant string source_file.close() lower_case = text.lower() # "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{}|~" words = lower_case.split() dictionary = {} # start an empty dictionary for i in words: q = i.stri...
129482d38291fe033010b9520846e69df5d8d5bc
msik-404/Ascii_transformer
/ascii_transformer/txt_to_image.py
1,621
3.625
4
from PIL import Image, ImageDraw class TxtToImage: def __init__(self): self.path = None self.symbols_array = None def open(self, path): """ Loads txt file to convert to image. :param path: path to txt file :return: Returns nothing """ self.path...
8ed7f544dd1ba222cf0b96ee7f1e3a2b18b9e993
krathee015/Python_assignment
/Assignment4-task7/task7_exc2.py
722
4.375
4
# Define a class named Shape and its subclass Square. The Square class has an init function which # takes length as argument. Both classes have an area function which can print the area of the shape # where Shape’s area is 0 by default. class Shape: def area(self): self.area_var = 0 print("area of...
83e8f766412009bd71dea93ed83a1d1f17414290
krathee015/Python_assignment
/Assignment3/task5/task5_exc2.py
376
4.34375
4
print("Exercise 2") # Write a program in Python to allow the user to open a file by using the argv module. If the # entered name is incorrect throw an exception and ask them to enter the name again. Make sure # to use read only mode. import sys try: with open(sys.argv[1],"r") as f: print(f.read()) except: ...
05c4af85244760104a102da318172a2f208055a8
krathee015/Python_assignment
/Assignment1/Task2/task2_exc5.py
124
3.71875
4
print ("Exercise 5") for num in range (2000,3200): if (num %7 == 0 and not(num %5 == 0)): print (num)
d282703436352013daf16052b74fd03110c645c8
krathee015/Python_assignment
/Assignment1/Task2/tasktwo_exercise2.py
984
4.125
4
print ("Exercise 2") result = 0 num1 = eval(input("Enter first number: ")) num2 = eval(input("Enter second number: ")) user_enter = eval(input("Enter 1 for Addition, 2 for Subtraction, 3 for Division, 4 for Multiplication, 5 for Average: ")) if (user_enter == 1): result = num1 + num2 print ("Addition of two ...
dd9ea2896ed744b8c1947ccd024f325a8345eb2b
krathee015/Python_assignment
/Assignment2/Task4/task4_exc1.py
188
4.5
4
# Exercise 1: Write a program to reverse a string def str_reverse(str): return str[::-1] input_str = input("Enter the string: ") print("After reverse: ",str_reverse(input_str))
e34c24f3f50b8f4620d42829d7a3c915ac5a016d
krathee015/Python_assignment
/Assignment2/Task4/task4_exc8.py
167
3.515625
4
# generate and print a tuple where the values are square of numbers between 1 and 20 (both 1 and 20 included) lst = map(lambda x: x**2, range(1,21)) print(tuple(lst))
a686bfd2630b68c5ff0cef47b5fbf4f77bd1d6dc
zhaokun00/Anaconda
/src/python/python中的字典类型.py
705
4.03125
4
""" 字典(dictionary)是pythonn中另一个非常有用的内置数据类型 列表是有序的对象集合,字典是无序的对象集合,两者之间的区别在于:字典当中的元素是通过键值来存取的,而不是通过偏移来存取 字典是一种映射类型,字典用{}标识,它是一个无序的键值对集合 键必须死样不可变类型,在同一字典中key必须是唯一的 """ # 示例1 dict1 = {} print("type(dict1):",type(dict1)) # 往字典中放入数据 dict1["name"] = "zhaokun" dict1["age"] = 30 print("name:",dict1["name"]); # 示例2,初始化时往字典中放...
3959f83bb97f248613cdb70c44863002777d2c1b
zhaokun00/Anaconda
/src/python/python中的randrom函数.py
795
4.09375
4
""" random()方法返回随机生成的一个实数,它在[0,1)范围内 语法: import random random.random() 注意:random()是不能直接访问的,需要导入random模块,然后通过random静态对象调用该方法 """ import random # 产生一个0到1之间的随机浮点数 print("随机数:",random.random()) # 产生一个1到100的一个整数型随机数 print("随机数:",random.randint(1,100)) # 产生一个从100到200间隔为5的随机整数 print("随机数:",random.randrange(100,200,5)) ...
2f67c527c9ac69cc1f5e6733fb0aba6b13648f96
Fastener-Counter/ECE445Project
/src/GUI/functions/plots.py
6,299
3.75
4
# -*- coding: utf-8 -*- """ Various methods of drawing scrolling plots. """ #import initExample ## Add path to library (just for examples; you do not need this) import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np import serieRead_test import sys # win = pg.GraphicsLayoutWidget(show=True) ...
38af0bdf3413e574a75753a82b7be4aaffeac4c0
HuanbinWu/testgit
/pythonjike/thread/con_cus.py
1,590
3.96875
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author:HuanBing from threading import Thread, current_thread import time import random from queue import Queue queue = Queue(5) # 定义队列长度5 # 生产者可以随机得一个休眠时间往队列添加数字 class ProduceThread(Thread): def run(self): name = current_thread().getName() # 获取到了线程得名字 ...
787ab85de849ddb79d1c471a1706677d9b4b74b9
HuanbinWu/testgit
/pythonjike/function/fuct_test.py
1,952
4.125
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author:HuanBing #函数基本操作 # print('abc',end='\n\n') # print('abc') # def func(a,b,c): # print('a=%s'%a) # print('b=%s' %b) # print('c=%s' %c) # func(1.c=3) #取得参数个数 # def howlong(first,*other): # print(1+len(other)) # howlong(123,234,456) #函数作用域 # var1=...
3043c3d3c3d3e02e2d2afab8c8e03a9fe924bcc7
yaelRashlin/hackerrank-python-sulotions
/superDigit.py
1,018
3.796875
4
''' https://www.hackerrank.com/challenges/recursive-digit-sum/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=recursion-backtracking ''' #!/bin/python3 import math import os import random import re import sys # # Complete the 'superDigit' function below. # # The function is e...
9ce2ddb9b87e7ec92f6df0a4d23023faf6335f41
JunNishimura/Competitive-Programming
/AizuOnline/python/PCK/Prelim/2016/0338.py
179
3.53125
4
def GCD(a, b): # a > b if a % b == 0: return b else: return GCD(b, a%b) w, h, c = map(int, input().split()) if w > h: g = GCD(w, h) else: g = GCD(h, w) print(h*w*c//g**2)
a09f3ab56f175cb0286000a3251ebf8feee07f68
murphyk2021/Election_Analysis
/Python_practice.py
2,712
4.5
4
print("Hello World") counties=["Arapahoe","Denver","Jefferson"] if counties[1]=='Denver': print(counties[1]) counties=["Arapahoe","Denver","Jefferson"] if "El Paso" in counties: print("El Paso is in the list of counties") else: print("El Paso is not in the list of counties") if "Arapahoe" in counties ...
e2b32ddb24dd9cca0c6551540165f2a31ee5edb4
loschtreality/Tic_Tac_Toe_Python
/src/game.py
1,528
3.953125
4
from board import Board from player import Player class Game(object): """ Game class responsible for initializing the game. Requires an array of two players and a board """ def __init__(self): self.players = [ Player(name="p1", marker="x"), Player(name="p2", marker...
4d81bed7beb807e174a915df31db7724c33d4cc6
lanveka/Python
/1.py
492
3.953125
4
def rec(a, b): if a > b: print('Квадрат ',b,' на ', b) return rec(a-b,b) + rec(a,a) elif a <b: print('Квадрат ',a,' на ', a) return rec(b-a,a) + rec(b,b) else: return 1 count = 0 a = int(input('Введите сторону прямоугольника А : ')) b = int(input('Введи...
c39c178806f755fd52321e9dc1383adf496e6074
pvillano/projecteuler
/346.py
654
3.703125
4
import math # 2^40 -1 is max # max base is 10^12 - 1 # aince a representation always exists in base n-1, we just have to check if a representation exists in base sqrt(i) or lower def isStrong(n): "this function does shit" maxbase = int(math.floor(n ** .5)) for i in range(2, maxbase, 1): if isbase(...
12e9c43a4eed190d2b3e29dcd089bd6585e3ba18
pvillano/projecteuler
/41.py
361
3.546875
4
from itertools import permutations from sympy import isprime for i in range(10): print(i, sum(range(i+1))%3) # must be 4 or 7 for digits in permutations(list(range(7,0,-1))): if digits[-1] % 2 == 0: continue num = 0 for digit in digits: num *= 10 num += digit if ispri...
e78d38c9bf07e3b03daa0b15d8afe7a071774fcb
pvillano/projecteuler
/7.py
221
3.515625
4
from numpyutils import primes from math import log def nthPrime(n): maxPrime = int(max(13, n * log(n * log(n)))) #upper bound on nth Prime return primes(maxPrime)[n - 1] print(nthPrime(10)) print(nthPrime(10001))
499f5f5f61fae2a212ad08cc2eb654ce3e77e5e6
howarder3/leetcode_practice
/new_practice_python/101.symmetric-tree.py
2,438
4.09375
4
# # @lc app=leetcode id=101 lang=python3 # # [101] Symmetric Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # def isSymmetric(self, root: TreeNode) -...
ebd16107a67db40355c1c288c40ed6c7a1f153ec
howarder3/leetcode_practice
/new_practice_python/116.populating-next-right-pointers-in-each-node.py
989
3.734375
4
# # @lc app=leetcode id=116 lang=python3 # # [116] Populating Next Right Pointers in Each Node # # @lc code=start """ # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.r...
d0031e90a7e004187f0279fa09f66f6b6ac0174a
howarder3/leetcode_practice
/new_practice_python/106.construct-binary-tree-from-inorder-and-postorder-traversal.py
2,047
3.921875
4
# # @lc app=leetcode id=106 lang=python3 # # [106] Construct Binary Tree from Inorder and Postorder Traversal # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = righ...
bf755e3de5c98d5851a923183e8fd693abdcafb9
howarder3/leetcode_practice
/new_practice_python/110.balanced-binary-tree.py
1,790
3.859375
4
# # @lc app=leetcode id=110 lang=python3 # # [110] Balanced Binary Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # def isBalanced...
5529594abc8608472f17595afe8372451293e4aa
tectronics/pymd2mc
/pymd2mc/xyz2hexnet/lattices.py
3,125
3.734375
4
""" This classes contain lattices for atoms """ __author__ = 'Mateusz Lis' __version__= '0.1' from math import sin, cos, pi class Position(object): """Class holds coordinates of position""" def __init__(self, x0 = [0.,0.]): self._x0 = x0 @property def x0(self): """list of coordinate...
904d7bf1450e3838387f787eb0411593c739d5f0
kunal5042/Python-for-Everybody
/Course 2: Python Data Structures/Week 3 (Files)/Assignment_7.2.py
1,119
4.125
4
""" 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: X-DSPAM-Confidence: 0.8475 Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below....
b3be5eaf872a254f8cec7c7eb33740c9c4f30303
kunal5042/Python-for-Everybody
/Course 1: Programming for Everbody (Getting Started with Python)/Week 6 (Functions)/Factorial.py
603
4.28125
4
# Here I am using recursion to solve this problem, don't worry about it if it's your first time at recursion. def Factorial(variable): if variable == 0: return 1 return (variable * Factorial(variable-1)) variable = input("Enter a number to calculate it's factorial.\n") try: x = int(variabl...
07f9f576b76b56b5f258d563de4b24cf8f5f2673
kunal5042/Python-for-Everybody
/Course 2: Python Data Structures/Week 5 (Dictionaries)/Dictionaries.py
1,291
4.3125
4
""" Dictionaries: Dic are python's most powerful data collection. Dic allow us to do fast database-like operations in python. Dic have different names in different languages. For example: Associative Arrays - Perl / PHP Properties or Map or HashMap - Java Property Bag - C# /.Net """ def dictionaryDemo(): #Initi...
e52b318f5ef1e29c6f6ff08ef2fb68336c62ab4b
kunal5042/Python-for-Everybody
/Course 1: Programming for Everbody (Getting Started with Python)/Week 5 (Comparison Operators, Exception Handling basics) /Assignment_3.1.py
1,066
4.28125
4
""" 3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use ...
c2138c13915b9f7cde94d6989b462023e1b1becc
kunal5042/Python-for-Everybody
/Assignments-Only/Assignment_7.1.py
1,002
4.46875
4
""" 7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below. You can download the sample data at http://www.py4e.com/code3/words.txt """ import urllib.request, urllib.parse, u...
681e8e75e103cfb2227a50813a6a8789320a277a
kunal5042/Python-for-Everybody
/Course 1: Programming for Everbody (Getting Started with Python)/Week 4 (Syntax, Reserved Words, Type Conversions, Variables) /AssignOperator.py
597
4.46875
4
print("Assignment operator example:") #Example: print("Hi!") myName= "Kunal" print("\nMy name is " + myName) myLastName = "Wadhwa" print("My last name is " + myLastName) myFullName = myName + " " + myLastName print("\nMy full name is " + myFullName) age= 19 age= age + 1 print(("I am ") + str(age) + (" years old."...
4c950e5f677cd9ecd10a54fd798ece237278ffc9
shivangi090/iNeuron
/Assignment1/Task-2/3-Solution.py
105
3.5625
4
#!/usr/bin/env python # coding: utf-8 # In[7]: #Question-3 s=input("enter a string-") print(s[::-1])
76952f55a304b30b4726ecbba9c1f10e905eca97
shivangi090/iNeuron
/Assignment1/Task-1/2-Solution.py
145
3.640625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: #Question-2 for i in range(2000,3201): if i%7==0 and i%5!=0: print(i, end=", ")
799a83da4b6bd0ee34f4a2522d5339ff40d87b20
deividVentas/ejercicios_python
/python/7-6-salidas.py
404
4
4
ingredientes = [] while(ingredientes != "quit"): ingredientes = input("Introduzca el ingrediente que desee \n si ya has terminado de elegir ponga quit, \n") print("Has elegido ", ingredientes) if (ingredientes == "mozarella"): print("Que rico está la mozarella") elif (ingredientes == "peperoni"): print("...
435afbc3be1bd9b407fdc1e839b8130dffdd94ef
deividVentas/ejercicios_python
/python/4-1-pizzas.py
208
3.65625
4
# -*- coding: utf-8 -*- pizzas = ["Margarita", "carne picada", "carbonara"] for trozos in pizzas: print("Me gusta muchisimo la pizza llamada " + trozos.title()) print("Realmente me gusta la pizza")
8856fdbc8ce8776d39e1854e4d513c8939cabb7f
deividVentas/ejercicios_python
/python/7-montain_poll.py
543
3.71875
4
respuestas = {} polling_active = True while polling_active: name = input("\n Cual es tu nombre? ") respuesta = input("Que montaña te gustaria escalar algun dia? ") respuestas[name] = respuesta repite = input("Le gustaria que respondiese otra persona? ") if repite == 'no': polli...
f9fcf6bee878d0958997ffaaeab36180b876256a
ZJUguquan/Leetcode
/leetsov/longest_common_prefix.py
730
3.6875
4
# -*- coding: utf-8 -*- __author__ = 'STEVE' __tag__ = "LeetCode" __status__ == "Accepted" def longestCommonPrefix(strs): from collections import OrderedDict if len(strs) == 0 : return "" if len(strs) == 1: return strs[0] dd = sorted(strs, key= len, reverse = False) ...
066cf54cce89a19f452224e976c56c6d4229bd89
ZJUguquan/Leetcode
/leetsov/largest-rectangle-in-histogram.py
3,400
3.828125
4
'Largest Rectangle in Histogram' 'First try, get TLE.' # class Solution: # # @param height, a list of integer # # @return an integer # def largestRectangleArea(self, height): # mx, i = 0, 0 # j = len(height) - 1 # if j < 0 : return 0 # while(i<j): # mx = max(mx...
d12b07bf94ee7d4f01df5148ef00b5c81a596da8
ZJUguquan/Leetcode
/leetsov/subset.py
786
3.75
4
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- # __author__ = 'STEVE' # __tag__ = "LeetCode" # __status__ == "Accepted" s = [1,2,3,4] result = [] for m in s: q = s q.remove(m) result.append(q) print result '能实现 效率可能有点低' def subset(S): A = [[]] S.sort() for n in S: for i in range(len(A)): ss = A[i][:]...
7c807e37ed962964af855e88a9760a3ffdd84001
ZJUguquan/Leetcode
/leetsov/interleaving-string.py
1,883
4.0625
4
# Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. # For example, # Given: # s1 = "aabcc", # s2 = "dbbca", # When s3 = "aadbbcbcac", return true. # aa(s1) db(s2) # When s3 = "aadbbbaccc", return false. """ Here is some explanation: DP table represents if s3 is interleaving at (i+j)...
4e21b837a632f913fa6b1a72dad05849c8d1a5d0
ZJUguquan/Leetcode
/leetsov/Longest-substring-without-repeating-characters.py
613
3.671875
4
'Longest-substring-without-repeating-characters' def lengthOfLongestSubstring(s): if len(s)<=1: return len(s) maxlen = 0 templen = 0 charused = {} start = 0 for i in range(len(s)): if s[i] not in charused or charused[s[i]] < start: charused[s[i]] = i templen += 1 maxlen = max(maxlen, templen) elif...
55bfbce7fe536fdce7fef0699a340d6777f30d3d
ZJUguquan/Leetcode
/leetsov/PermutationNK.py
1,210
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Stevey" __project__ = "" """ The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "321" Given n and k, return...
0cf95940cbb2ddda696ec4d65de7bd8eaa422811
ZJUguquan/Leetcode
/leetsov/about_sort.py
811
3.53125
4
# -*- coding: utf-8 -*- import sys from collections import OrderedDict from operator import itemgetter default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) m = ["abc", "cba", "cad", "zzz"] #sorted(m, key=m[0]) print m "Sort a di...
6942f0f216319a5f6d622484213f8a2ce86f1179
ElizabethZapata/Mision_02
/clase.py
563
3.9375
4
# Autor: Elizabeth Citlalli Zapata Cortes, A01746002 # Descripcion: Calcular el porcentaje de mujeres y hombres inscritos en una clase. # Escribe tu programa después de esta línea. #Entradas mujeres = int(input("Mujeres inscritas: ")) hombres = int(input("Hombres inscritos: ")) #Calculo total = mujeres + hombres por...
cfebc88246f89c00c5490038df14769fd52f59be
vmizener/euler
/src/problems/p0523/main.py
535
3.671875
4
def swap_sort(lst): steps = 0 i = 0 while i < len(lst)-1: if lst[i] > lst[i+1]: print(lst, (lst[i], lst[i+1]), swap_count(lst)) lst = [lst[i+1]] + lst[:i+1] + lst[i+2:] i = 0 steps += 1 else: i += 1 return steps, lst ...
5016eb63e4f618f3dacb446566e6208cd74abaa7
younggeun0/SSangYoung
/dev/python_workspace/python_prj/date0510/use_exceptio.py
580
3.578125
4
# -*- coding:UTF-8 -*- group1List = ['김정윤','이재찬','박은영','백인재','이봉현','정택성'] num = 5 try: print("1조의 희망 {name}은 오후에 조퇴각".format(name=group1List[num])) num1 = num/2 print(num1) except IndexError as ie: print('잘못된 인덱스 번호 : ',ie) except ZeroDivisionError as zde: print('0으로 나눌 수 없습니다 : ',zde) except: ...
7322656d5ba9f88ef783622622bb13045d8e02db
younggeun0/SSangYoung
/dev/python_workspace/python_prj/date0508/use_while.py
205
3.5625
4
#--*-- coding:UTF-8 --*-- i=0 while i < 10: print(i) # i+=1 i =i+1 print('-'*50) # 분기문 : break i=0 while i< 10: if i==5: break print(i) i+=1
3cb4c020daeab3659eef66fa7da076807db2c72e
tkelestemur/learn-linalg
/linalg/lstsq/lstsq.py
723
3.53125
4
"""A least-squares solver for systems of linear equations. """ from linalg.qrdecomp import QR from linalg.ludecomp import LU def lstsq(A, b): """Finds the least-squares solution to a linear system Ax = b for an over-determined A. Solves the linear system of equations Ax = b by computing a vector x that minimi...
3820e7373bc32531be8713da83fd7a55840bcfc7
tkelestemur/learn-linalg
/linalg/kahan/sum.py
2,436
3.640625
4
import numpy as np class KahanSum: """Precise summation of finite-precision floating point numbers [1]. Reduces numerical error by storing a running compensation term that captures lost low-order bits. References: [1]: https://en.wikipedia.org/wiki/Kahan_summation_algorithm """ def __init__(self): ...
5cb2a0edae2f227f37ba504dc2ea4b305639c630
AlbertoCastro22/Programa-final-disor-2019-veran
/final/Padovan.py
2,745
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 31 22:55:48 2019 @author: luisalbertocastroquevedo """ import unittest class Padovan: def Algoritmo(numero): if numero==0 or numero==1 or numero==2: variableAuxiliar=1 return variableAuxiliar else: ...
31d6b6d534bb89fb655c3fdb3ff9c1850183760c
izzatii/learning
/Python/Intermediate-deque.py
368
3.65625
4
#8 collections deque import collections from collections import deque ''' d = deque("hello") d.append('4') d.append(5) d.appendleft(5) d.pop() d.popleft() d.clear() d.extend('456') d.extend('hello') d.extend([1,2,3]) d.extendleft('hey') d.rotate(1) print(d) ''' d = deque("hello", maxlen=5) prin...
97e1c7c3c00067602ca94705bb73f097d464a735
ShrutiBhawsar/problem-solving-py
/Problem4.py
1,547
4.5
4
#Write a program that asks the user how many days are in a particular month, and what day of the # week the month begins on (0 for Monday, 1 for Tuesday, etc), and then prints a calendar for that # month. For example, here is the output for a 30-day month that begins on day 4 (Thursday): # S M T W T F S # 1 2 3 # 4 5 6...
4f03b84942530c09ff2932e497683e5f75ccbf9c
ShrutiBhawsar/problem-solving-py
/Problem2_USerInput.py
1,237
4.3125
4
#2. Print the given number in words.(eg.1234 => one two three four). def NumberToWords(digit): # dig = int(digit) """ It contains logic to convert the digit to word it will return the word corresponding to the given digit :param digit: It should be integer :return: returns the string back ...
94eb1b16576d0f32178e606b0ce70e5726982366
strugee/pumptweet
/pumptweet/shorturl.py
1,165
3.734375
4
#!/usr/bin/env python2 # # shorturl.py # Shorts a long URL from command line, using ur1.ca. # Shows original page's title and short url. # # ksaver, (at identi.ca); Sep, 2010. # version 0.2, Mar 2011. # Requires BeautifulSoup library in order to work properly: # http://www.crummy.com/software/BeautifulSou...
a3f008c1941bb1c5315fc9636cd20cb3c09c20d3
darshan-gandhi/Hackkerank
/majic square.py
962
3.65625
4
mat=[] for i in range(3): row=input().split() mat.append(row) sumc=0 sumr=0 sumd=0 print(mat) sc=[] sr=[] sd=[] for i in range(len(mat)): sumr=0 for j in range(len(mat)): sumr=sumr+int(mat[i][j]) # print(f"the sum is {sumr}") sr.append(sumr) print(sr) for j in range(len(mat)): ...
5ccb0dabbd851fabc9f044d738179fa0a021949a
konsatanasoff/python-oop-2021
/testing/exercises/hero/test/test_hero.py
2,690
3.59375
4
from unittest import TestCase, main from project.hero import Hero class TestHero(TestCase): def setUp(self): self.main_hero = Hero("Main Hero", 5, 100, 10) self.other_hero = Hero("Other Hero", 10, 90, 30) def test_check_attr_are_set(self): self.assertEqual("Main Hero", self.main_hero...
cc09e0620fa13dbb666790a417a5a981e25b7cd2
meenal5gupta/Emailer
/Emailer/emailer.py
1,917
3.5
4
import requests import smtplib def get_emails(): emails={} try: email_file= open('emails.txt','r') for line in email_file: (email, name) = line.split(',') emails[email] = name.strip() except FileNotFoundError as err: print(err) return emails def get_schedule(): try: schedule_file = open('schedul...
720aa2c1ce7ec5b940ecafdd52445ae97e069e95
Manojkumarchow/ML-Classifiers-practice-
/AdaBoost.py
1,313
3.625
4
# Note: This is just a basic AdaBoost Classifier done for my practice. # Let's import the dependencies # Dependencies: # sklearn # required datasets from sklearn package print("<-----------AdaBoost Classifier----------->") from sklearn.model_selection import train_test_split from sklearn.ensemble import AdaBoo...
98853c76f5ef5e854a6bd8c321401b48bde3aa7a
aunoyp/Mapping
/mapping/population.py
5,105
3.53125
4
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pickle class Population(object): ''' Population object: PURPOSE: To prepare for population-level analyses by running through all neurons, fitting gaussian functions, and save these coefficients...
6ab629eecc5d43f7b32bad8f3f7e0abe272160b7
RealistikDash/pythoncalc
/Calc.py
3,302
3.59375
4
#Calculator by RealistikDash and historis #Written in Python 3.6.7 #For more help contact us on github https://github.com/RealistikDash/pythoncalc #Feel free to fork import math class Expression(object): def eval(self): raise NotImplementedError("Please implement this method") def printme(self): ...
5e8af218fd919e4f163c1a071c12e7540662c25e
portelaoliveira/matplotlib_e_pygal
/scatter.squares2.py
943
3.875
4
import matplotlib.pyplot as plt # Pontos individuais com scatter(). # plt.scatter(2, 4, s = 200) # O argumento S define o tamanho dos pontos usados para fazer o gráfico x_values = list(range(1, 1001)) y_values = [x**2 for x in x_values] ''' Quando essas listas são passadas para scatter(), o matplotlib lê um valor de ...
fa7d4b6d5e82dc2c32d8923f3a0266ca05d7aa98
yunzc/pykitti
/pykitti/datetime.py
1,918
3.5
4
"""Datetime class for timestamps""" __author__ = "Yun Chang" __email__ = "yunchang@mit.edu" SEC2NSEC = 1e9 MIN2SEC = 60 HR2MIN = 60 DAY2HR = 24 class Datetime: def __init__(self, string): self.year = 0 self.month = 0 self.day = 0 self.hr = 0 self.min = 0 self.sec = 0 self.nanosecs = 0 # initiate...
7e3ad5beaf7abcece044ca1b19579c9fd48b66a4
Foxijqy/Manipulator
/arms/scripts/kinematics.py
881
3.90625
4
#!/usr/bin/env python # Kinematics used for Manipulators. # Qingyuan Jiang. 2018 Aug. # Quaternion to Rotation Matrix # Rotation Matrix to Quaternion. # Quaternion to Rotation Matrix from scipy.linalg import norm import numpy as np def Quaternion2Rotation(q): q = q/norm(q) qw = q[3] qx = q[0] qy = q[1] qz ...
5d75490ce7da2f9ceb17fc9e5552feaf3798402b
prachi39/acad
/gui-2.py
511
3.515625
4
#1 from tkinter import * root=Tk() scrollbar = Scrollbar(root) scrollbar.pack(side=RIGHT,fill=Y) DICT={'asa':123,'dff':345,'bbn':432,'dfd':787,'zxc':989,'yoy':678,'tyu':564,'pyp':434,'bbn':343,'hgh':544} mylist=Listbox(root,yscrollcommand=scrollbar.set) for i in DICT: mylist.insert(END,i,DICT[i]) mylist.pack(side=...
df66ac8b769df7831cce916f1f3a18755ea0a7cd
prachi39/acad
/class assn.py
1,937
3.796875
4
#1 class Circle(): def __init__(self,radius): self.radius=radius def getArea(self): print(3.14*self.radius*self.radius) def getCircumference(self): print(self.radius*2*3.14) c=Circle(radius=4) c.getArea() c.getCircumference() #2 class Student(): def __init__(self,name,rollno): ...
d15e7849bf66c7d4d774f075b9f71aab7a918ccb
heweller/IST256FinalProject
/FP_PART1_FINAL.py
1,073
3.796875
4
#!/usr/bin/env python # coding: utf-8 # In[28]: #Importing the data # In[30]: import pandas as pd import numpy as np import csv import warnings warnings.filterwarnings('ignore') searchResults = pd.read_csv('FP_SearchResults.csv') # In[31]: #Creating a function to select the titles of policy documentation ...
b1984e62804fdc11e7330594cc45b067e795e90c
Dadda97/vale2.0
/client.py
579
3.578125
4
#!/usr/bin/env python3 import socket import sys if len(sys.argv) > 1: HOST = 'gentle-dawn-03506.herokuapp.com' # The server's hostname or IP address PORT = int(sys.argv[1]) # The port used by the server else: HOST = '127.0.0.1' # The server's hostname or IP address PORT = 12344 ...
72769d1234f1a596b8cb35710c1a10861764eef5
wmm0165/crazy_python
/03/3.3/index_test.py
417
3.84375
4
# -*- coding: utf-8 -*- # @Time : 2019/12/23 10:29 # @Author : wangmengmeng """index()用于判断某个元素在列表中的出现位置""" a_list = [2, 30, 'a', 'b', 'crazyit', 30] print(a_list.index(30)) # 定位30元素出现的位置 print(a_list.index(30, 2)) # 从2开始,定位30出现的位置 print(a_list.index(30, 2, 4)) # 在索引2和4之间定位30出现的位置,找不到该元素 ValueError
690c8698631850652e7d8527f70275c3e019ce9f
wmm0165/crazy_python
/06/6.5/invoke_override.py
446
3.796875
4
# -*- coding: utf-8 -*- # @Time : 2019/8/19 19:30 # @Author : wangmengmeng class BaseClass: def foo(self): print("父类中定义的foo方法") class SubClass(BaseClass): def foo(self): print("子类复写父类中的foo方法") def bar(self): print("执行bar方法") self.foo() BaseClass.foo(self) # 使用类名调用...
0edc58fbf257055980a8afbc37b213fd0c436e90
wmm0165/crazy_python
/06/6.3/property_test3.py
776
3.53125
4
# -*- coding: utf-8 -*- # @Time : 2019/8/19 14:14 # @Author : wangmengmeng # 使用@property修饰方法,使之成为属性 class Cell: # 使用@property修饰方法,相当于为该属性设置getter方法 @property def state(self): return self._state # 为state属性设置setter方法 @state.setter def state(self, value): if 'alive' in value.lower()...
6fa3ba5bc455c3923aa0fb50f07d3ec4ea0c8ca2
wmm0165/crazy_python
/06/decorator_test.py
578
3.578125
4
# -*- coding: utf-8 -*- # @Time : 2019/6/23 16:43 # @Author : wangmengmeng def funA(fn): print('A') fn() return 'fkit' @funA def funB(): print('B') print(funB) # output: # A # B # fkit def foo(fn): def bar(*args): print("===1===", args) n = args[0] print("===2===", n ...
4fa81a7adab3e965a6ec5d89651973d269c1994a
KishoreMuthyala/Password-Saver
/home/passenc.py
1,036
3.734375
4
import random import string import ast def encode(password): """ Takes Password as input and returns a tuple of encrypted password and keys """ i = 0 d = {} pswdLen = 5 while i <= 255: letters = string.ascii_lowercase + string.digits code = ''.join(random.choice(letters...
a019f50e4109a48d7f89b7c6b10b26fd40303b9e
cmychina/Leetcode
/leetcode_树_二叉树的后续遍历.py
658
3.84375
4
""" left-right-root """ class Solution: #迭代 def postorderTraversal(root): res = [] cur = root stack = [] while cur or stack: while cur: res.append(cur.val) stack.append(cur) cur = cur.right tmp = stack.pop() ...
1c8e7bb61796b88580581078e145ba7820bef487
cmychina/Leetcode
/leetcode_链表_2.删除链表的倒数第N个节点.py
1,141
3.609375
4
""" 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5. 进阶: 你能尝试使用一趟扫描实现吗? 思路:快慢指针 """ from linklist import ListNode class Solution: def removeNthFromEnd(self, head, n): if not head or not head.next: return head fast,slow=head,head for ...
d95ac08163c80aa3643513ed448dac3a090506c6
cmychina/Leetcode
/leetcode_剑指offer_59.之字形打印二叉树.py
631
3.890625
4
class Solution: def Print(self, root): if not root: return [] stack=[root] res=[] flag=False while stack: cur_val=[] next_level=[] for node in stack: cur_val.append(node.val) if node.left: ...
70067769f5ac3006507dcba631d5a9cecad39840
cmychina/Leetcode
/leetcode_链表_10.分隔链表.py
973
3.671875
4
""" 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 你应当保留两个分区中每个节点的初始相对位置。 输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5 思路:双链表分别记录大于x和小于x的 """ from linklist import * class Solution: def partition(self, head: ListNode, x: int) -> ListNode: d1=ListNode(-1) d2=ListNode(-1) p1=d...
3fe21dcc8c113899b61a21b4f0d1a25b7c27ff88
cmychina/Leetcode
/leetcode_杂七杂八_阿里笔试三.py
1,021
3.640625
4
class Solution: def minPath(self,matrix): n=len(matrix) m=len(matrix[0]) self.fly = 5 self.min_path=float("inf") visited=set() def dfs(i,j,path): if i<0 or i>=n or j<0 or j>=n or matrix[i][j]=="#" or (i,j) in visited:#跨界和障碍 return ...
8f9402c8f37adeca331b6963b74ccd60c0c06338
cmychina/Leetcode
/leetcode_链表_1.两数相加.py
3,476
3.546875
4
""" 给出两个非空的链表用来表示两个非负的整数。 其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 """ from linklist import ListNode class Solution: def addTwoNum(self,l1,l2): ans=ListNode(-1) cur=an...
8ad34e5475fb9e77f75a512201194f6c9ebc4ed0
cmychina/Leetcode
/leetcode_链表_5.两两交换链表中的节点.py
1,003
3.75
4
""" 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 给定 1->2->3->4, 你应该返回 2->1->4->3. """ from linklist import ListNode,convert class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head cur=head.next head.next=self.swa...
852df72dc1f1d89714933450baa4665c02941667
cmychina/Leetcode
/leetcode_回溯_全排列II.py
691
3.6875
4
class Solution: """ 包含重复数字的,返回所有不重复的排列 """ def permuteUnique(self, nums): n = len(nums) res = [] visited = set() def dfs(tmp): if len(tmp) == n: res.append(tmp) return for i in range(len(nums)): if i ...
e12a6c58085c83a1eef96e72b1f58902989a329c
cmychina/Leetcode
/leetcode_回溯_单词搜索.py
2,681
3.609375
4
class Solution: def exist(self,board, word): m = len(board) n = len(board[0]) self.visited=set() self.path=[] def dfs(i, j, k): if not 0 <= i < m or not 0 <= j < n or board[i][j] != word[k] or (i, j) in self.visited: return False if ...
e28302e637fe6c223cf456d6e9fdbba18ebdef25
cmychina/Leetcode
/leetcode_树_二叉树展开为链表.py
841
3.875
4
class Solution: def flatten(self, root): """ Do not return anything, modify root in-place instead. """ if not root: return #打平左右子树 self.flatten(root.left) self.flatten(root.right) tmp = root.right root.right = root.left roo...
ecaffe6671a77c2cf9631c7ff11799c010c73b31
cmychina/Leetcode
/leetcode_链表_二叉树中的列表.py
1,452
3.734375
4
class Solution: """ 类似于A是B的子树 """ def isSubPath(self, head, root) -> bool: if not root: return False return self.helper(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right) def helper(self, head, root): if not head: retur...
674c86de585a132ebedcdb1d7a6fd5bbb15a24cf
cmychina/Leetcode
/leetcode_堆_第k个数.py
790
3.5
4
""" 有些数的素因子只有 3,5,7,请设计一个算法找出第 k 个数。注意,不是必须有这些素因子,而是必须不包含其他的素因子。 例如,前几个数按顺序应该是 1,3,5,7,9,15,21。 """ #同丑数 import heapq class Solution: """ 使用最小堆排序,时间复杂度O(nlogn),空间复杂度O(2n) """ def nthUglyNumber(self, k): heap = [1] visited = set([1]) heapq.heapify(heap) nth = 0 f...
29034507230b272f19ccf7c73151ea33a70bc54b
cmychina/Leetcode
/leetcode_回溯_N皇后.py
1,305
3.53125
4
""" 对于所有的主对角线有 行号 + 列号 = 常数,对于所有的次对角线有 行号 - 列号 = 常数. """ #O(N!) class Solution: def solveNQueens(self, n: int): res = [] if n == 0: return res nums = [i for i in range(n)] col = set() master = set() slave = set() stack = [] def backtrack( n...
15db21c7be745a70de7b17cdbe6046937a8a1320
cmychina/Leetcode
/leetcode_树_二叉树遍历汇总.py
3,982
3.65625
4
#1.二叉树前序遍历:root-left-right #迭代 def preorderTraversal(root): if not root: return [] stack = [root] res = [] while stack: cur = stack.pop() res.append(cur.val) if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) retu...
30e21224c3305d52f639e12404444f1a9ea730bf
cmychina/Leetcode
/leetcode_链表_14.环形链表.py
628
3.859375
4
""" 给定一个链表,判断链表中是否有环。为了表示给定链表中的环, 我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 输入:head = [3,2,0,-4], pos = 1 输出:true """ from linklist import * class Solution: def hasCycle(self, head: ListNode) -> bool: if not head: return False slow,fast=head,head.next while fas...
7ee141c5f85d42b9b3dc58eba232d4dbc3b846f0
cmychina/Leetcode
/leetcode_树_平衡二叉树.py
473
3.796875
4
""" 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 """ class solution: def isBalanced(self,root): self.res = True def helper(root): if not root: return 0 left = helper(root.left) right = helper(root.right) if abs(right - left) > 1: self...
8bf099d9c96dd7216dcfe51bbd3d6184ec375645
cmychina/Leetcode
/leetcode_树_树的子结构.py
483
3.53125
4
class Solution: def isSubStructure(self, A, B) -> bool: def isSameTree(t1,t2): if not t2: return True if not t1 or t1.val!=t2.val: return False return isSameTree(t1.left, t2.left) and isSameTree(t1.right, t2.right) if not A: ...
2b17b0cb56fc26ad7e944d5cb861955340e56d29
nicoluv/TareaP1
/tarea11/main.py
1,311
3.609375
4
class TablaAccDirecto: #Creando clase para construir tabla de acceso directo def __init__(self): self.tabla = [0] * 52 self.size = 0 def getIndex(self, caracter): #Complejidad #Tiempo:O(1) #Espacio:O(1) if caracter.islower(): return ord(caracter.low...
0de7ee92d3c1a41f146459c3f301708da8990288
peter-zsn/mytwotongbkt
/copy_bad.py
954
4.0625
4
#coding=utf-8 """ @varsion: ?? @author: 张帅男 ---- 不能使用可变参数作为参数的默认值 @file: copy_bad.py @time: 2018/1/25 10:04 """ # class BadBus: # def __init__(self, passengers=[]): # self.passengers = passengers # # def pick(self, name): # self.passengers.append(name) # # def drop(self, name): # se...
8be0cab4409a793423af2bb1eb1d6c788a372194
RafaelLua13/Jogo-da-velha-em-uma-linha-Python
/versaoOriginalNaoLambda.py
4,280
4.125
4
# Um jogo da velha criado para atender aos parâmetros Lambda, comentado com explicações do código e especificação dos setores 'l' usados no código de uma linha. # O arquivo "Jogo1Linha" apresenta este mesmo código convertido ao Lambda em apenas 1 linha # Nome do projeto: Jogo da velha - Versão original # Linguagem: P...