blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b19cf4ec663f504f0d5b764986073ee4ed9dd09e
ao-spirogyra/Cipher
/TextPackage/texthundler.py
482
4.09375
4
# argument is text and list of alphabets # this returns a dictionary(key is alphabet, value is number of each alphabet in the text) # it can process various type of list(like A~Z&a~z,a~z&" "&!? or whatever) def count_alphabets(text,alphabets): # make dict recording appearance times for each alphabets dict_count...
5411703d93caaf9f293fc87c2b1069f79a1caf8b
Wessie/python-tmdb3
/tmdb/util.py
1,133
3.6875
4
class AttributeDict(dict): """ Simple dictionary subclass that supports attribute access to the dictionary alongside normal access. """ def __init__(self, dct): super(AttributeDict, self).__init__(dct) self.recursive_instantion() def __getattr__(self, key): try: ...
55c799533967401da8a032a2efd7b85b954fd299
Vatsalparsaniya/Data-Structure
/reverse-sentences/reverse.py
137
4.21875
4
input_str = input('Enter input string: ') input_str = ' '.join(input_str.split(' ')[::-1]) print ('Reverse of input string: ', input_str)
fa8ebb44da853dc52b8404d806686de78b9ce5bb
ugant2/python-snippate
/Assingment/task2.py
1,217
4.25
4
# Question​ ​ 2 1. Define a function that computes the length of a given list or string(Do not use # library​ ​ function​ ​ of​ ​ length). def count_length_list(): #function without any parameter c = 0 l = [3,4,5,6,7,78,2] for i in l: c = c + 1 return c print(count_length_list(), "\n") def...
8541fc73d53e92a0e939af99b9baaa38a6a80359
aaronz9/python_mini
/python/func.py
660
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 10 12:29:37 2018 @author: aaronfernandez """ chance = int(input("enter your chances")) def prime_or_not(): for attempt in range(chance): num = int(input('Enter your number')) if num > 1: for i in range(2,n...
98842d488f483ad1c99a135530c2a9ddc7d658aa
nithen-ac/Algorithm_Templates
/data_structure/array_examples.py
8,974
3.5
4
from functools import reduce from collections import Counter # [852] https://leetcode.com/problems/peak-index-in-a-mountain-array/ # Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. # # linear search def peakIndexInMountainArray1(A)...
f0a8c728772e910753cae71a072e986f8d58b849
vamvindev/DSA-Collab
/Python/Linked List/Merge Two Sorted Lists.py
991
4.15625
4
# Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. # Input: l1 = [1,2,4], l2 = [1,3,4] # Output: [1,1,2,3,4,4] # Example 2: # Input: l1 = [], l2 = [] # Output: [] # Example 3: # Input: l1 = [], l2 = [0] # Output: [0] class L...
72d5b332ffaac5e8a748df7114d085fd108d1c55
jumboframezz/fundamentals2021
/Exercises/15. Functions - Exercise/10. Array Manipulator.py
6,477
3.6875
4
# 10. *Array Manipulator # Trifon has finally become a junior developer and has received his first task. It's about manipulating an array of # integers. He is not quite happy about it, since he hates manipulating arrays. They are going to pay him a lot of # money, though, and he is willing to give somebody half of it i...
dc4f15338e3b5a02b7617045d13a8ec4a45aa612
hellorobo/PyCode
/hello_world.py
272
4
4
# a routine to greet a user ''' this is a block comment code author RJ ''' name = input('enter your name: ') if name is 'Robert': print('Hello {0}!'.format(name)) elif name is 'Anna': print('Hi {0}!!'.format(name)) else: print('How are you {0}?'.format(name))
2ecf58ff01de3efc7ce6664da083ee0a4425171e
alferesx/Python-Exercises
/EstruturaSequencial/Exercicio-9.py
149
4
4
farenheit = float(input('Digite o valor da temperatura: ')) celsius = (5*(farenheit -32)/9) print('O valor da temperatura em Celsius é: ',celsius)
08cc44a1169a0489cf8b188eb25d919fd2cfebb0
karanoberoi28/Python_Challenge
/level_4.py
745
3.625
4
import urllib from urllib import urlopen import re web = urllib.urlopen("http://www.pythonchallenge.com/pc/def/linkedlist.php").read().decode() comments = re.findall("<!--(.*?)-->",web,re.DOTALL) text = comments[-1] print(text) digit = [int(i) for i in text.split() if i.isdigit()] link = "http://www.pythonchallenge.c...
93abe5546305be25126129f08261675f8a5038bc
Terhands/AdventOfCode
/2018/6/solution.py
4,070
3.859375
4
class Coord(object): def __init__(self, x, y): self.x = int(x) self.y = int(y) self.is_finite = True def __str__(self): return "(%d, %d)" % (self.x, self.y) def __repr__(self): return self.__str__() def manhattan_distance(p1, p2): return abs(p1.x - p2.x) + a...
9ec6e8b961bbe2a9d608f94662a745f9471f95dc
redmage123/pythonfortooldevelopers
/examples/fibonacci1.py
517
3.578125
4
#!/usr/bin/python3 import timeit def fib(n): if n < 2: return n else: return fib(n-2) + fib(n-1) def main(): i = 5 t = timeit.Timer(setup = 'from __main__ import fib', stmt = 'fib(5)') print ('Value of n = %.d\nPure python %.2f usec/pass' % (i,t.timeit(number=100000))) outp...
c7cc17862a079718d21ec89a844843a61703739c
Ivan-Dimitrov-bg/Python_100_Days_UdemyCourse
/25.IntermediateWorkingwithCSV/225.ReadingCSVData.py
495
3.625
4
# # with open("weather_data.csv") as data_file: # data = data_file.readlines() # print(data) # import csv # # with open("weather_data.csv") as data_file: # data = csv.reader(data_file) # temperature = [] # for row in data: # if row[1] != "temp": # temperature.append(int(row[1]))...
57a4c5838a0e2435505956513769a528cba0bf76
Ninjavietus/csci102-wk12
/fib.py
189
3.78125
4
#John Robert #CSCI 102 - Section E #Workshop Week 2 num_1 = 0 num_2 = 1 print(num_2) for i in range(2, 100): num_3 = num_1 + num_2 num_1 = num_2 num_2 = num_3 print(num_3)
3750ff8cc4306d98c0886d20d2a840dfdec6eac4
kk77777/LeetCode-Solutions
/q543.py
557
3.640625
4
# 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 ht(self,root,dia:list)->int: if(root==None): return 0 lh=self.ht(root.left,d...
f14fca16ef182940c0fbecffb58a91e95e3787c1
melissa040601/PROGRAMACION-II-MELISSA-FLORES
/Directorio.py
579
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 1 11:24:59 2020 @author: Melissa A Flores Colunga """ nombre = input ("dame un nombre") edad = input ("ingresa edad") fecha = input ("ingresa fecha de nacimiento") ciudad = input ("ingresa ciudad") codigo = input ("ingresa codigo postal") calle = input ("ingre...
387df7b39f889f489fdcb6ea9d934ef450bc1b4a
wilfredarin/geeksforgeeks
/Graph/detect-cycle-in-a-directed-graph.py
635
3.953125
4
#https://practice.geeksforgeeks.org/problems/detect-cycle-in-a-directed-graph/1 def isCycle(v,graph,visited,stack): visited[v] = 1 stack[v] = 1 for nbr in graph[v]: if not visited[nbr]: if isCycle(nbr,graph,visited,stack): return True elif stack[nbr]: ...
9867009d1ac94b72ea202a0cd7fa6690a29c6645
quan7794/clean-code
/cleanCode.py
3,592
3.734375
4
#6__________Don't Pass Null.__________________________________________________________________________ class Cat: def __init__(self, name, color): self.name = name self.hairColor = color def main(): Sphynx = Cat("Sphynx", None) FelisCatus = Cat("Felis Catus", "Bicolor") print(childCa...
c0e714483ffac20c9bc44572b6f1311eaebb2346
Th3-C0d3-I3r34k3r/Python_Basics
/34pyexcephandling.py
1,625
4
4
#Python Try Except # try = this block lets you to test ablock of code for errors # except = this block lets you to handle errors # finally = this block lets you to ececute code,regardless of the result of the try=and except blocks print () print (" **************************************") print (" * Pyt...
9c3e0980988d059dac91c78cfc61749af0d7bbfe
KritikPant/Beginner-Projects
/Fibonacci.py
3,189
4.15625
4
#Fibonacci Calculator import sys import math def isPerfectSquare(x): s = int(math.sqrt(x)) return s*s == x def isFibonacci(n): return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4) def is_number(s): try: float(s) return True except ValueError: return False wh...
6bd2d6dfea153893f3539438a4bc962acc6e6432
juan-ivan-NV/Data_Engineering_Nanodegree
/16_Project_5_Capstone_Project/create_tables.py
1,962
3.515625
4
import configparser import psycopg2 from sql_queries import create_table_queries, drop_table_queries def drop_tables(cur, conn): """Drops database tables Args: cur (:obj:`psycopg2.extensions.cursor`) ► Cursor for connection con (:obj:`psycopg2.extensions.connection`) ► database connection...
4dcdd0382bf2d30c2ddf5073f649ee7d8b6e445a
Tanmay-Thanvi/DSA-and-Leetcode-Walkthroughs
/Recursion/merge list recursively.py
205
3.71875
4
def get_merge_list(alist): if len(alist) == 1: return alist[0] else: return alist[0] + get_merge_list(alist[1:]) print(get_merge_list([[1, 2, 3], [2, 3, 5, 6], [7, 8, 9]]))
807696a5678f7bafa92f52b50494c10497a2ee3c
e8johan/adventofcode2018
/1/1a.py
198
3.5
4
freq = 0 while True: try: delta = int(raw_input()) except ValueError: break except EOFError: break freq += delta print("Frequency: %s\n" % (freq))
0db279984dbce38a90794ac1adad7663ca105ab2
keiti93/Programming0
/week4/4-Count-Vowels-Consonants/count.py
504
4.09375
4
def count_vowels_consonants(word): count_vowels = 0 count_consonants = 0 vowels = "aeiouyAEIOUY" consonants = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ" for letter in word: if letter in vowels: count_vowels +=1 elif letter in consonants: count_consonants ...
5cf3640037b571a0c36a426cb7d10671c2fcaf17
Masheenist/Python
/lesson_code/ex43_Basic_Object-Oriented_Analysis_and_Design/central_corridor_scene.py
1,790
3.578125
4
class CentralCorrridor(Scene): def enter(self): print(dedent(""" An ominous force has inhabited your ship and there is no trace of your crew. You seem to be the last surviving member and in such situations you are have been instructed and trained to detonate the ship as your first priority, ...
bee43df285561eed659f82def5c92ba27ee4818c
brendonwanderlust/DigitalCraftsCoursework
/Week 2/Tuesday/FunctionsExercises.py
892
3.9375
4
#Functions Exercises # 1 '''Before''' ''' string = "My name is Brendon" reverseList = [] newString = '' for x in range(len(string)-1, -1, -1): reverseList.append(string[x]) for index in range(len(reverseList)): newString = newString + reverseList[index] print newString''' #After def reverseStri...
7f13717fa8a7d98f3832f4978841e6cfbac37a68
jdanray/leetcode
/numSmallerByFrequency.py
2,500
3.515625
4
# https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/ class Solution(object): def numSmallerByFrequency(self, queries, words): def freq(s): s = sorted(s) f = 0 i = 0 while i < len(s) and s[i] == s[0]: f += 1 i += 1 return f fqueries = [freq(q) for q in que...
11904e5019586c4b2d5966eac73ef359021e686f
kkclaire/Leetcode
/119.py
662
3.75
4
class Solution(object): def getRow(self, rownum): """ :type rowIndex: int :rtype: List[int] """ # # Method 1: calculate all element # # result = [[1 for j in range(i)] for i in range(1, rownum + 1)] # # for i in range(2, rownum): # # for j in range(1, i)...
545ab0c0f7c50d5ff7061f3c7062b9e2f2be6b64
Mister7F/cmdargs
/examples/test_2.py
567
3.6875
4
from cmdargs import console, parse_args @console def sum(a: int, b: int = 5): ''' Sum a and b and print the result Args: a: First integer b: Second integer ''' print('Result:', a + b) @console def product(a: int, b: int = 5): ''' Multiply a and b and pr...
98cab9001f13330b247217f9e62e2dc21b32a55d
samruddhichitnis02/programs
/ProgramsA/algorithms/binary_string.py
1,040
3.8125
4
import Utilities.algo_utility import time sa = input('Press Enter to start the stopwatch') print('Stopwatch started!') begin = time.time() a=[ ] try: n = int(input('Enter length of String-')) for i in range(n): m=input('Enter the elements') if(m.isalpha()): a.append(m) else: ...
c53524099cd1d1824ce8b8a1a3fb3e4eeb264730
masakiaota/kyoupuro
/practice/ants_book/049_fence_repair.py
899
3.734375
4
# http://poj.org/problem?id=3253 from heapq import heapify, heappop, heappush, heappushpop class PriorityQueue: def __init__(self, heap): ''' heap ... list ''' self.heap = heap heapify(self.heap) def push(self, item): heappush(self.heap, item) def pop(self...
19d6a49d0f98b9204de4afa346e3dd47ab15f393
kgpyi/python
/Problem Solving/Udemy/Practice 20. Number of digits in an Integer.py
109
3.90625
4
num = int(input("Enter a number: ")) temp = 0 while num > 0: num = num // 10 temp += 1 print(temp)
f5690d93ac9b76fc64833dde50a5d77b3043d8a1
rstojan/Learning_Python
/Section8/task8.py
414
4.1875
4
# Complete the function to remove trailing spaces from the first string and # leading spaces from the second string and return the combined strings def removeSpaces(string1, string2): # Student code goes here # expected output: SFG Rocks-You know it! print(removeSpaces('SFG Rocks ', ' -You know it!')) #...
9dae9c24657681d93daac2c679ba20c832ad6e0e
AVNISHPATEL102/Python-Challenges-1
/10. First and Last Digit/PythonProgram.py
375
3.9375
4
def FirstLastDigit(): i = int(input("Please enter the number if input you want to calculate")) for x in range(1, i + 1): print("Please enter the {} number:- ".format(x)) u = int(input()) l = u % 10 while(u >= 100): u=u/10 f=int(u/10) t=f+l prin...
8f6152e51be7d7368e9e93308f32a3f24c0252b9
will8889/binus
/25-11-2019/no5.py
235
4.125
4
def reverse(text:str): reversed_text:str = " " # for i in range(len(text)-1,-1,-1): # reversed_text += text[i] # #return text [::-1] return reversed_text print(reverse("I am testing"))
543fff03db1c239696241079bcd40a10943a002f
AggarwalAnshul/Dynamic-Programming
/InterviewBit/sorted-insert-position.py
2,287
4.28125
4
""" Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 → 0 [+]Temporal marker ...
6444f3a5a58876b93ec8f60ad7726be032e3e5f1
yanhuicang/lintcode
/MinStack.py
1,333
3.96875
4
#!/usr/bin/env python # -*-coding:utf-8 -*- class MinStack: def __init__(self): # do intialization if necessary self.stack = list() self.head = -1 """ @param: number: An integer @return: nothing """ def push(self, number): # write your code here self...
fa34eb07bfad7ab8d670213711fddf9bc8ba5692
jackalsin/Python
/12746-XuesongPython/Assignment 4/BookClass.py
225
3.5625
4
class Book(object): def __init__(self, number, title, author, price, pages): self.number = number self.title = title self.author = author self.price = price self.pages = pages
90893929389c999e1501320867aa71d269558c4f
amtfbky/git_py
/dg/base/review/card_main.py
965
3.734375
4
import card_tools def main(): while True: card_tools.show_menu() action_num = input("请输入您要选择的操作:") print("您选择的操作是:【%s】" % action_num) # 这里action_num直接判断是否在列表里,很是简洁明了 if action_num in ["1", "2", "3"]: # 这里的1是字符串,要加上引号,我居然没加 if action_num == "1": ...
75eff135771c159a2e3592d1baca5ff0fc8304f2
carrickkv2/Side-Projects
/Lyrics generator.py
10,587
4.46875
4
''' This would allow the user to choose from a list of songs and then get the lyrics to that song. ''' ''' Lyrics generator Ask a user to choose from a list of 10 songs. When the user does, you print out the lyrics to the song they selected. Example: Welcome, please select a select a song from this top 10 songs: 1...
958bc74f7a4e189817721434797dd499a5ea0c2e
JupiterWalker/algorithm016
/Week_01/Mon_70_爬楼梯_动态规划.py
481
3.8125
4
# coding:utf-8 __author__ = 'cwang14' class Solution: def climbStairs(self, n: int) -> int: if n < 3: return n two_before = 1 one_before = 2 for i in range(3, n+1): temp = one_before one_before = two_before + one_before two_before = ...
478f29f01d46397a399e63dccc29d446edd4b776
sagnikghoshcr7/DSA-AlgoExpert-Practice_Solutions
/Linked Lists/reverseLinkedList.py
897
4.15625
4
""" Reverse Linked List Write a function that takes in the head of a Singly Linked List, reverses the list in place (i.e., doesn't create a brand new list), and returns its new head. Each LinkedList node has an integer value as well as a next node pointing to the next node in the list or to None / null if it's...
8db69f891e1066eb9b059eae9eeb1eb330435526
Ignatyew/Intro_Python_Homeworks_
/Homework5.py
7,395
3.734375
4
# 1. Дано целое число (int). Определить сколько нулей в этом числе. ######################################################################## value = 20020025876055505 value_str = str(value) zero = value_str.count('0') print("В числе ", value, "находится", zero, "нулей") ###############################################...
4e512ed08e9d17d46143540a5c340df7c76f6538
geniousisme/leetCode
/Python/111-minDepthBinaryTree.py
903
3.828125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {integer} def minDepth(self, root): if root: return self.minDepthTraversal(...
e45c77dd997391326ae947da5e6537cb39458720
AshTiwari/Python-Guide
/Debugging/Debugging_logging_module.py
901
3.796875
4
#Debugging logging import logging logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s-%(levelname)s-%(message)s') ''' To save the logging in a file and not show on console: logging.basicConfig(filename = 'D://programLogs.txt',level = logging.DEBUG, format = '%(asc...
06867e7e0d4a51e60956f00020b147d40c3c79ee
bobowang2017/python_study
/algorithm/leetcode/2/24.两两交换链表中的节点.py
1,303
3.75
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def new_list(self, data): head = ListNode(data[0]) p = head for idx, d in enumerate(data): if idx == 0: ...
4a03a8de212f52d24874e2d33bd08f4537f40e12
JiniousChoi/encyclopedia-in-code
/jpylib/jsorts/mergesort.py
2,584
3.53125
4
#!/usr/bin/python3 ## author: jinchoiseoul@gmail.com from math import ceil import sys sys.setrecursionlimit(10000) def mergesort_iter(arr): n = len(arr) tmp = [None] * n if n%2==1: #optimization tmp[-1] = arr[-1] unit = 1 while unit < n: for i in range(int(ceil(n/2/unit)...
bc9f20100d01d4d02d8243509f5296b2c18bc191
caudate-julie/ProjectEuler
/024.py
821
3.515625
4
# What is the millionth lexicographic permutation # of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? from math import factorial from time import time def Permutations(a, ordnum): seq = list(range(a)) n = len(seq) pnum = [0]*(n-1) seq.sort() for i in range(1, n): pnum[i-1] = factorial(n-i) ...
ab3b64c4af98fd8cfb15bc2d202233276638861b
yukiyao119/Leetcode-practice
/LongestSubstringWithoutRepeatingCharacters.py
942
3.90625
4
# Given a string s, find the length of the longest substring without repeating characters. # Example 3: # Input: s = "pwwkew" # Output: 3 # Explanation: The answer is "wke", with the length of 3. # Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. # Example 4: # Input: s = "" #...
2c62f0eb0c6d9fcc58c07df77ebf9f48cdc56b19
nnard1616/projectEuler
/PythonSolutions/41.py
782
3.9375
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 17 21:06:56 2016 @author: Nathan """ def is_prime(n): if n < 2: return False if n in (2, 3): return True if n % 2 == 0 or n % 3 == 0: return False max_divisor = int(n ** 0.5) # square root of n divisor = 5 w...
8d6683c7d0f61a9d9220f8a511235192ea9b198e
imtiaz-rahi/Py-CheckiO
/Electronic Station/Reverse Roman Numerals/mission.py
420
3.53125
4
def reverse_roman(roman_string): roms = ('CM', 'M', 'CD', 'D', 'XC', 'C', 'XL', 'L', 'IX', 'X', 'IV', 'V', 'I') ints = (900, 1000, 400, 500, 90, 100, 40, 50, 9, 10, 4, 5, 1) num = 0 for i in range(len(roms)): count = roman_string.count(roms[i]) if count > 0: ...
7d85e381eaf748f7161e3195a5635a68fa3a496f
martin-martin/nlpython
/exercises/solutions/user_input.py
252
3.984375
4
while True: message = input("enter your message: ") print(message) keep_going = input("more? enter yes/no: ") while keep_going not in ['yes', 'no']: keep_going = input("enter yes/no: ") if keep_going == 'no': break
95368f86fe126d53e4ee61fe33eb8b8727d3d32b
preetising/if_else
/side of angle_5.py
315
4.21875
4
side1=int(input( "enter the side 1")) side2=int(input("enter the side 2")) side3 =int (input("enter the side3")) if side1==side2==side3: print(" it is equilateral triangle") elif side1==side2 !=side3 or side2 == side3 !=side1 or side3==side1!=side2: print (" isosceles triangle") else: print(" scalene triangle")
0307f1378d277a968910c417e15f325eeabb7f1e
bbbourq/hello-world
/random_password_generator.py
2,388
4.25
4
#! python3 # python random password generator # First we need to import the random module import random # Set up the password list we will use to make the password password = [] while True: try: # Ask the user how many characters long they would like the password pwLength = int(input('How many characters long?...
5a03393101478a7f8ca6eb2a0c0780c537fedf78
Tomtao626/python-note
/py_interview/pythonic-code/25.数字列表化.py
458
3.625
4
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author:tom_tao626 @license: Apache Licence @file: 25.数字列表化.py @time: 2020/12/10 @contact: tp320670258@gmail.com @site: xxxx.suizhu.net @software: PyCharm """ # 下面代码将整数转换为数字列表。 nums = 123456 # 使用map digit_list = list(map(int, str(nums))) print(digit_list) # [1,2,...
dd5a46a819f1da2bc4b7139b05ba98fd983d1ce7
BrianLoveGa/atbs-python
/section-06/listDataType.py
1,413
3.984375
4
# 6.13 - like a JS array # ['cat', 'bat', 'rat', 'dog'] spam = ['cat', 'bat', 'rat', 'dog'] # spam[0] = 'cat' # layered lists cake = ['frog', 'lizard', ['car', ['ford', 'chevy'], 'bus', 'truck'], 'snake', 'toad', ['tree', 'flower']] # can access forwards print(cake[2][1][1]) print("T...
bb4c89ebb6846b6e64ea66dd53a7551ff395be15
ArunRamachandran/ThinkPython-Solutions
/Chapter12/read_file.py
218
3.734375
4
def read_file(): fin = open('words.txt') # where , fin is the file object # File object provides several methods for reading, including # readline etc. print fin line = fin.readline() print line read_file()
fdce4d15b9423aabd71cf7f06f82afe0a1ef3a0c
c108glass/MIT-IntroProgramming-Python
/Lecture4-Python-MachineInterpretation.py
4,001
4.34375
4
##Lecture 4 ##Machine Interpretation of a Program ##Intro to Computer Science And Programming - MIT ##https://ocw.mit.edu ##One issue with the previous lecture's bisection search program (shown below) ##is that it doesn't account for an x less than 1. ##The square root of any x less than 1 will be greater than ...
c6e4a83b7a09326660bf4683b162f07aee17a41e
AnsonYW/python-summary
/test_accountant.py
402
3.703125
4
import unittest from accountant import Accountant class TestAccountant(unittest.TestCase): """Test for the class Accountant""" def test_initial_balance(self): # Default balance should be 0 acc = Accountant() self.assertEqual(acc.balance, 0) # Test non-default balance. ...
fb92f16786314af071039c24f2cce0a8b0d86dac
TheGeekAndI/online-courses
/003 Discrete Optimisation/02 Week 2/knapsack/greedy_solvers.py
4,846
3.84375
4
""" The greedy solver class contains the different greedy solvers for the knapsack problem """ from collections import namedtuple import pandas as pd from operator import attrgetter, itemgetter import time class Greedy_solvers(object): """ Object which contains different optimsation solver algorithms """ ...
30c9bb1f1eed2c741ed6016b1b030f5652f5a501
lan-tianyu/python3
/CookBook-Learning/code/chapter8/test-8-5.py
1,044
3.671875
4
class A: def __init__(self): self._internal = 0 self.public = 1 def public_func(self): print('public_func') self._internal_func() def _internal_func(self): print('_internal_func') a = A() a.public_func() # a._internal_func() print(a.public) # print(a._internal) p...
492d516863c3b877e9137f414158ebacfd920ab3
B04kaMedy/TelegramBotICT
/excel/excel_db.py
4,788
3.703125
4
import csv from typing import List, Dict, Optional from excel.functions import * _students = dict() # type: dict[str: List[str]] _columns = ['student'] # type: List[str] def push_to_tmp_container(file_name: str): for student_name in _students: update_student_list(student_name) path = file_name ...
29f9d538b9bd19b03e0cae90f96557a83368435d
chrisxue815/leetcode_python
/problems/test_0395_two_pointers.py
1,373
3.515625
4
import unittest import utils # O(n) time. O(1) space. Two pointers. class Solution: def longestSubstring(self, s: str, k: int) -> int: result = 0 for max_num_unique_chars in range(1, 27): counts = [0] * 128 lo = 0 hi = 0 num_unique_chars = 0 ...
6096dec1cf377b24197050b7d17808329d1e54f2
zhukaijun0629/Programming_Daily-Practice
/2020-12-17_Determine-If-Linked-List-is-Palindrome.py
867
4.0625
4
""" Hi, here's your problem today. This problem was recently asked by Microsoft: You are given a doubly linked list. Determine if it is a palindrome. Can you do this for a singly linked list? """ class Node(object): def __init__(self, val): self.val = val self.next = None self.prev = None def is_palin...
0891ec72450474e8e97b51c4042f4c8df7eb64db
adityachhajer/LeetCodeSolutions
/Sum of Root To Leaf Binary Numbers.py
789
3.6875
4
# 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 selff(self, ans, root, l): if root == None: return ans = ans + str...
5f74237c53e9107b304b1116cf65cadfae8962c4
wlj572831/Class_27
/day01/课下/练习/猜年龄.py
1,855
3.890625
4
''' 练习1:猜年龄游戏 (10分钟) 要求: 允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出 ''' # # #定义真实年龄 # age = 22 # # #循环次数初始值 # count = 0 # # while count < 3 : # #用户输入年龄并转为int类型 # input_age = int(input('猜年龄:')) # if input_age == age: # exit('恭喜您猜对了') # #循环次数+1 # count += 1 ''' 练习2:猜年龄游戏升级版 要求: 1. 定义循环初始值,wh...
a0145e9a7a3fc5706cf471ff127c72d7e991fcf6
omer-ayhan/Python101
/Alıştırmalar/İki Liste.py
557
4.15625
4
def two_list(list1, list2): new_dict = dict() try: # checks if length of two lists are equal if len(list1)!=len(list2): raise IndexError for key in list1: # adds two lists as key-value pair new_dict[key] = list2[list1.index(key)] return new_di...
967e302346e5eb1eb205b5c33c3d84d23af37550
sgsangam/GitRep
/gettweets.py
4,839
3.796875
4
import oauth2 as oauth import urllib2 as urllib import json """ gettweets.py: Author: S. G. Sangameswara Contact: sgsangam@gmail.com Created for: Coursera Data Science Coursolve Project Uasge: python27\python 'gettweets.py' 'serach_terms.txt', where serach_terms is any file containg serach keywords, one perline...
4dbb6d16f45b04e1660ef3dff1aa2d0e0ff407b1
AmreshTripathy/Python
/103_decorator_property.py
539
3.546875
4
class Employee: company = 'Bharat Gas' salary = 5600 salaryBonus = 400 # totalSalary = 6100 @classmethod def printSalary(cls, val): cls.salary = val @property def totalSalary(self): return self.salary + self.salaryBonus @totalSalary.setter de...
74de02417cb35bd33ef032157706034689c95e52
blackdogcode/PythonBoot
/100DaysOfCode/Day015/CoffeeMachine/main.py
3,011
3.828125
4
from coffee_machine import nespresso from coffee import coffees def turn_on(coffee_machine): if not coffee_machine['status']: coffee_machine['status'] = True print(f'The coffee machine is turned on successfully') def turn_off(coffee_machine): if coffee_machine['status']: coffee_machi...
e3bdee9dce11195e5801a509182d958ff5cffe71
clovery410/mycode
/leetcode_review2/100same_tree.py
573
3.5625
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree(self, p, q): def dfs(node1, node2): if node1 == None and node2 == None: return True if node1 == None or n...
0cde3444a7896a01433c67c513af68e70b66c1f9
alex75311/Python-homework-4
/Isaev_Alexey_DZ4_2.py
844
4.21875
4
''' Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. ''' from random import randint def gen_max(arg): result = [x for idx, x ...
4e2a0a25a99ece09f26fd7646f1bf4bad701822f
aidansoffe/python
/first.py
1,203
4.0625
4
""" >>> adder( ... 2, ... multiply(3, 4) ... ) 14 """ def adder(x, y): """ >>> adder(3,9) 12 >>> adder(8, -9) -1 >>> adder(2, -33333333) -33333331 """ return x + y def multiply(x, y): return x * y class Cat: """ >>> cats_a=Cat("V") >>> cats_a.say_hello() Meow! My name is V >>> cats...
488338ac69785bf62e646ee40a66c60eef6f6285
padillandrea/JavaWhileAnalyser
/tokenizador.py
419
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re def tokenizador(whiles): file = open(whiles, "r") lines = [line.strip() for line in file.readlines() if line.strip() != ""] file.close() tokenArray = re.finditer(r"while|[(a-z0-9<>){}]|==", ''.join(lines)) tokens = [] for e...
8667118827d55765cd90a2cd6a5ca6e7cfaefc54
baasitsharief/Python-Function-Assignments
/Question6.py
1,032
3.890625
4
def pygLatin(word): #takes a word. processes accordingly. vowels=['a','e','i','o','u'] word=word.lower().strip() if(not word): return '' if(word.isnumeric()): new_word=word elif(word[0] in vowels): new_word=word+'hay' else: new_word=word[1:]+word[...
f60254fe64c5892ce0e0b062f5ac64956e827e84
Gyaha/AOC2020
/day_07_b.py
2,152
3.625
4
TARGET = "shiny gold" def create_rules(s: str) -> dict: rules = {} for l in s.strip("\n").split("\n"): current_bag, contained_bags = l.strip().split(" bags contain ") contained_list = [] for b in contained_bags.split(", "): if b == "no other bags.": continue...
43382f2d44d6f21ebbfee11820822f199d300076
tyler-fishbone/data-structures-and-algorithms
/challenges/shift-list/shift_list.py
366
3.890625
4
def insert_shift_list(list_input, val): list_output = [] list_midpoint = len(list_input) // 2 for i in range(len(list_input) + 1): if i < list_midpoint: list_output += [list_input[i]] elif i == list_midpoint: list_output += [val] else: list_output ...
9e81789bc1090110c5794ca324d0acbde4fabc74
am8265/BioinformaticsAlgorithms
/Course1/matchPattern.py
672
3.875
4
#!/usr/bin/env python #######Match a Pattern in a Genome############## import sys import re def patternMatch(genome,pattern): pos=0 positions=[] while True: pos=genome.find(pattern,pos) if pos==-1: break; positions.append(pos) pos=pos+1 if len(positions)==0: ...
4412ddf62308fe3e78893772a7a96c559e32c20f
luciengaitskell/csci-aerie
/csci0160/3-data/athome4_stacks_queues.py
5,884
4.1875
4
""" Stacks and Queues Handout Due: Tuesday, October 13th NOTES: - For the exercises, please do NOT use online resources. They are common algorithm questions so they have answers online but it won't help your understanding. - If you are stuck or want help on any of them, come to office hours! Completed by Luc...
2fff5b78fa2d32adc149ba7cdb2432efa754a4d8
C-SIN-TC1028-002-2113/ses03-ej1-A01742292
/assignments/13CantidadLitrosPintura/src/exercise.py
252
3.734375
4
def main(): #escribe tu código abajo de esta línea a= float(input("cuanta area ocupas pintar: ")) r= float(input("cuanto te rinde la pintura: ")) l= a/r print("vas a comprar estos litros",l) if __name__ == '__main__': main()
ee49a41b80f0c38e3d490d59dfd5f270ee34ab6f
INFO-4602-5602/project-3-mozilla-project-3-team-6
/vis2/parse_data.py
6,116
4.0625
4
#!/usr/bin/env python3 import csv from nested_dict import nested_dict from collections import defaultdict class MaleFemaleVis(): """ Class that contains the functions needed to read in a csv file and filter it to provide data for a visualization """ def __init__(self, filename='../data/NCWIT...
a3426688e6f57df25ba72dec155075a7958c5aeb
oxhead/CodingYourWay
/src/lt_16.py
1,658
3.828125
4
""" https://leetcode.com/problems/3sum-closest Related: - lt_15_3sum - lt_259_3sum-smaller """ """ Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. ...
fa0af287924867eab0e438b4912e0e4d91a496ac
qqqyyy111/Algorithm
/python/graph.py
5,901
3.609375
4
#!/usr/bin/env python """ Graph classes. Contains graph data structure implementations. 1/11/2013 created Yong Shin """ from __future__ import division import heapq, copy class Graph(object): """Adjacency list implemetation of graph data structure. Graph instance is created by specifying number of vert...
b7fdb59e882fef7de617fea9a243b327bff72a6a
kiara-williams/ProgrammingII
/prac_05/word_occurrences.py
909
4.15625
4
"""Program that takes a string and counts unique words""" def main(): words = {} longest_word = 0 word_string = input("Enter a string").lower() word_list = word_string.split() for word in word_list: if len(word) > longest_word: longest_word = len(word) if word in words: ...
c42c50e0de45b6a8eef8c41d07b55b3600345f10
sdeva90/Python
/deletingnode_linkedlist.py
3,215
4.34375
4
# deleting the middle nodes in linked list class LinkedList: head = None # head will always contain the first Node of LinkedList def LinkedList(self): self.head = None class Node: data = 0 next_node = None #Adds node to the start of the LinkedList def push...
62677d839c68595eb80b15ece568b378a35dfcdc
hardik8945/power-of-two
/power.py
647
4.46875
4
''' Write a program to find whether a given number is a power of 2 or not. Input format: The first line of the input contains the number n for which you have to find whether it is a power of 2 or not. Output Format: Print 'YES' or 'NO' accordingly without quotes. Example: Input: 32 Output: YES Input: 26 Output:...
66137dff632153d9526125ed0760c03c02d1e3fb
klundblad/Monkey-Brains-Test
/MonkeyBrainsGraphDisplay.py
1,528
3.90625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a test for plotting MatLib with Tkinter Using a canvas plotting a graph for voltage data display """ import tkinter #something to get stuff connected to tkinter interface from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,Na) from matplotli...
c2c7f8c2890884914a7037ef9bd0ef6c582b2dc1
vicasindia/programming
/Python/if_else_statement.py
219
4.125
4
# Control flow: if-else statement number = 40 if number < 20: print(number, "is less than 20") # Printing if condition is true else: print(number, "is greater than or equal to 20") # Printing if condition is false
a3e17667db8540ad8a33e98a8157d2ebcb09444c
stephenchung27/old-python-leetcode
/Google Questions/Jeff's Google Questions/number_two.py
909
4.125
4
''' Given an unsorted array, return the numbers that can be found with binary search. Time complexity: O(n) ''' # Current iteration is O(logn) def binarySearchable(arr): def leftSearch(start, end, prev): if start > end: return mid = (start + end) // 2 if arr[mid] <= arr[prev]: nums.append(a...
8fe8cce4287168ba91e87351260aeca1606468f6
xiaotian1991/actual-10-homework
/03/sunhao/nginx-raw-function-ip.py
1,046
3.515625
4
#!/usr/local/bin/python #-*- coding: UTF-8 -*- def open_file(file_name): res = {} with open(file_name) as f: for line in f: tmp = line.split(" ") ip = tmp[0] if ip in res: res[ip] += 1 else: res[ip] = 1 retur...
3934f5298928e85285170136b567954aafa92a1d
Naveenpenta/Hackerrank
/WarmUp/7.Staircase.py
204
3.765625
4
#!/bin/python3 import sys n = int(input().strip()) for i in range(1,n+1): for j in range(n,i,-1): print(" ",end='') for k in range(i): print("#",end='') print()
e2c87c0cdada0d2e5b127bdae4e9fdfc263dfbcb
BlazejNowicki/ASD
/obowiazkowe/sort_n_from_0_n2-1_range.py
606
3.625
4
from random import randint def counting_sort(A, key, n): C = [0]*n B = [0]*(n*n) for i in range(n): C[key(A[i])] += 1 for i in range(1, n): C[i] += C[i-1] for i in range(n-1, -1, -1): C[key(A[i])] -= 1 B[C[key(A[i])]] = A[i] return B def sort_linear(T, n): t...
6ae83d84a7e1f96e6a3ef31bcecf4bab39f58d6e
alehatsman/pylearn
/py/lists/merge_sorted.py
514
4.34375
4
def merge_sorted(head1, head2): """ Mergers two sorted linked lists. Time complexity: O(N) Space complexity: O(1) """ cn1 = head1 cn2 = head2 head = None if cn1.value <= cn2.value: head = cn1 else: head = cn2 while cn1 and cn2: if cn1.value > cn2....
46a84c3249274c271af118c825d22b1930cebf7e
jlin711110/yzu_python-20210414
/day02/hello5.py
253
3.703125
4
# -*- coding:UTF-8 -*- h=1.73 w=90 BMI=w/(h*h) bmi=w/(h**2) print("H=",h,"; \nW=",w,"; \nBMI=",BMI, ";\nbmi= %.2f" %bmi) print(5/2) print(5//2) # 整除 print(5%2) # 餘數 num = 1234567 if num%2 == 0: print("偶數") else: print("奇數")
28339fa3e4c9529ec421ea827771da4184524211
KECaram/PythonWeatherApp
/weatherWebApp.py
3,118
3.75
4
#!/usr/bin/python # Keith Caram # INFO.305.061: Survey of Python, Perl, and PHP # Assignment #4 - Complex Python Program # Program Summary # This is a python web app that returns weather conditions using the openweathermap API. The program # uses the Flask web framework to create a development server that hosts ...
acc257e33a0d319150cb98576f5e1d04a972e21d
bdscloud/MachineLearningProject
/Initialisation-et-matrice-propre.py
11,889
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 21 09:04:00 2016 @author: BriceLaTeub """ import random import numpy as np import matplotlib.pyplot as plt import math as math import copy as cp import scipy.ndimage # ***** Déclaration des classes ***** class Point(): "Un point de notre plan" class P...
206ab566f82162376a266f495fb8b55d10f31680
longtomjr/project_euler
/solutions/problem_007.py
1,664
4.28125
4
#!/usr/bin/env python3 import math def prime_range(n: int) -> list: """ Gets a range that the nth prime can reasonably be expected to be in Found the formula (from the Prime Number Theorem) here: https://math.stackexchange.com/questions/1257/is-there-a-known-mathematical-equation-to-find-the-nth-prime...
df79e11c42da50525000a3cb2723b76b5b37ae80
ole511/hello_world
/54字符流中第一个不重复的字符.py
1,493
3.671875
4
# -*- coding:utf-8 -*- 用了内置函数count class Solution: # 返回对应char def __init__(self): self.s="" def FirstAppearingOnce(self): # write code here res=filter(lambda c:self.s.count(c)==1,self.s) return res[0] if res else '#' def Insert(self, char): # write code here ...
58161a7469e00603a0aa0a8ba62940c4594d32d7
fabiomacdo/curso-python
/mundo2/ex041.py
411
4
4
from datetime import date atual = date.today().year nasc = int(input('Informe o ano de nascimento: ')) idade = atual - nasc print('O atleta tem {} anos.'.format(idade)) if idade <= 9: print('Categoria: MIRIM') elif idade <= 14: print('Categoria: INFANTIL') elif idade <= 19: print('Categoria: JUNIOR') elif i...