blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
63bcc3398aa5a360cb9c2cb6b9a81ebf44c3a0ab
chxj1992/leetcode-exercise
/55_jump_game/_1.py
1,008
3.71875
4
import unittest from typing import List class Solution: def canJump(self, nums: List[int]) -> bool: """ Timeout! """ cache = {} def recursion(index: int): if index in cache: return cache[index] if len(nums[index:]) == 1 or not nums[i...
5748c6b5d7a4fd16e633d70728212ba3853109d3
chxj1992/leetcode-exercise
/169_majority_element/_2.py
651
3.65625
4
import unittest from typing import List class Solution: def majorityElement(self, nums: List[int]) -> int: l = len(nums) // 2 nums.sort() prev = nums[0] count = 0 for i in nums: if i == prev: count += 1 else: prev = i ...
ca3f41a8b2e0ead234da83522cec6712f0f93ba3
chxj1992/leetcode-exercise
/49_group_anagrams/_1.py
1,539
3.765625
4
import unittest from typing import List class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: """ Time: O(n^2) Space: O(1) Timeout! """ res = [] while len(strs) > 0: curr = strs.pop(0) row = [curr] i...
a40a82211b52554af5b14c1674bb22a80939b619
chxj1992/leetcode-exercise
/subject_lcof/29/_1.py
1,156
3.890625
4
import unittest from typing import List class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if len(matrix) == 0: return [] curr = (0, 0) left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1 res = [matrix[0][0]] while rig...
5e208e7700e6cfab63cf67e6e6ebe2f3a50e036b
chxj1992/leetcode-exercise
/190_reverse_bits/_1.py
353
3.515625
4
import unittest class Solution: def reverseBits(self, n: int) -> int: b = bin(n)[2:] b = '0' * (32 - len(b)) + b return int(b[::-1], 2) class Test(unittest.TestCase): def test(self): s = Solution() self.assertEqual(964176192, s.reverseBits(43261596)) if __name__ ==...
769a79c8ad14b52843a548f46897ceeff73a43d1
chxj1992/leetcode-exercise
/subject_lcof/22/_1.py
976
3.9375
4
import unittest # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: prev = head i = 1 while head: if i > k: p...
0cf283edd673daeff56b6ed2e4211c3c292665d6
chxj1992/leetcode-exercise
/198_house_robber/_2.py
574
3.78125
4
import unittest from typing import List class Solution: def rob(self, nums: List[int]) -> int: dp_list = [0] for i, x in enumerate(nums): if i < 2: dp_list.append(max(nums[:i + 1])) else: dp_list.append(max(dp_list[i], dp_list[i - 1] + x)) ...
c4619837564f4be4a25a01ed14789b1ca5ea657d
GeekTemo/Python_Algorithms
/sort/merge_sort.py
614
3.859375
4
__author__ = 'gongxingfa' def merge(arr, lo, mid, hi): for i in range(lo, hi): aux[i] = arr[i] i = lo j = mid + 1 k = lo while k <= hi: # or (i < mid or j < hi) if i > mid: arr[k] = aux[j] j += 1 elif j > hi: arr[k] = aux[i] ...
2a079f90c7e359d61aca111a7d3d8a6cb29349a1
axiomiety/exercism-io
/python/clock.py
455
3.765625
4
class Clock(object): def __init__(self, hours, minutes): self.minutes = minutes % 60 self.hours = (hours + minutes // 60) % 24 def add(self, minutes): m = (self.minutes + minutes) % 60 h = (self.hours + (self.minutes + minutes) // 60) % 24 return Clock(h,m) def __repr__(self): return '...
7280cc558f163f80889c0ed161b31fb34e89f48b
Kaustav-Byte/Assignments
/Untitled.py
413
3.90625
4
#!/usr/bin/env python # coding: utf-8 # In[11]: for i in range (2000, 3000,1): if i%7== 0 and i/5!=0: print (i,',',end="") else: continue # In[15]: def my_function(x): return x[::-1] mytxt = my_function(input('Enter your First name= ')) myend =my_function(input('Enter your Second ...
21e0efc165d96630552f72405d8c99c61dcdc252
green-fox-academy/dzsofa
/PythonPractice/0104/linearsearch.py
204
3.84375
4
numbers = [4, 5, 6] def linear_search(my_list, sought): for number in my_list: if number == sought: return my_list.index(number) return -1 print(linear_search(numbers, 6))
c137c714f180a04d18ee4427edd9021ffcf1fa73
green-fox-academy/dzsofa
/PythonPractice/1211/PrintBigger.py
393
4.125
4
# Write a program that asks for two numbers and prints the bigger one number1 = int(input("Give me the first number: ")) number2 = int(input("Give me the second number")) def printbigger(number1, number2): if number1 > number2: print(number1) elif number2 > number1: print(number2) else: ...
445b08a82edb6952c0e4d7eff6a56d2f0491a0dd
penguinsss/interface
/requests库/请求/get请求/getBaiduRequestParams.py
496
3.640625
4
""" Requests库是用Python编写的,基于urllib开发的工具,能够进行HTTP协议的接口测试和调试工作,使用简单,功能强大,完全满足HTTP测试需求; """ import requests # 3种方式访问百度搜索,params的值为一个字符串或字典 resp = requests.get('http://www.baidu.com/S?wd=嗯哼') resp1 = requests.get('http://www.baidu.com/S', params="wd=杨幂") resp2 = requests.get('http://www.baidu.com/S', params={"wd": "秋刀鱼"}) ...
915c64980a5d689f4f1333ebdc3116f59f231c74
penguinsss/interface
/requests库/事务.py
1,244
3.8125
4
""" 事务提交机制: 自动提交: 1 建立连接设置autocommit=True来设置自动提交 2 建立连接后,通过conn.autocommit(True)来设置 手动提交: 1 conn.rollback 进行回滚 2 conn.commit 进行提交 """ import pymysql conn, cursor = None, None try: conn = pymysql.connect('localhost', 'root', 'root', 'books') # utf8, utf-8不行 cursor = co...
3d3e9db12ff25265fe6994218ba6052cc6f9568a
kvsaijayanthkrishna/Python_Programming
/2_character_frequency.py
404
4.40625
4
#2. Write a Python program to count the number of characters (character frequency) in a string. #Sample String : google.com' #Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1} string=input("enter a string\t:") letter="" print("output:-") for s in string: if s not in letter: ...
8afb9e8b2813f3c14161304f4786948f20a5015f
kvsaijayanthkrishna/Python_Programming
/addition of two numbers.py
177
4.03125
4
#. Write a program to add 2 numbers. Accept the input in a single line. n1,n2=(input("enter 2no's\t:")).split() n1=int(n1);n2=eval(n2) print(n1,"+",n2,"=",n1+n2) print()
2ccd3e41c313528e0fb0eb75f79d969bdcdcce16
kvsaijayanthkrishna/Python_Programming
/sum_of_first_n_nos.py
153
4.0625
4
#sum of first n numbers n=int(input("enter a number\t:")) sum=0 for i in range(1,n+1): sum+=i print("sum of {0} numbers is {1}".format(n,sum))
f9a50021eca47f4d830454f08a46dfc80d2afd6f
kvsaijayanthkrishna/Python_Programming
/5_long_word.py
406
4.28125
4
#5. Write a Python function that takes a list of words and returns the length of the longest one. string=input("enter list of words with spaces\t:") words_list=string.split() length=len(words_list[0]) longest="" for word in words_list: if len(word)>length: length=len(word) longest=word prin...
2ce0060c14988f64d14dcd84a6014994cce06384
kvsaijayanthkrishna/Python_Programming
/7_remove_odd_index.py
259
4.34375
4
#7. Write a Python program to remove the characters #which have odd index values of a given string. string=input("enter a string\t:") new_string="" i=0 for s in string: if(i%2==0): new_string+=s i=i+1 print("new string:-",new_string)
d81b3164e349450e7d9daf6c0543c85e927b037a
kvsaijayanthkrishna/Python_Programming
/triangle2.py
129
3.78125
4
m=int(input("enter size\t:")) for i in range(m): for i in range(m-i,0,-1): print("*",end=" ") print()
5df716b35bcabe42bec9830de5b6cb76aeaaaad0
kvsaijayanthkrishna/Python_Programming
/string_without_vowels_for.py
269
4.34375
4
#lec-19/slide-8 #Write a program to accept a string from the user and display it vertically #but don’t display the vowels in it using for loop. string=input("enter a string\t:-") for ch in string: if ch in "aeiou": continue print(ch) print()
0331f1354dc9537c01f4294d4d6ae40fd630fe05
victorhook/mqtt-broker
/src/utils/security.py
4,410
3.578125
4
import binascii import hashlib import getpass import os import sys CREDENTIALS_FILE = 'passwd' BASE_DIR = os.path.join(os.path.dirname(sys.argv[0]), 'etc') CREDENTIALS_PATH = os.path.join(BASE_DIR, CREDENTIALS_FILE) PASSWORD_LIMIT = 4 def hash_password(password): """ hashes a given password with sha256 and r...
f5078fcf3bcf7f46e168969a33c6c334e17685cf
Vasia228/hello
/Сдать/BinTree.py
5,599
3.703125
4
class node(): def __init__(self,data,left,right,mother): self.Data=data self.Left=left self.Right=right self.Mother=mother def inputNode(root,data): curCheck=root while(1): if data>curCheck.Data: if curCheck.Right==0: curCheck....
d5beac50f1ed6a986a635201e8745aaf55ea117d
pavel-malin/pavel
/buttondot.py
375
3.640625
4
from tkinter import * root = Tk() var = IntVar() rbutton1 = Radiobutton(root, text='1', variable=var, value=1) rbutton2 = Radiobutton(root, text='2', variable=var, value=1) rbutton3 = Radiobutton(root, text='3', variable=var, value=1) rbutton1.pack() rbutton2.pack() rbutton3.pack() root.mainloop() """ point select...
e2fcf0917844232594be77ed02d59d72a217ea57
MechaEdgar/PracticasPython
/hello.py
246
4.09375
4
print ("Hola mundo!") hola =input("hola ¿cual es tu nombre? ") print ("mucho gusto en conocerte " + hola) edad = input("Cual es tu edad: ") print ("Entonces tu nombre es: " +hola+ " Y tu edad es: "+ edad) a= "a" print ("Esto es una letra " + a)
3446ddab720a3a900616a85172dce04e87dc5621
Schmidty88/ICP3
/Source/File2.py
418
4.3125
4
#This function is used for counting vowels then def VowelCount(Sentence): #this set contains all the vowels we will be using if #it sees a letter in the set it will add to the counter Vowel = set("aeiou") counter = 0 for letter in Sentence: if letter in Vowel: counter += 1 print("Vow...
edd9b8b1f15497f1dc1c246027a5c294cf9d0566
kevinmolina-io/GrokkingInterview
/Two_Pointer/tripletSumCloseToTarget.py
1,834
4.09375
4
def triplet_sum_close_to_target(arr, target_sum): """ HIGH LEVEL: This is a similar approach to triplet sum, with a little twist. You want to use a two pointer approach to solve it efficiently. Here's how it goes: Variables: closest_sum global_difference left, right...
f968395c2a1f85a5121e66d80bb0b52a80012fc0
kevinmolina-io/GrokkingInterview
/Sliding_Window/permutationInAString.py
2,018
3.984375
4
def find_permutation(str, pattern): """ HIGH LEVEL: Create a hashmap that keeps track of frequency count of each letter in pattern. You want to use a sliding window technique, and keep expanding the window until you reach len(pattern), at that point you need to shrink the window In bet...
ab3de7e5c050ac72c931c3f039cf479a54350cd8
kevinmolina-io/GrokkingInterview
/Sliding_Window/longestSub_sameLetters_replacement.py
1,198
4.125
4
def length_of_longest_substring(str, k): """ HIGH LEVEL: This is another sliding window problem. The trick to these problems where they ask to find the longest substring AFTER REPLACEMENT, is to keep track of the max repeating character. If the difference between the current substring and...
76ad5a738f26b25f109febcc2777a489d5d41d18
sophiaperson/ConLingo
/syntax.py
752
3.5
4
# Sophia Ho # Sentence Class # andrewID: swho # Recitation: P class Sentence(object): def __init__(self, writtenSent, pronuncation, meaning): self.writtenSent = writtenSent self.pronunciation = pronunciation self.meaning = meaning def getHashables(self): return (self.writtenSent...
06ea4f9e9cb4c0912cae59fe0ae4ed2eb730b65e
BenjaminAage/Kattis_Problems
/Level_1.3/greetings.py
179
3.75
4
greeting = input() returnGreeting = "" count = 0 for i in greeting: if i == "e": returnGreeting += "ee" else: returnGreeting += i print(returnGreeting)
734f5cffc4e86a353170af1f5217c3bb0435ded0
BenjaminAage/Kattis_Problems
/Level_1.4/spavanac.py
307
3.796875
4
time = input() Hours, Minutes = time.split(" ") if int(Minutes) <= 44: if int(Hours) != 0: Hours = int(Hours) - 1 Minutes = int(Minutes) + 15 else: Hours = 23 Minutes = int(Minutes) + 15 else: Minutes = int(Minutes) - 45 print(str(Hours) + " " + str(Minutes))
c3db0feccf0bab678a1e4aa816e26cf72f5f3903
BenjaminAage/Kattis_Problems
/Level_1.3/qualityAdjustedLifeYear.py
153
3.53125
4
N = int(input()) count = 0.0 for i in range(N): qaly = input() num1, num2 = qaly.split(" ") count += float(num1) * float(num2) print(count)
20d04fa9553f7cdb8951580c57c431daa24c0f62
BenjaminAage/Kattis_Problems
/Level_1.4/alphabetSpam.py
426
4.03125
4
sentence = input() whitespace = 0.0 lowercase = 0.0 uppercase = 0.0 symbols = 0.0 for i in sentence: if i == "_": whitespace += 1 elif i.islower(): lowercase += 1 elif i.isupper(): uppercase += 1 else: symbols += 1 print(float(whitespace / len(sentence))) print(float(...
2adc0f98b406a943027c44cf721477151bdb25cb
BenjaminAage/Kattis_Problems
/Level_1.4/acmContestScoring.py
674
3.671875
4
correct = {} incorrect = {} problem = "" solved = 0 time = 0 while problem != "-1": problem = input() if len(problem) < 3: break problem = problem.split(" ") key = problem[1] if problem[2] == "right": solved += 1 if key in incorrect: value = incorrect.get(key...
c5f748a26f2ed3b68c9d3e1fe826ce372d855de6
tong800/ICS-32
/project0.py
366
3.53125
4
user = int(input()) if user < 1000: i = 1 x = " " print("+-+") print("| |") if user > 1: print("+-+-+") elif user ==1: print ("+-+") while i != user: print(x*i + "| |") if i+1 != user: print(x*i + "+-+-+") else: ...
8fa1324afa4f9d46559a5997f5c90b56fe947e79
jpch89/effectivepython
/ep015_nonlocal.py
2,203
4.25
4
# 把 numbers 中出现在 group 里面的数字放在前面 def sort_priority(values, group): def helper(x): if x in group: return (0, x) return (1, x) values.sort(key=helper) numbers = [8, 3, 1, 2, 5, 4, 7, 6] group = {2, 3, 5, 7} sort_priority(numbers, group) print(numbers) """ [2, 3, 5, 7, 1, 4, 6, 8] """ ...
ed7035dec39bf19299ac149805a2be8aa829ecc1
jpch89/effectivepython
/ep028_collectionsabc.py
616
3.84375
4
class FrequencyList(list): def __init__(self, members): super().__init__(members) def frequency(self): counts = {} for item in self: counts.setdefault(item, 0) counts[item] += 1 return counts # 继承于 list 的类拥有 list 提供的全部标准功能 foo = FrequencyList(['a', 'b', ...
b345d66b818e6d3816b3cad8b19b77ae135df6c1
jpch89/effectivepython
/ep008_nolongcomprehensions.py
1,396
3.71875
4
# 使用两级列表推导展开矩阵 # 推导顺序是从左到右 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [x for row in matrix for x in row] print(flat) print('-' * 50) # 对矩阵每个元素求平方,组成新矩阵 squared = [[x ** 2 for x in row] for row in matrix] print(squared) print('-' * 50) # 假如是三维列表,列表推导要拆成几行才好看 # 不推荐这种写法,因为没有比嵌套循环更清晰方便 my_lists...
e8013f373923e2f9dbb39515196b7279b9587fc2
yyoonca/Python
/hackerrank/BuiltIn/G.py
1,335
3.796875
4
''' @author: simon.park version 1 ''' N=int(input()) students = [] lowest = 100 for i in range(N): lst = [] x = input() y = float(input()) lowest = min(lowest,y) lst.append(x) lst.append(y) students.append(lst) # It will creat another list which remove the students having the lowest grade...
0893c94c67b71eb46f6781df5e33b28f3747310d
sidvanvliet/py-fibonacci-sequence
/main.py
315
3.671875
4
times = int(input('Enter the sequence amount (e.x.: 19): ')) print("Writing out " + str(times) + " Fibonacci sequences:\n- - -") previous_y = 1 previous_z = 2 for time in range(times): seq_answer = (previous_y + previous_z) previous_y = previous_z previous_z = seq_answer print(str(seq_answer))
9f32fb1e545ff04eed882ce994985a1415a01ef7
myusf01/100-days-of-code
/R1D2/edx_interst.py
1,510
3.8125
4
""" author= Muhammed Yusuf bln: stands for balance aIR: for Annual Interest Rate mPr: for Monthly Payment Rate """ ### Version 0.1 def interest(bln, aIr, mPr): def clc(bln, aIr, mPr): for i in range(12): monthlyInterstRate = aIr / 12.0 minMonthlyPayment = mPr * bln mo...
6f51919565828d00d6fdb14ae8bf292a07949522
mallison/herdcats
/herdcats/players.py
3,690
3.734375
4
"""Players (owners and cats).""" from . import tube def create(number): """Returns list of cats and owners positioned at random stations.""" owner_and_cats = [] for i in xrange(number): owner_and_cats.append(_create()) return owner_and_cats def move(owners_and_cats, turn): """Returns lis...
188e698e8700061f8661b234de6312ce1fd39ab3
msinghnanhre/Python-Coding-Challenges
/hackerRank/timeConversion.py
281
3.875
4
timeString = "07:05:45PM" def timeConversion(s): if s[-2:] == "AM" and s[0:2] == "12": return("00" + s[2:-2]) elif s[-2:] == "PM" and s[0:2] == "12" or s[-2:] == "AM": return(str(s[:-2])) elif s[-2:] == "PM": return(str(int(s[:2])+12)+s[2:-2])
e9db3680392dcf98ef17c701c46f6365e87ddccf
robertperimov/amis_python71
/km71/Perimov_Robert/mylabs/3/task1.py
198
4.125
4
print("this program will add together 3 numbers") x = int(input("enter first number ")) y = int(input("enter second number ")) z = int(input("enter third number ")) answer = x + y + z print(answer)
a82225eb7ccb800305ecbe88ab91fed75b17ca5a
ldc84/python-ex
/basic/20.logic.py
532
3.640625
4
# def return_false(): # print('함수 return_false') # return False # def return_true(): # print('함수 return_true') # return True # print('테스트1') # a = return_false() # b = return_true() # if a and b: # print(True) # else: # print(False) # print('테스트2') # if return_false() and return_true(): # 단락평가 # print...
cf7a0debe3c0675cdfd2c0ac62f247a53be5f05b
ldc84/python-ex
/basic/16.tuple_packing.py
200
3.671875
4
a, b = 1, 2 print(a, b) c = (3,4) print(c) d, e = c print(d, e) f = d, e print(f) x = 5 y = 10 print(x, y) x, y = y, x print(x, y) def tuple_func(): return 1, 2 q, w = tuple_func() print(q, w)
edf10b96c29c5d23ab8b295612994e72fd709136
noraibraheem/Hangman_project
/hangman.py
2,657
3.90625
4
import random def hangman(): word = random.choice([ "pugger", "littlepugger", "tiger", "superman", "thor", "pokemon", "avengers", "savewater", "earth", "annable" ]) turns = 10 while turns > 0: print("guess the word:", "-" * len(word)) guess = input() if guess =...
256e512e252e02cb2d4648c8056477a9b35e968d
teamneem/projecteuler
/euler2.py
489
4
4
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued term...
a3f797e5bd75d6c2c556a4b6dea813ec773740a8
droy78/Leetcode
/63.UniquePaths2.py
2,953
3.703125
4
class Solution(object): #You can reach any cell either from the cell above it and to its left. However, if the cell has #a value 1 that is a blocked cell. Similar to problem no. 62-Unique paths, we create another grid #called table where each cell will hold the no. of ways of reaching it. If the obstablegri...
c894619a7072dbe1f8234d572fae0f14c8c4f347
sauravsingh243/IISc-LAP-Coding-Assignment
/solution.py
1,343
3.890625
4
import random class Solution: def __init__(self): pass def MontyHall(self, N): ans = [0.0, 0.0, 0.0, 0] # Write your code here. Please do not change the return statement. # Update ans[0], ans[1], ans[2] and ans[3] as mentioned in the question. numberOfDoors = 3 for i in range(0,N): ...
c23321e9ee8c8541b0d4dc662288167806a2aeae
GeuberLucas/linguagem_python
/python/classes/Alunos.py
1,809
3.890625
4
class Alunos(): nome=None prova1=None prova2=None trabalho=None matricula=None nota_max_prova1=None nota_max_prova2=None peso_trabalho=None situacao=None nota_max_trab=None nota=None nota_max=None def __init__(self,nota_max_prova1,nota_max_prova2,nota_max_trab,peso_t...
49680d296d916bb5ca7cf7dfc188b5e564c76c5b
GeuberLucas/linguagem_python
/python/herança/exec1_her/Aluno.py
558
3.765625
4
from Pessoa import Pessoa class Aluno (Pessoa): matricula: int = None curso = None def setmat(self): self.matricula = int(input('insira a matricula: ')) def getmat(self): return self.matricula def setcurso(self): self.curso=input('insira o curso do aluno: ') def get...
33c991eada4d781694798864dbd5c287eb751c1e
AvaniVerma/Python-codes
/profanity_editor.py
692
3.71875
4
import urllib def read_text(): #Give the absolute path of the file you want to check for profanity as input for open input_file = open("C:\Users\Avani\Desktop\Python udacity\Input_for_profanity_editor.txt") input_text = input_file.read() #print(input_text) input_file.close() profanity_check(inp...
4768933db52051acade495c26dd96e9e185dc458
ajlongcoy21/StoreInventory
/product.py
3,580
3.59375
4
import datetime from peewee import * # Define Product db = SqliteDatabase('inventory.db') # Define Product class Product(Model): product_id = PrimaryKeyField() product_name = CharField(max_length=255, unique=True) product_qty = IntegerField(default=0) product_price = IntegerField(default=0) dat...
75ac11613e8843d21d34d5ab3f1388780051d032
LegendKrazy/Learning
/Project Euler/pe6.py
772
3.625
4
# Project_Euler_Problem_6 # The sum of the squares of the first ten natural numbers is, # 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and # the squar...
ada7d3aa25694537e9dcf3ca68d28333697e99b7
archanasheshadri/Python-coding-practice
/queueclass.py
1,481
4.21875
4
class Queue(object): """A Queue is a set of integers The value is represented by a list of ints, self.vals. Each int in the set occurs in self.vals exactly once.""" def __init__(self): """Create an empty set of integers""" self.vals = [] def insert(self, e): """Assumes e is...
98615a7a5289609427243b88b0bd1821f020530c
archanasheshadri/Python-coding-practice
/alphabetsub.py
2,176
4.3125
4
#author Archana ''' Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbc...
565f18341cb930b461515aec81a526098d13f341
archanasheshadri/Python-coding-practice
/squareroot.py
539
3.8125
4
x = 23 epsilon = 0.01 step = 0.1 guess = 0.0 while abs(guess**2-x) >= epsilon: if guess <= x: guess += step else: break if abs(guess**2 - x) >= epsilon: print 'failed' else: print 'succeeded: ' + str(guess) #Second approach--- runs into infinite loop #x = 25 #epsilon = 0.01 #step =...
e16c4918c005be136424c46af4ba19978b2c5aac
konrei/lecture2
/dictionaries.py
89
3.546875
4
ages = {"Samet": 18, "Eren": 21} ages["Ömer"] = 21 ages["Samet"] += 1 print(ages)
f0477b3e615e9ae843a7c89e72f8689c27b0e672
mkrotos/Algorithms
/algorithms/extra/dijkstra_algorithm.py
2,490
3.578125
4
from .graph import * class Road: def __init__(self, weight: float, parents: dict = None, finish=None): self._weight = weight self._parents = parents self._path = self.find_path(parents, finish) @staticmethod def find_path(parents, finish): path = [] node = finish ...
4eb1c05afc2e11b94ad1ac5c2609d0cf82912ae5
mkrotos/Algorithms
/test/test_quicksort.py
546
3.65625
4
from unittest import TestCase from algorithms.quicksort import quicksort class Test(TestCase): def test_single_element_list(self): # given & when actual = quicksort([1]) # then self.assertEqual([1], actual) def test_sort_list(self): # given & when actual = qui...
1bcc8610e5fb62d1ecee7097b9a6720e46568a18
JaeZheng/jianzhi_offer
/07.py
1,199
3.90625
4
""" 题目描述: 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。 n<=39 解决思路: 递归,但是代入公式复杂度是2的n次方,会超时。所以改用数组存储或者是两个临时变量存储,时间换空间 """ # -*- coding:utf-8 -*- # # 递归公式,会超时 # class Solution: # def Fibonacci(self, n): # if n == 0: # return 0 # if n == 1 or n == 2: # return 1 # ...
98e40f016721fed39d1e2518b51fd8aa5472d99c
JaeZheng/jianzhi_offer
/25.py
1,324
3.59375
4
""" 题目描述 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点), 返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) 解决思路: 用一个另外的字典来储存对应关系 """ # -*- coding:utf-8 -*- class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # 返回 Ra...
0f253e5c5f347c7bdffef7ffb44801947f58b268
JaeZheng/jianzhi_offer
/62.py
768
3.75
4
""" 题目描述 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。 """ # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): list = self.inorderTra...
487812a5162d74d0c45558084ee907922b0af91d
JaeZheng/jianzhi_offer
/17.py
948
3.671875
4
""" 题目描述: 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) 解决思路: 写一个函数判断A树是否包含B树,再递归调用 """ # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def HasSubtree(self, pRoot1, pRoot2): if pRoot1 == None or pRoot...
d4aea444e400224109d23fb804a0a40a6829e1ae
JaeZheng/jianzhi_offer
/38.py
1,393
3.9375
4
""" 题目描述: 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 解决思路: 第一种:递归。即求孩子节点的最大深度,要么是左孩子,要么是右孩子,那么我们只需要对传入的孩子节点递归调用即可。 第二种:BFS。层次遍历,每经过一层就深度加一。 """ # -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 第一种 # c...
2c018b879e226a3e3dcd068ebc132b7f21978ede
JaeZheng/jianzhi_offer
/11.py
943
3.796875
4
""" 题目描述: 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 解决思路: 第一种:n&(n-1),把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0. 那么一个整数的二进制有多少个1,就可以进行多少次这样的操作。 第二种:转为字符串之后计数 第三种:用1和n的每一位按位与 """ # -*- coding:utf-8 -*- # 第一种 # class Solution: # def NumberOf1(self, n): # # python需要把负数统一转为补码 # n = n & 0xffffffff # count = 0 #...
07dd3c78d5cb418ea7e09268e54331259e033fd5
JaeZheng/jianzhi_offer
/36.py
1,513
3.84375
4
""" 题目描述: 输入两个链表,找出它们的第一个公共结点。 解决思路: 第一种: 把两个链表的结点都入栈,然后同时出栈(即从后向前遍历),出现相同时加入结果数组,结果数组出栈第一个元素即为第一个公共结点。 第二种:两个链表不知谁长谁短,但是相加起来,到最后的公共结点部分长度是相同的,所以遍历时出现null就跳到另一个链表。 """ # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # 第一种 # class Solution: # d...
1a5db3ec15b799f081375487c9923c7e2aca79e3
avinashnarasimha/Python_Training_Trishana
/forDemo2.py
160
4.15625
4
#program to print only odd or even numbers for data in range(0,11,2): print(data) #to print only odd numbers for v in range(1,11,2): print(v)
0c777c1dc256a7f99b24274a16f3c09e9821cbd9
avinashnarasimha/Python_Training_Trishana
/inputDemo2.py
257
4.125
4
#python code to read numbers x =float(input("enter a number")) #reading in string y = float(input("enter a nnumber")) total=int(x)+int(y) #converting float into int. print("sum of %f and %f is %d " %(x,y,int(total))) print("sum of"x,y," is", total)
92d64e2db89df1297cc37d2500b2abfe847a7852
nicolasdonato/reverse-snake.github.io
/test_flipper.py
3,779
3.734375
4
# Takes a test (defined below) and builds the other 7 symmetrical tests # To automate rotation, the test needs to fit within a 10x10. The program checks for this, and can shift the snake to match. snake = [[7, 2], [7, 3], [7, 4], [7, 5], [7, 6], [6, 6], [5, 6], [4, 6], [3, 6], [3, 5], [3, 4], [3, 3], [3, 2], [3, 1], [...
93569b03705db06fa90d626300205d3006540000
JoosikHan/Effective-Python-temp
/files/BetterWay21_ForceKeywordArgument.py
4,047
3.578125
4
# 83쪽. 키워드 전용 인수로 명료성을 강요하자. # 2016/10/27 작성. ####################################################################################### """ 키워드로 인수를 넘기는 방법은 파이썬 함수의 강력한 기능이다. 키워드 인수의 유연성 덕에 코드의 쓰임새를 명료하게 정의할 수 있다. 예를 들어 어떤 숫자를 다른 숫자로 나눈다고 해보자. 어떤 에러를 발생시키지만 예외를 조심해야 한다. 때로는 무한대값을 반환하거나, 0을 반환하고 싶을 수도 있다. """ ...
72a54bca1901187812764ea78385184ea49c2cdc
IdeaLaboratory/MachineLearning
/DataAnalytics/numpyPandas.py
883
3.71875
4
import numpy as np import pandas as pd import os def header(msg): print('-' * 50) print('[ ' + msg + ' ]') # 1. load hard-coded data into a dataframe header("1. load hard-coded data into a df") df = pd.DataFrame( [['Jan',58,42,74,22,2.95], ['Feb',61,45,78,26,3.02], ['Mar',65,48,84,25,2.34], ['Apr',67,50,92,28,1...
03be83d26008d2383aae9605b4c4d974d5c2acda
Chuphay/hadoop
/temp/invertThis.py
320
3.546875
4
#! /usr/bin/env python import sys import re myDict ={} numbers = "\d+" for line in sys.stdin: num,text = line words = text.split() for word in words: try: myDict[word].append(num) except KeyError: myDict[word] = [num] for key in myDict: print key, myDict[key]
71bbe30c6f5c82448da4e0da711819f30a3df535
GanatheVyshnavi/Vyshnavi
/7th.py
74
3.84375
4
s=float(input('enter value of s')) a=4*s print("perimeter of square is",a)
8af4889a4941a1e589d4d2e787a92b220be77d04
GanatheVyshnavi/Vyshnavi
/assignment 9.py
1,902
4.125
4
# program to get smallest and largest numbers from the list n=int(input('Enter number of items in the list: ')) l=[] for i in range(0,n): e=float(input('Enter a number: ')) l.append(e) print("The smallest number in the list is",min(l)) print("The largest number in the list is",max(l)) # program to multiply a...
9e3a5e36ab30a6068ebbb8b580a932031a0a4aa9
maryamkarimi/map-reducer-python
/Part3/reducer2.py
533
3.5625
4
#!/usr/bin/env python """reducer.py""" import sys current_count = 0 # input comes from STDIN for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # convert line (currently a string) to int try: count = int(line) except ValueError: # count was not a ...
d99020c3001a5db3fda8e17699e489b2158fea52
Aug-G/my-awesome-python
/1.Algorithm/Fibonacci.py
458
4.09375
4
#coding:utf-8 # Fibonacci 数列的Python实现 #lambda 实现 fib = lambda n: 1 if n < 2 else fib(n - 1) + fib(n - 2) # decorator 经典实现 def memo(func): cache = {} def wrap(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrap def fib2(i): if i < 2: ...
6776dbe4ba898e4ee5954c2ee812f9c1c4154c6e
saijayadeep1998/Python-math-Module
/math.isnan() Method.py
313
3.515625
4
# Import math Library import math # Check whether some values are NaN print (math.isnan (56)) print (math.isnan (-45.34)) print (math.isnan (+45.34)) print (math.isnan (math.inf)) print (math.isnan (float("nan"))) print (math.isnan (float("inf"))) print (math.isnan (float("-inf"))) print (math.isnan (math.nan))
a50ed11c72d651c6bf9a22d96146e6a55c33877c
saijayadeep1998/Python-math-Module
/math.pow() Method.py
105
3.703125
4
# Import math Library import math # Return the value of 9 raised to the power of 3 print(math.pow(9, 3))
9041fb5afcad7bdb9296029eeb6df521c22c89ab
choi5798/GIT_Practice
/aiya.py
224
3.765625
4
def fact(n): if n == 0: return 1 else: return n * fact(n-1) n = int(input("n 팩토리얼의 값을 구해줍니다. n을 입력하세요 : ")) print("값은 : " + str(fact(n))) print('Hello World!')
b2d384d4f4035f3bcfc9475eb3054341f2379dce
kusumachan/prak_ASD_C
/MODUL-1/MODUL1-L200170078.py
5,192
3.90625
4
"""(NO 1)""" def cetakSiku(x): i=1 while i <= x: print("*"*i) i+=1 cetakSiku(5) """(NO 2)""" def gambarlahPersegiEmpat(x): l=x[1] p=x[0] jarak=l-4 i=1 while i <=l: if i==1: print("@"*l) elif i==l: print("@"*l) ...
0ef13352aea24b617fa14bad27f171be2a4bbf6d
eabasir/algo
/utils/linked_list.py
948
3.546875
4
class SinglyLinkedList(object): def __init__(self, value, next=None): self.value = value self.next = next @staticmethod def from_list(vals: list): head = SinglyLinkedList(vals[0]) current = head for i in vals[1:]: current.next = SinglyLinkedList(i) ...
23e295bd415047317766b5ec865cbde4401e2efc
Ypman/fakeisos
/json_handler.py
578
3.796875
4
import json def get_dict_from_json(json_file): """ Opens given json file and parse it as dictionary :param json_file: filename of *.json in json folder :return: json as dictionary """ with open("json/{}.json".format(json_file)) as file: data = json.load(file) file.close() r...
8e73593897d9ec80d263dc8c46069e556afd14ab
maymashd/webdev2019
/week10/informatics/3)циклы/цикл while/B.py
85
3.609375
4
n=int(input()) b=2 while (b<=n): if (n%b==0): print(b) break
9f8341c763859fafeff033afa40423aab58c26f3
maymashd/webdev2019
/week10/Hackerrank/13)String split and join.py
95
3.734375
4
s=input() a="" for i in s: if i==' ': a+="-" else: a+=i print(a)
dac64dccf4958e8ca42761ff68811aa62309eb70
maymashd/webdev2019
/week10/CodeingBat/logic-1/in1to10.py
173
3.75
4
def f(a,ok): if a>=1 and a<=10: return True elif ok: return True else: return False a=int(input()) b=bool(input()) print(f(a,b))
2bd1c90d6dfef947eb1d1018855642cef83f38ef
maymashd/webdev2019
/week10/informatics/4)массивы/A.py
154
3.625
4
list1=[] n=int(input()) for i in range(0,n): a=int(input()) list1.append(a) for i in range(0,n): if (i%2==0): print(list1[i])
6937044db9946d9195790d0d5a78505ff86718ce
maymashd/webdev2019
/week10/CodeingBat/String-1/make_tags.py
125
3.5
4
def make_tag(tag,words): return '<'+tag+'>'+words+"</"+tag+'>' tag=input() words=input() print(make_tag(tag,words))
b3938edda72cc1ec752a7f9f7195963821e2a2fa
maymashd/webdev2019
/week10/informatics/5)функции/B.py
99
3.6875
4
def power1(a,n): return pow(a,n) a1=int(input()) n1=int(input()) print(power1(a1,n1))
49bfb275f013e755054e63238bbf604e4d506389
jul-star/Stepik_BasicUse
/03/src/ex_3_3_08.py
518
3.5625
4
import sys import re def zz3(_str): """ Выведите строки, содержащие две буквы "z", между которыми ровно три символа. :param _str: :return: True/False """ # pattern = r"(z.{3}z)" # return len(re.findall(pattern, _str)) > 0 pattern = r"z.{3}z" return re.search(pattern, _str) is not ...
0f989ade4b30dcd79223488e82bab1500b723b39
ameykasbe/algorithms
/1. searching_algorithms/1. linear_search.py
250
3.765625
4
def linear_search(arr, key): for i in range(len(arr)): if arr[i] == key: return i return -1 if __name__ == "__main__": arr = [55, -78, 88, 1, -50] print(linear_search(arr, 88)) print(linear_search(arr, 100))
7d303f61d3ed5e7c9bdf558a848d9c2abc4b3c4e
ttknight2020/py
/GaussNaive.py
989
3.9375
4
def GaussNaive(A, b): ''' GaussNaive: naive Gauss elimination x = GaussNaive(A, b): Gauss elimination without pivoting input: A = coefficient matrix b = right hand side vector output: x = soultion vector ''' import numpy as np m, n = A.shape if m != n:...
d564ef3c7a178cc19f45f9ae545bb1b8f0466577
karakumm/puzzle
/puzzle.py
3,086
3.9375
4
''' Playing board for logic puzzle ''' def check_column(board: list, column: int) -> bool: ''' Checks if the column is valid. Returns True if yes, and False if not. >>> check_column([\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 2 ****"...
31531a1fd7549bb2e999d070bd43f9209119c6b2
lbain/exercism-python
/rna-transcription/dna.py
276
3.578125
4
def convert(char): transcription = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'} return transcription[char] def to_rna(test_string): transcribed = map(convert, test_string) return ''.join(transcribed)
1b51258b43ffb71800ceddbed5b6ebcd99632e49
WilbertHo/leetcode
/easy/count_and_say/py/countandsay.py
566
3.78125
4
import re import sys class Solution(object): # @return a string def countAndSay(self, n): num = '1' for i in range(1, n): say = '' while num: digit = num[0] digit_count = len(re.search(r'^{d}+'.format(d=digit), num).group(0)) ...
277454aa808b0394d9ce372c006c1f4e955cda0f
troutstick/magic_words
/get_magic.py
1,854
3.625
4
import create_magic import random seen_words_file = 'seen_magic.txt' def reset(): try: f = open(seen_words_file, 'w') f.close() except FileNotFoundError: f = open(seen_words_file, 'x') f.close() print("List of seen words has been reset!") def get_magic(ignore_seen=False):...
2feecefe98cf4882672213d2713742a0db19c52b
bartoszmaleta/dojos_katas_exercise_bank
/katas_codewars/7 kyu/alphabetical_addition.py
1,258
4.125
4
# Your task is to add up letters to one letter. # The function will be given a variable amount of arguments, each one being a letter to add. # Notes: # Letters will always be lowercase. # Letters can overflow (see second to last example of the description) # If no letters are given, the function should return 'z' # E...
15ee729c38b581fa56f254b1111a4c76336e63fe
yanivr78/MyProjects
/Python/Nested_lists.py
980
4.28125
4
#/usr/bin/python3 fruits = ["Streberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"] vegetables = ["Spinach", "Kale", "Tomatos", "Celery", "Potatoes"] dirty_dosen = [fruits, vegetables] print(dirty_dosen) print(dirty_dosen[1][1]) print(dirty_dosen[0][1]) # Nested List Game row1 = ["⬜️","⬜️",...