blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
e7a2aeeaece89d8091827c210ba333275b31c263
Xudoge/PythonStudy
/Python/BaseKnowledge/inherit/inherit.py
433
3.71875
4
class A: def __init__(self,value,name): self.value=value self.name=name print("这是一个父类方法") def hihi(): print(self.name) class B(A): def __init__(self,value,name): #A.__init__(self,value=1,name="a") super().__init__(value,name) print("这是一个子类类方法1"...
15a0cde2ab30d5ed1d4eaf04cac7af6d6f3faf31
bjmyers/prtp
/Combination.py
15,540
3.75
4
import numpy as np from prtp.Rays import Rays import astropy.units as u import prtp.transformationsf as trans class Combination: ''' Class Combination: A combination object is a group of several components that the user wants to group together When Rays are traced to a Combination Object, they...
692e4f7a9df5800599d2492b20a732b65e7e7c60
keerthz/luminardjango
/Luminarpython/collections/listdemo/prgmforsearching.py
232
3.84375
4
lst=[10,12,13,14,15] element=int(input("enter the element for search")) flg=0 for i in lst: if(i==element): flg=1 break else: flg=0 if(flg==1): print("element found") else: print("not found")
ff64e2214caf2f674365a5cacd003b9afe7b1d0d
keerthz/luminardjango
/Luminarpython/languagefundamentals/sumof6.py
87
4.0625
4
num=int(input("enter the num")) sum=0 for i in range(0,num+1): sum=sum+i print(sum)
6ed8de9512fcf7f26e356d1e8def736dfe7e5051
keerthz/luminardjango
/Luminarpython/languagefundamentals/secondlargest.py
353
4.1875
4
num1=int(input("enter num1")) num2=int(input("enter num2")) num3=int(input("enter num3")) if((num2>num1) & (num1>num3)): print("num1 is largest",num1) elif((num3>num2) & (num2>num1)): print("num2 is largest",num2) elif((num1>num3) & (num3>num2)): print("num3 is largest",num3) elif((num1==num2) & (num2==num3...
8c9824e79adaffc0d82b70faf2fbf5cd8b5fc11e
keerthz/luminardjango
/Luminarpython/collections/listdemo/pattern.py
170
3.65625
4
lst=[3,5,8]#output[13,11,8] #3+5+8=16 #16-3=13 #16-5=11 #16-8=8 output=[] total=sum(lst) for item in lst: num=total-item#16-3=13 output.append(num) print(output)
b83ddc757ec963dbe30a142285ed68655fbc93b5
keerthz/luminardjango
/Luminarpython/languagefundamentals/vowels.py
167
3.734375
4
string=input("enter a word") list=["a","e","i","o","u"] count=0 for i in list: if(i in string): count+=1 print(count,i) else: break
009248f4014b9f8ce04bf4701c45e2ec4ecd46c2
keerthz/luminardjango
/Luminarpython/oops/polymorphism/empl1.py
484
3.859375
4
class employee: def __init__(self,id,name,salary): self.id=id self.name=name self.salary=int(salary) #def printValues(self): # print(self.id) # print(self.name) # print(self.salary) obj=employee(1001,"ayay",25000) obj2=employee(1002,"arun",30000) obj3=employee(1003...
832f2cb1ee730068f1865f9c0655e38472a9fab0
keerthz/luminardjango
/Luminarpython/regularexpression/quantifiers.py
251
4
4
import re #pattern="a+" #pattern="a*" #pattern="a?" #pattern="a{2}" pattern="a{2,3}" matcher=re.finditer(pattern,"aabaaaabbaaaaaabaaabb") count=0 for match in matcher: print(match.start()) print(match.group()) count+=1 print("count",count)
d15700beffef5f6f30597d848d67c736c9673182
Yuji-Takai/switchIn
/website/switchinweb/modules/utility.py
708
4.03125
4
from datetime import datetime """ converts the string extracted from text to date :param date: string representing the date :returns: datetime for the string """ def convertDateFormat(date): if (len(date) == 8): month = date[0:2] day = date[3:5] year = date[6:len(date)] yea...
4f06365db3bb2fdfa5e6c62e722e03f1ca916a7b
twillis209/algorithmsAndDataStructures
/arraySearchAndSort/insertionSort/insertionSort.py
422
4.125
4
def insertionSort(lst): """ Executes insertion sort on input. Parameters ---------- lst : list List to sort. Returns ------- List. """ if not lst: return lst sortedLst = lst[:] i = 1 while i < len(sortedLst): j = i - 1 while j >= 0 and sortedLst[j] > sortedLst[j+1]: temp = sortedLst[...
18290f2b984ca71bdbc4c147ec052ba17e246ad0
twillis209/algorithmsAndDataStructures
/arraySearchAndSort/timsort/timsort.py
1,029
4.25
4
import pythonCode.algorithmsAndDataStructures.arraySearchAndSort.insertionSort as insertionSort def timsort(): pass def reverseDescendingRuns(lst): """ Reverses order of descending runs in list. Modifies list in place. Parameters --------- lst : list List to sort. Returns ------- List. """ runStack...
e47c62abda3b57756034c72860b47ebeef96f4dc
luoyun/LuoYunCloud
/lyweb/lib/SQLAlchemy-0.8.2/examples/association/__init__.py
922
3.515625
4
""" Examples illustrating the usage of the "association object" pattern, where an intermediary class mediates the relationship between two classes that are associated in a many-to-many pattern. This directory includes the following examples: * basic_association.py - illustrate a many-to-many relationship between an ...
227ffd15cf6fd13ac446c356d96c0761e1932f4d
ruteshr/python
/string_palindraome.py
243
4.15625
4
#String is Palindrome string=list(str(input("enter a String :"))) a="" for i in string: a=i+a if("".join(string)==a): print('{} is palindrome'.format("".join(string)) ) else: print('{} is not palindrome'.format("".join(string)) )
a7947ff5b7e90e1996753e5c05c0fbe3ff0f582d
ruteshr/python
/pattern_diamond.py
2,697
3.75
4
n=5 for i in range(n): for j in range(n-i-1): print(end=" ") for j in range(2*i+1): print("*",end="") print() for i in range(1,n):#for i in range(n)-->for 10 line for j in range(i): print(end=" ") for j in range(2*n-(2*i+1)): print("*",end="") print() ''' OUTPUT: * *** ***** ******...
df296049dd2cd2d136f15afdf3d8f1ebec49871d
wulianer/LeetCode_Solution
/062_Unique_Paths.py
902
4.25
4
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Ab...
4e88fc3f4a0a63fbc41f29b2dc27ae7690190719
wulianer/LeetCode_Solution
/025_Reverse_Nodes_in_k_Group.py
2,023
3.96875
4
""" Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in...
43e7ef8659037e36c7e61b0e3c5b3c6766e1bda4
wulianer/LeetCode_Solution
/128_Longest_Consecutive_Sequence.py
772
3.9375
4
""" Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. """ class Solution(object): def longes...
4b367305f53d32a184f9260916827e26a6896c42
wulianer/LeetCode_Solution
/041_First_Missing_Positive.py
1,112
3.796875
4
""" Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, --> lower: 2, upper: 2 and [3,4,-1,1] return 2. --> lower: 1, upper: 3 nums: 1 5 4 2 3 6 8 lower: 1 1 1 2 3 upper: 1 5 4 4 Your algorithm should run in O(n) time and uses constant space. """ class...
70f0a5a7ee0fd7b6d75193be8bde2978db720f7d
wulianer/LeetCode_Solution
/076_Minimum_Window_Substring.py
1,001
4.09375
4
""" Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC". Note: If there is no such window in S that covers all characters in T, return the empty string "". If there are multipl...
81437f168b3fa1c08f38fffa627e0567263482be
wulianer/LeetCode_Solution
/050_Pow(x, n).py
532
3.78125
4
""" Implement pow(x, n). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 """ class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 i...
d7eb6774c273c399562026528da66b35a05d89f7
wulianer/LeetCode_Solution
/078_Subsets.py
688
3.984375
4
""" Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. For example, If nums = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] """ class Solution(object): def subsets(self, n...
b6783ba65e1f3c7e793e8eb36ad695ba2007015b
vishwanathvishu95/Python-games
/madlibs.generator.py
613
3.953125
4
#prompts for a series of input programmer = input("Someones Name: ") company = input("A Company Name: ") language1 = input("A Programming Language: ") hr = input("Someone else's Name: ") language2 = input("Another Programming Language: ") #printing the story with the given inputs print("-----------------------...
3af7d990e3433ff03e3a62368f454d627efe4c35
Kezuo0605/Python
/Lesson1.py
4,667
4.34375
4
# 1.Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. number = 1205 word = "START" print(f'Планируем начать обучение {number} {word} course Python') number = int(input('Напишите, когда хотите начать курс в фор...
4e72c806834109e6ac6810e7b6706af02b5a6f22
tzmhuang/GaussianProcess
/GP_regression.py
2,140
3.609375
4
''' based on: Machine learning -- Introduction to Gaussian Processes, Nando de Freitas ''' import numpy as np import matplotlib.pyplot as plt np.random.seed(seed = 1010) n = 5 data_x = np.linspace(3,5,n).reshape(-1,1) def kernel(a,b): #define kernel sqr_dist = np.sum(a**2,1).reshape(-1,1)+ np.sum(b**2,1) - 2*n...
d8e7568483e6583d0157bced6a93fd3672d67c34
shadowstep666/phamminhhoang-fundamental-c4e25
/section1/intro.py
174
3.703125
4
from turtle import * shape("turtle") speed(0) for i in range(300): for j in range (4): forward(200) left(90) right(7) mainloop()
55cab638287d2ff91e594c7e2111123ed2b4c4ac
shadowstep666/phamminhhoang-fundamental-c4e25
/section3/homework_day3/turtle2.py
300
3.8125
4
from turtle import * colors = [ 'red','blue','brown','yellow','gray'] for index , colour in enumerate(colors): color(colour) begin_fill() for i in range(2): forward(50) left(90) forward(100) left(90) forward(50) end_fill() mainloop()
33eaa474c2cf5191c44e189987c0de0d1fef4bc1
shadowstep666/phamminhhoang-fundamental-c4e25
/section3/menu.py
679
3.78125
4
# item1= " bun dau mam tom" # item2="pho" # item3="banh my" # item4 = "lau" # items = [] # empty list # print(type(items)) # items = [ " bun dau"] # print(items) items = ["bun dau mam tom ", "pho","banh mi", "lau"] # print(items)# print la mot loai read nhung chi doc ket qua # items.append("banh ny") #...
c68bf1082ec0684aef2788848101c283c88cb508
shadowstep666/phamminhhoang-fundamental-c4e25
/section2/homeworkDay2/n_start.py
88
3.515625
4
xs = "* " n = int(input("nhap vao n :" )) for i in range(n): print(xs, end=" ")
4d09e92399cffd253ec767fa52db207f28521079
ChihaoFeng/Leetcode
/20. Valid Parentheses.py
541
3.796875
4
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] for p in s: if p == '(': stack.append(')') elif p == '[': stack.append(']') elif p == '{': stack.appe...
273c9140794b49bd00f600c924355d478b4580b3
ChihaoFeng/Leetcode
/74. Search a 2D Matrix.py
682
3.78125
4
class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or not matrix[0]: return False x, y = len(matrix), len(matrix[0]) i, j = 0, x * y - 1 while i...
62f5eec73b9300a69398ba171c6daa4444fbf416
ChihaoFeng/Leetcode
/52. N-Queens II.py
1,600
3.515625
4
def totalNQueens(self, n): """ :type n: int :rtype: int """ def dfs(row): if row == n: self.ret += 1 return for col in range(n): if cols[col] or d1[col - row + n - 1] or d2[row + col]: continue cols[col] = d1[col - row ...
520410658429bb33202f390ea275b2393e154f5e
ChihaoFeng/Leetcode
/9. Palindrome Number.py
755
3.90625
4
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0 or (x and not x % 10): return False y = 0 while x > y: y = y * 10 + x % 10 x //= 10 return x == y or x == y // 10 """ we first ne...
a0fc54a4a0ef4f59666707712ed0f16318e9f512
ChihaoFeng/Leetcode
/37. Sudoku Solver.py
1,824
3.703125
4
class Solution: def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ def pre_process(): for i in range(9): for j in range(9): if board[i][j] == '....
078fe3fd6e966d82b68b0be61dd2ad73223a0b7f
ChihaoFeng/Leetcode
/103. Binary Tree Zigzag Level Order Traversal.py
745
3.90625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: ...
1fb90380a3e2c19219922cb9d46e2cf8aa520344
ChihaoFeng/Leetcode
/69. Sqrt(x).py
403
3.609375
4
class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ i, j = 0, x while i <= j: m = (i + j) // 2 if m * m == x: return m elif m * m < x: i = m + 1 else: j =...
2c231997492be2f5c53c01e6e3469e7d735e0af3
JuliandroR/Atividades-IFMS
/python/bin4dec.py
243
3.65625
4
entrada = input("A sequência em binário, please") a = int(entrada[:7], 2) b = int(entrada[8:15], 2) c = int(entrada[16:23], 2) d = int(entrada[24:31], 2) print("A sequẽncia informada convertida é: {} . {} . {} . {}".format(a, b, c, d))
c9364b322396ef9d1c140ba5c8e6c184acf6a41c
chenchals/interview_prep
/amazon/copy_linked_list_with_random_pointer.py
882
3.703125
4
# Definition for singly-linked list with a random pointer. class RandomListNode(object): def __init__(self, x): self.label = x self.next = None self.random = None class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rtype: Rando...
db082c1d53e70879e26a3d2d1cc9d08f85e38d2c
chenchals/interview_prep
/algorithms/tree_traversal.py
1,857
3.625
4
import math class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None def PreOrderTraversal(root, cb): cb(root.value, end=' ') if root.left is not None: PreOrderTraversal(root.left, cb) if root.right is not None: PreOrderTraversal(root.right, cb) return cb def...
a2aba7dc8d55e05aa6b7ce31cbc456bed61e946b
chenchals/interview_prep
/amazon/intersection_of_linked_list.py
1,258
3.6875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if not headA or no...
33ce2afb61fca3b33bd2439f9b12d1d09f41436f
chenchals/interview_prep
/linked_list/merge_two_sorted_linked_list.py
1,303
3.96875
4
class Node(object): def __init__(self): self.__v = None self.next = None def next(self, Node): self.next = Node @property def v(self): return self.__v @v.setter def v(self, v): self.__v = v def build_linked_list_from_list(li): head = Node() hea...
6f6010cd508110c20469513733cac735f6313694
chenchals/interview_prep
/algorithms/dijkstra.py
462
3.8125
4
class Vertex(object): def __init__(self, x, distance): # 2-dim tuple (x, y) self.key = x # distance[(1,2)] = distance -> coord to cost dict self.distance = distance self.parent = None def Dijkstra(graph, start, end): # set of visited coord for i in range(len(graph)): for j in range(len(graph[0])): ...
f75ae19fcc5b53606004ffe42edd406d0264c7ae
Catherine1000/PythonExercises
/AverageGrades.py
560
4.0625
4
bio_score = float(input("Enter your biology score: ")) chem_score = float(input("Enter your chemistry score: ")) physics_score = float(input("Enter your physics score: ")) if bio_score < 40: print("Fail") elif chem_score < 40: print("Fail") elif physics_score < 40: print("Fail") else: score = (bio_sco...
fb10a2f3e98da33e6f5cbbe1f1d08f41dc452855
vincenttchang90/think-python
/chapter_1/chapter_1_exercises.py
1,190
4.375
4
#chapter 1 exercises #1-1 # In a print statement, what happens if you leave out one of the parentheses, or both? ## print 'hello') or print('hello' return errors # If you are trying to print a string, what happens if you leave out one of the quotation marks, or both? ## print('hello) or print(hello') return errors wh...
4919605e133d383f8a7c848efa3eaf1405a58a96
bharatanand/B.Tech-CSE-Y2
/applied-statistics/python-revisited/intermediate-concepts/list-comprehension/gen-n-even-nos.py
91
3.796875
4
n = int(input("Display even numbers below: ")) ls = [i for i in range(0, n, 2)] print(ls)
526886cff12e987b705d2443cd0bc1741a552f36
bharatanand/B.Tech-CSE-Y2
/applied-statistics/lab/experiment-3/version1.py
955
4.28125
4
# Code by Desh Iyer # TODO # [X] - Generate a random sample with mean = 5, std. dev. = 2. # [X] - Plot the distribution. # [X] - Give the summary statistics import numpy as np import matplotlib.pyplot as plt import random # Input number of samples numberSamples = int(input("Enter number of samples in the sample lis...
5ad337bd7a7d4d10ee0fec4a1e2e1f8806039911
sjrathod/learning-python
/crackingTheCodingInterview/arrayAndStrings/oneAway.py
844
3.65625
4
#!/usr/bin/python def oneAway(str1, str2): i = 0 j = 0 edited = False diff = len(str1) - len(str2) if diff < -1 or diff > 1: return False s1 = str1 if (len(str1) > len(str2)) else str2 s2 = str2 if (len(str1) > len(str2)) else str1 if diff == 0: while(i < len(s1) and j < len(s2))...
1f45cddab2c6b1ac0f4c7b4b24415815c8c24df1
sjrathod/learning-python
/crackingTheCodingInterview/linkedLists/partition.py
952
3.828125
4
#! /usr/bin/python from basicLinkedList import * import pdb def partition(current, k): beforeLL = LinkedList() afterLL = LinkedList() while current: if current.data < k : beforeLL.insertAtTail(current.data) else: afterLL.insertAtTail(current.data) current = current.nex...
fa57f7fed7a1b413b04d7f7e331794660b15a2bd
haema5/python_level_1
/hw01_easy.py
2,447
3.9375
4
__author__ = 'Пашков Игорь Владимирович' import random # Задача-1: Дано произвольное целое число (число заранее неизвестно). # Вывести поочередно цифры исходного числа (порядок вывода цифр неважен). # Подсказки: # * постарайтесь решить задачу с применением арифметики и цикла while; # * при желании решите задачу с при...
b8f822a44c8b35e6d1e40a6c04c3afdac0989219
LBHukan/Clima
/clima.py
1,176
3.671875
4
import requests import json name_city = str(input("Digite Sua Cidade: ")) name_state = str(input("Digite Seu Estado Abreviado: ")) def ID(cidade, estado): city = str(cidade) state = str(estado) requisicao = requests.get("https://api.hgbrasil.com/weather?key=40acff95&city_name="+ name_city +","+ name_state...
c5d76587c717609f3a2f3da3a9136f92b3fee367
bmgarness/school_projects
/lab2_bmg74.py
755
4.125
4
seconds = int(input('Enter number of seconds to convert: ')) output = '{} day(s), {} hour(s), {} minute(s), and {} second(s).' secs_in_min = 60 secs_in_hour = secs_in_min * 60 # 60 minutes per hour secs_in_day = secs_in_hour * 24 # 24 hours per day days = 0 hours = 0 minutes = 0 if seconds >= secs_in_day: days ...
285c7fe0c7af03f251dd0b45dfc1d2cb0d66fced
B7504C/ichw
/pyassign4/wcount.py
1,823
3.75
4
#!/usr/bin/env python3 """wcount.py: count words from an Internet file. __author__ = "Bai Yuchen" __pkuid__ = "1800011798" __email__ = "1800011798@pku.edu.cn" """ import sys from urllib.request import urlopen def wcount(lines, topn): """count words from lines of text string, then sort by their counts in ...
9e905216e5e04d4b1b21d0f30afa26115da84044
ayeshaghoshal/learn-python-the-hard-way
/ex29.py
1,607
4.03125
4
# -*- coding: utf-8 -*- print "EXERCISE 29 - What if" people = 200 cats = 45 dogs = 100 if people < cats: print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs: print "The w...
ec32d18f39290dc135c190a49764ae585be27ccd
ayeshaghoshal/learn-python-the-hard-way
/ex14.py
1,252
4.5
4
# -*- coding: utf-8 -*- print "EXERCISE 14 - Prompting and Passing" # Using the 'argv' and 'raw_input' commands together to ask the user something specific # 'sys' module to import the argument from from sys import argv # define the number of arguments that need to be defined on the command line script, ...
8c787b221b005f2f997f7d927a008d3ff9fa1514
ayeshaghoshal/learn-python-the-hard-way
/ex19.py
2,520
4.40625
4
# -*- coding: utf-8 -*- print "EXERCISE 19 - Functions and Variables" # defining the function that commands the following strings to be printed out # there are 2 parameters that have to be defined in brackets def cheese_and_crackers(cheese_count, boxes_of_crackers): # use of the parameters is the same method ...
a4757d33b940e4cfcb580a0d18cb9f7117384929
giuschil/Python-Essentials
/sorting algorithms/bubblesort.py
1,214
3.859375
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 29 11:36:50 2019 @author: giuse """ def swap(a,b): tmp = b b = a a = tmp return a,b def random_array(): import random n= int(input("How many numbers you want to generate? ")) m= int(input("Number Max for choice? ")) ...
77bac9d5c187722aba0582983c074af89176dbfa
giuschil/Python-Essentials
/Hello.py
251
3.9375
4
"Write the numbers from 1 to 10" lista = [] for i in range(0,11): lista.append(i) print("il numero è: ",i) print("La lista è: ",lista) print("/n") for i in lista: print("il numero nella lista è: ",lista[i])
c5ee299d12ea8ad5e50aec5dcc1fcde6a5b789cb
juletats/LabsNMPy
/lab3.2.py
5,264
3.875
4
def NullMatrix(n): """Создание нулевой матрицы""" nullM = [0] * (n); for i in range(n): nullM[i] = [0] * (n) return nullM def MultiplyMM(matrix1, matrix2): """Умножение матрицы на матрицу""" n = len(matrix1); result = NullMatrix(n); for i in range(n): for j in range(n...
cce19d5079460040e6174142d487e9fac7a22adf
jamesfeng1994/ORIE5270
/HW2/tree/tree_print.py
2,454
4.15625
4
class Tree(object): def __init__(self, root): self.root = root def get_depth(self, current, n): """ This function is to get the depth of the tree using recursion parameters: current: current tree node n: current level of the tree return: the dept...
6ecb1094565598ff59b837c26a0af6ff7d802067
EnriqueDev01/be_semana_01
/Reto_01.py
723
3.765625
4
''' BIENVENIDA Para este reto tendremos que hacer lo siguiente: 1) Ingresar un nombre y su edad. 2) Si es menor de edad que indique que dependiendo de la hora (si es mas de las 6pm) debe ir a dormir y si no hacer la tarea. 3) Si es mayor de edad que indique que no esta obligado a hacer nada. ''' import datetime as dt ...
5dd1ad88e8daabdd120c401431088fe8326d86ff
Vandeilsonln/Python_Automate_Boring_Stuff_Exercises
/Chapter-10_Debugging/personalnotes.py
3,054
3.671875
4
#! python3 import logging logging.basicConfig(filename=r'C:\delicious\logfile.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') # logging.disable(logging.CRITICAL) # Comment this out to disable logging messages to be diplayed # I'll be writing the author's suggestion and notes in this co...
dab565b2e260dadc9fb14543fee9df41c84c904a
Vandeilsonln/Python_Automate_Boring_Stuff_Exercises
/Chapter-9_Organizing-Files/renamepictures.py
1,491
3.8125
4
#! python3 # renamepictures.py - The code will go through a directory tree and will rename all the pictures # based on it's creation date. # For now the code will just identify '.jpg' files. Any other formats will remain unchanged, although # their filenames will be written in the 'rejected.txt' file. By doing this, y...
180595fd0f78376e8b9d3da6af980876a743fcda
Vandeilsonln/Python_Automate_Boring_Stuff_Exercises
/Chapter-9_Organizing-Files/selective_copy.py
1,268
4.125
4
#! python3 # selective_copy.py - Once given a folder path, the program will walk through the folder tree # and will copy a specific type of file (e.g. .txt or .pdf). They will be copied to a new folder. import os, shutil def copy_files(folderPath, destinyPath, extension): """ Copy files from 'folderPath' to ...
26d42973cb952c3c2af0cddba3d4772c34b2d788
Liam-Hearty/ICS3U-Unit2-03-Python
/circumference_finder.py
493
4.625
5
#!/usr/bin/env python3 # Created by: Liam Hearty # Created on: September 2019 # This program will calculate the circumference of a determined circle radius. import constants def main(): # this function will calculate the circumference # input radius = int(input("Enter the radius of circle (mm): ")) ...
8c22a3529adcc775f3178ebe0c2a500e2ba98d74
Snehitkale/pythonprogramminglab
/lab_function.py
658
4.09375
4
def armn(x): #define a function sum=0 #then assign variables for values t=x #using while loop assign a condition while(t>0): #using a variable d assign a condition of input num...
748da75ce2505e4ea7c3a099ce23016174eced4c
Ziqi-Li/Cracking-the-code-for-interview
/Ch4. Trees and Graphs /4.2.py
1,148
3.921875
4
''' Ziqi Li 8.2 Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the surrounding area until you hit a border of that color. ''' from collections import deque def BFS(g,start,...
df06470e115da8ebaa8e2e9435c68d4595dec9e4
Ziqi-Li/Cracking-the-code-for-interview
/Ch2. Linked List/2.3.py
902
4.0625
4
''' Ziqi Li 2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node. EXAMPLE Input: the node 'c' from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e ''' class node(object): def __init__(self,data,ne...
e579216c6a8e871f956dcfab2c3902e182a75017
Ziqi-Li/Cracking-the-code-for-interview
/Ch8. Recursion/8.2.py
1,230
4.09375
4
''' Ziqi Li 8.2 Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the surrounding area until you hit a border of that color. ''' def robotWalk(m, n): if m == 1 or n == 1: ...
28fb6e72d2529ad57810ed6545e84db41f4a4471
Ziqi-Li/Cracking-the-code-for-interview
/Ch1. Arrays and Strings/1.6.py
730
3.890625
4
''' Ziqi Li 1.6 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? ''' def rotate(img,n): for i in range (0,n): for j in range (i+1,n): img[i][j], img[j][i] = img[j][i], img[i][j] ...
b478e1623d95f0cc868f41ba52824423a8e2fc93
petef4/payg
/footnote.py
1,054
3.65625
4
from textwrap import fill def definitions(footnotes): """Convert JSON footnotes into a format suitable for Jinja2. In JSON a footnote is a list. The first element is the id. Other elements are either string or list, concatenated to make the text. A list is a grade (e.g. poor) followed by a string...
0d36514e5d069335e7e00b9f1ce6f88635624b65
eleven2021/xor
/xor.py
544
3.6875
4
def crypto_text_to_hex(src_text, key): xor_code = key while len(src_text) > len(xor_code): xor_code += key return "".join([chr(ord(data) ^ ord(code)) for (data, code) in zip(src_text, xor_code)]).encode().hex() def decrypto_hex_to_text(hex_text, key): crypt_data = bytes.from...
57d65fa197e6ad4672a2f5cc5cfc049c9de3af0b
ronyu21/data-analysis-app
/src/DataAnalysisApp.py
5,434
3.96875
4
from typing import List import matplotlib.pyplot as plt from src.FileHandling import load_csv_to_2d_list, save_data_to_csv if __name__ == "__main__": # load from csv file and save as a list data_list = load_csv_to_2d_list('./resource/Emissions.csv') # transform the list to become dictionary # with ...
eac543f52b8e273aaa54942592edc2e1d0680759
dudu9999/Tkinter_Projects_dudu9999
/03 - muda label Funcionou/main.py
366
3.671875
4
from tkinter import * def bt_click(): print("Botao clicado") lb['text'] = 'Funcionou' janela = Tk() janela.title("Janela Principal") janela["bg"] = "purple" lb = Label(janela, text="Texto Label") lb.place(x=120, y=100) bt = Button(janela, width=20, text='OK', command=bt_click ) bt.place(x=80, y=150) janel...
2b37622cd4de1d5beb32d3e3734ebd704f5582e2
bipins867/Python-Server-Clinet-Remote-Controlling
/Encode.py
1,412
3.53125
4
#Encoder from collections import OrderedDict from re import sub def encode(text): ''' Doctest: >>> encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW') '12W1B12W3B24W1B14W' ''' return sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), ...
32f56e3193bb85c6b23213a1e09332aef8f5ac17
bjrubinstein/PyHSPF
/examples/evapotranspiration/etexample01.py
9,200
3.65625
4
# etexample01.py # # David J. Lampert (djlampert@gmail.com) # # last updated: 03/15/2015 # # this example shows how to use the ETCalculator class to compute daily # reference evapotranspiration from the other time series after using the # ClimateProcessor class to extract and aggregate the climate data from the # Worl...
c9497ad2a313d2664ee99f371138776ab980f1f4
hugovk/wotdbot
/wotdbot.py
3,644
3.609375
4
#!/usr/bin/env python """ Pick a random [Finnish] word from a word list, open its Wiktionary page and tweet it """ import argparse import random import sys import webbrowser from urllib.parse import quote import yaml # pip install pyyaml from twitter import OAuth, Twitter # pip install twitter def load_yaml(filena...
cfbb448e37e667067f98ffcfbf1c7972b807f85e
xiawq1/leetcode-c-
/leetcode/stack.py
4,902
3.5625
4
#coding:gbk #ջźƥ䣬ųջжջǷΪգΪΪTrueΪFalse. class Solution: def isValid(self, s): stack = [] #ڴſ mapping = {')':'(', '}':'{', ']':'['} #ɢбƥ for char in s: if char in mapping: if len(stack) != 0: tmp = stack.pop() if mapping[char]...
8f8b1f239de525c01abfce4e556caed1f12a9300
JensMellberg/Neural-Networks-Exercise-2
/Exercise2.py
6,083
3.65625
4
# coding: utf-8 # # Tensorflow Tutorial (MNIST with one hidden layer) # ## Neural Networks (TU Graz 2018) # (Adapted from the documentation of tensorflow, find more at: www.tensorflow.org) # # # Improving the MNIST tutorial by adding one hidden layer # # <img src="hidden_layer.png" style="width: 200px;" /> # In[1]: ...
71fecce0bba7ea6072ac11c0c7e82466480c5015
EdgeLord836/229
/Labs_Mat_Vec_etc/Lab3_229.py
490
3.75
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 22 15:48:46 2017 @author: Sam """ print('P1') s = [1,2,3,4] def cubes(arg): return [x**3 for x in s if x % 2 == 0] print(cubes(s)) print('\nP2') dct = {0:'A', 1:'B', 2:'C'} keylist = [1,2,0] def dict2list(dct, keylist): return [dct[i] for i in keylist] print(dict2l...
d97f49825c56c71f1f6864c46840bbe7f71237f8
OldSchoolWeaver/WeatherGeneratorApp
/Run.py
2,725
3.609375
4
#!/usr/bin/env python3 # coding: utf-8 import pandas as pd import numpy as np import datetime import random import sys from Aux import * from WeatherSimulator import * from WeatherDataGenerator import * def RunSimulation(): """ This function will create an instance of a simulation and will save the outp...
1c64989c3d865d279c0d8bc7dbbba53dc4c4c247
loadlj/leetcode
/Range_sum_query.py
760
3.734375
4
# Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. class NumArray(object): def __init__(self, nums): self.nums = nums self.updatedlist = [] self.updateList() def updateList(self): if len(self.nums) >0: self.updat...
4b784585fefbe4087acbc9747f481fc650a21f84
D7DonKIM7E/Python
/BOJ_2588.py
119
3.6875
4
first = int(input()) second = input() for digit in second[::-1] : print(first*int(digit)) print(first*int(second))
a686a0f2ff0ea00d450015ed2f203ac144098c0d
luka3117/toy
/py/山内 テキスト text sample code/ohm/ch4/list4-2.py
1,149
3.515625
4
#-*- coding: utf-8 -*- # List 4-2 skew、kurtosisの例 from scipy.stats import skew, kurtosis, norm, uniform, kurtosistest import math import numpy as np import pandas as pd from matplotlib import pyplot as plt numsamples = 100000 v1 = norm.rvs(loc=0.0, scale=1.0, size=numsamples) print('正規分布N(0,1)', 'skew=', round(skew(v1...
5e260fa16cb00b8d231a1285fe00b907654183c2
luka3117/toy
/py/山内 テキスト text sample code/ohm/ch7/list7-7.py
2,833
3.53125
4
# -*- coding: utf-8 -*- # List 7-7 出生率と死亡率の関係 import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm np.set_printoptions(precision=4) x = np.loadtxt('shusseiritsu.csv', delimiter=",") # CSVファイルからデータを読込む # 出典 http://www.mhlw.go.jp/toukei/saikin/hw/jinkou/suikei15/dl/2015suikei.pdf birth1 = [u[...
afdc0cfdf6ac796e06cc2e1cd574cfb765b67eed
j2sdk408/misc
/mooc/algorithms_II/lsd_sort.py
2,265
3.625
4
""" implementation for least-signficant-digit-first string sort """ from str_custom import StringCustom class LsdSort(object): """class for LSD string sort""" def __init__(self, str_list): """initialization""" self.str_list = str_list self.sort() def __str__(self): """to...
20fadd9ad05d61ed6b884287fd0cebdd0ae916e6
j2sdk408/misc
/mooc/algorithms_II/st_tst.py
4,503
3.734375
4
""" implementation for string symbol table with ternary search try """ class Node(object): """class for tri node""" MIDDLE = 0 LEFT = 1 RIGHT = 2 def __init__(self): """initialization""" self.value = None self.char = None # 0: middle # 1: left # 2...
e671953c188a7d380130aa00f48a25ccbf099ad5
j2sdk408/misc
/mooc/algorithms_II/msd_sort.py
2,709
3.546875
4
""" implementation for least-signficant-digit-first string sort """ from str_custom import StringCustom class MsdSort(object): """class for MSD string sort""" def __init__(self, str_list): """initialization""" self.str_list = str_list self._aux_list = [None] * len(self.str_list) ...
8829a7674ab5b9cdd3b0e5e54f28611912b206d8
j2sdk408/misc
/mooc/algorithms_II/pathes.py
858
3.734375
4
""" implementation of graph algorithms """ class Pathes(object): """class for path searching""" def __init__(self): """initializer""" self.s = 0 @classmethod def from_graph(cls, G, s): """find pathes in G grom source s""" p = cls() p.s = s assert s <...
02307d05d584281dd61948087f1ed8fc6853dafd
chitritha/python-project
/finalProj_cnalluru_07.py
5,965
3.890625
4
""" Program: Commodity Data Filtering Final Author: Nalluru Chitritha Chowdary Description: This program is used to filter and represent data based on user inputs Revisions: 00 - Importing CSV, datetime and plotly modules 01 - Printing announcement 02 - Import data from CSV file and change into required format ...
94a97edaa66c9527fc133ec3c33386a5410968ba
biradarshiv/Python
/CorePython/24_String_Formatting.py
1,464
4.46875
4
""" The format() method allows you to format selected parts of a string. Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input? To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method: """ print("# Fi...
6ef55a33502d489e160f6b1109182584a17b792b
biradarshiv/Python
/CorePython/1Introduction_Comments.py
1,466
4.03125
4
""" Python is a programming language. Python Syntax compared to other programming languages Python was designed for readability, and has some similarities to the English language. Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. Python us...
a36c60c380517b1e6b6d146669e9b93cf797fbcd
biradarshiv/Python
/CorePython/13_ClassObject.py
2,393
4.25
4
""" Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. """ print("# Create a class and access a property in it") class MyClass: x = 5 print(MyClass) p1 = MyClass() p...
3edbceaa1a25e81edc5e284886f8a74ed0b875cc
szoto1/python101
/day03.py
3,946
3.625
4
# # # # # wiek = input("Ile masz lat?") # # # # # koty = input("Ile masz kotów?") # # # # # # # # # wiek = 2 # # # # # koty = 5 # # # # # # # # # zdanie = "Ala ma 2 lata i posiada 5 kotów." # # # # # zdanie = "Ala ma " + str(wiek) + " lata i posiada " + str(koty) + " kotów." # # # # # zdanie = f"Ala ma {wiek} lata i po...
50d9dd353abba8ec79d57f9603db650e5756fae9
sathishkumar-smart/Sathish-kumar
/grap.py
286
3.796875
4
import turtle colors = [ "red","purple","blue","green","orange","yellow","white","brown","violet"] my_pen = turtle.Pen() turtle.bgcolor("black") for i in range(360): my_pen.pencolor(colors[i % 9]) my_pen.width(i/50 + 1) my_pen.forward(i) my_pen.left(65)
3446b3c1b5cb77bc60d2c5709e91d8656c3447ea
Nicholas-Swift/Data-Structures
/set.py
5,193
3.859375
4
# A Hash Table from linkedlist import LinkedList class Set(object): def __init__(self, init_size=8): """Initialize this hash table with the given initial size""" # Best: Omega(1) # Worst: O(n) (init size) self.buckets = [LinkedList() for i in range(init_size)] self.entri...
4ff11193a8c26d84d00ba20d3fab03525b980fa9
Nicholas-Swift/Data-Structures
/test_deque.py
2,267
3.765625
4
#!python from deque import Deque import unittest class QueueTest(unittest.TestCase): def test_init(self): q = Deque() assert q.peekLeft() is None assert q.peekRight() is None assert q.length() == 0 assert q.is_empty() is True def test_init_with_list(self): q ...
0abe423a5725967d6b813d2c72571fb1d5b96773
Junrongh/15-619-CloudComputing
/Project1_1/q5.py
1,235
3.8125
4
#!/usr/bin/env python3 import pandas as pd import json from csv import QUOTE_NONE def main(): """ Please search and read the following docs to understand the starter code. pandas.read_table 1) With 'squeeze=True', pandas.read_table returns a Series instead of a DataFrame. 2) Wi...
5b23f87d82b4596860ca67e2d6232e4207f053a9
kanosaki/picbot
/picbot/utils/__init__.py
824
3.5
4
import itertools def uniq(*iters): """Make unique iterator with preserving orders. """ return UniqueIterator(itertools.chain(*iters)) class UniqueIterator(object): def __init__(self, source): self.source = source self._history = set() def __iter__(self): return self def ...
8f6472d4db42afc132521b63df85977a06582164
SociallyAwkwardTurtle/Python
/Vestluskaaslane.py
398
3.96875
4
print("Hello world!") print("I am Thonny!") print("What is your name?") myName = input() print("Hello, " + myName + ", it's nice to meet you!") print("How old are you?") input() print("Oh, that's nice!") from random import * a = (randint(2, 5)) if a == 2: a=("two") elif a == 3: a=("three") elif a == 4: a=("...
f0d4e56573bf9b971b561a94b472facc155ebb35
ajboxjr/CS-2-Tweet-Generator
/class7/data-structure/linkedlist.py
7,118
4.21875
4
class Node(object): def __init__(self, data): """Initialize the node with a data and a pointer(next)""" self.data = data self.next = None def __repr__(self): """Return a string representation of this node.""" return 'Node({!r})'.format(self.data) """ TO lower space time ...