blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
724e07386b640ece765abe2b9f53eca3514f7e06
dtran39/Programming_Preparation
/04_Linked_List/Flatten_List_By_Value/Flatten.py
1,000
3.6875
4
''' Problem: - ---------------------------------------------------------------------------------------------------- Examples: 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 ...
b6ce0ac3615fd0c8e59b3c33ea1bf94281867289
dtran39/Programming_Preparation
/01_Arrays/422_Valid_Word_Square/ValidWordSquare.py
1,608
3.890625
4
''' Problem: - Given a sequence of words, check whether it forms a valid word square. A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). ---------------------------------------------------------------------------------------...
50c2f840abfd5d3cf6cb516674029ba3f7f634d0
dtran39/Programming_Preparation
/02_String/125_Validate_Palindrome/ValidatePalindrome.py
1,590
3.796875
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ # Special cases if len(s) < 2: return True # Normal cases: two pointers (only consider letters) start_ptr, end_ptr = 0, len(s) - 1 def validateAlphanumeric(a_c...
01d7acc6de04fa61c4cead6abbc7e79d284b7b0c
dtran39/Programming_Preparation
/04_Linked_List/023_Merge_K_Sorted_List/MergeKSortedLists.py
3,143
4.28125
4
''' Problem: - Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. ---------------------------------------------------------------------------------------------------- Examples: [1,4, 7] [2, 3, 6] [5, 8] -> [1, 2, 3, 4, 5, 6, 7, 8] ----------------------------------------...
0eb64f4cde6f50e898b680a4723e7003b7010e8e
Niwana/DAT171-Exercises
/Exercise 2/main.py
243
3.515625
4
import cardlib cards = [(1, 's'), (2, 'h'), (1, 'h')] def count(l, value): val = 0 for i in l: if i.count(value): print(i.count(value)) val += 1 return val print(cards.count(cards, 'h'))
5a0ebe60224bbff8051745ad9b4bc0a8aa961ea3
ScrypticLabs/iWriter
/src/connect4.py
5,182
3.59375
4
""" An interactive game that is short but fun. This game can be played several times without dedicating too much of your personal time. It doesn’t require very accurate eye tracking, as selecting what column to place the chip in only requires the x-coordinates. In general, the selection of the columns is based on gaz...
ca6a668b1391df0beceb48780bca44975c86f350
Auspicions/WebUI_autotatest
/chenRuiJuan/data1201/yichang.py
612
3.515625
4
# try: # 1/0 # except ZeroDivisionError as e: # print("异常处理----------") # else: # print("正常执行------") # finally: # print("不管你运行是否,我正常执行") # print("继续执行。。。。") # 自定义异常 class ShortException(Exception ): def __init__(self,msg): self.msg=msg class Student: def setld(self,id): if len(i...
9f105abfc8daeb89b41fe16d5d76250b391610dc
Auspicions/WebUI_autotatest
/chenRuiJuan/data1201/exe.py
732
3.53125
4
# 第一种 # f=open("test") # str=f.readlines() # print(str) # f.close() # # 第二种 f=open("test") str=f.read(2) print(str) f.close() # # 第三种 # f=open("test") # while True: # str=f.read(2) # print(str,end="") # if str=="": # break # # 第四种 # f=open("test") # str=f.readlines() # print(str) # 优化 # c=open("F:\\...
51c9e2f3731dfb63c77d04a3ea9849b9419ac7cd
itstep-hw/homework
/snitko.py
102
3.9375
4
a = 1 b = input ("Number") if b == a print ("Its your number") else: print ("Its not your number")
8e4be5bb64ed8447cf98a6d28e769b9ea6e8dea7
Priya2120/back-topic
/que 14.py
1,100
4.0625
4
# Write a Python program to print the following patterns. result_str=""; for row in range(0,7): for column in range(0,7): if (((row == 0 or row == 3 or row == 6) and column > 1 and column < 5) or (column == 1 and (row == 1 or row == 2 or row == 6)) or (column == 5 and (row == 0 or row == 4 or...
baa4a7b4ddd60ad013ade2d628164cb40be55e2e
maitrikpatel2025/100_day_of_python
/Day_11/Day_11_Project_black_jack/Solution(maitrik).py
2,111
4.03125
4
from art import logo import random import sys cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] your_card = [] computer_card = [] your_score = 0 computer_score = 0 def select_card(playing_for): if playing_for == "player": return random_select(your_card, 2) if playing_for == "comput...
c48592bcddb024b655caab622667d37ee9108e94
maitrikpatel2025/100_day_of_python
/Day_29/Day_29_Password_Manger/main.py
4,015
3.5625
4
from tkinter import * from tkinter import messagebox from password import Password # import pandas # # # data_dic = { # # "website": [], # # "email": [], # # "password": [] # # } # ---------------------------- CONSTANTS ------------------------------- # PINK = "#e2979c" RED = "#e7305b" GREEN = "#9bdea...
add42f4ff9d7af792ada3ee859d8f75e5546a30c
maitrikpatel2025/100_day_of_python
/Day_12/Day_12_Guessing_number/solution(maitrik).py
1,038
4.03125
4
from art import logo import random attempts = 0 def game(guess): global attempts attempts -= 1 if number_gussed == guess: return f"You gussed correct" elif number_gussed > guess: return f"Too Low \ntry again" elif guess > number_gussed: return f"Too high \ntry ag...
8f6964cf14d398cfe92c977c8b72450e20f09475
pape1412/abtesting
/abtesting/ABTest.py
5,593
3.640625
4
import math class ABTest(): class TestGroup(): def __init__(self, size=None, mu=None, sigma=None): """ Generic class for evaluating A/B tests Attributes: size (int) Size of the test group mean (float) Mean value of test group ...
9b7d8d3a2e5f836481491d8d1430e252bd45da5e
periakiva/Google-Interview-Dev-Guide-Sols
/maxProfit.py
544
3.5
4
class maxProfit: def __init__(self,sell,buy): self.sell = sell self.buy = buy self.x = 'hello' def buySell(self,prices): mintemp = prices[0] profit = 0 for i in xrange(0,len(prices)): if prices[i] < mintemp: mintemp = prices[i] ...
cf6343253b3dc85c17e0ebb08762a4d92e4da4e0
periakiva/Google-Interview-Dev-Guide-Sols
/bracketBalance.py
412
3.609375
4
class sol: def detectBalance(self,string): hash = {'{':'}','[':']','(':')'} sk =[] if len(string)%2 is not 0: return "NO" for c in string: if c in hash: sk.append(hash[c]) elif sk and c == sk[-1]: sk.pop() ...
394766b2694fa57f8cf48e337d3154f8dff2f677
periakiva/Google-Interview-Dev-Guide-Sols
/withoutstring.py
409
3.59375
4
class sol: def withoutString(self,string,todel): size = len(todel) try: for i in range(0,len(string)): if todel == string[i:i+size]: string = string.replace(string[i:i+size],"") print string except IndexError: r...
63655e7b67d2a36f5c23714b2aa73b1b1353f526
MontePalaSando/programaci-n-de-audio
/Tarea2 2/Valores.py
3,760
3.828125
4
import math class Calc5: def __init__(self, dBFS1,dBFS2): self.dBFS1 = dBFS1 self.dBFS2 = dBFS2 def operar5(self): Max= ((2**16)*(10**(float(self.dBFS1)/20))) Max1= ((2**16)*(10**(float(self.dBFS2)/20))) ...
d8d0773556b19569a3ba68d82f8945a4d7ce7381
GabrielTuratti/Estudos
/PythonExerciciosGuanabara/ex004.py
240
3.59375
4
algo = input('Digite algo') print('Qual é o tipo desse valor ?',type(algo)) print(algo.isdecimal()) print(algo.isnumeric()) print(algo.isalnum()) print(algo.isdigit()) print(algo.isidentifier()) print(algo.islower()) print(algo.isupper())
0c059625a297e986c8b65ebe7e12dc8ec020fb28
GabrielTuratti/Estudos
/PythonExerciciosGuanabara/ex011.py
232
3.875
4
l = float(input("Qual é a largura da parede?:")) a = float(input("Qual é a altura da parede?:")) area = l * a print(" Sua parede tem {} metros quadrados e será necessário {} litros de tinta pra pintar.".format(area, (area/2)))
377606323f31f2814cba04e0b87afe08ab71e688
seunghee6022/SW-Expert-Academy
/Algorithm Problem Solvings/4월9일/숫자추가.py
1,464
3.515625
4
import sys sys.stdin = open('t.txt','r') def printlist(lst,cur,idx): for i in range(idx): cur = cur.next return cur.data def InsertAt(mylist,idx,val): new = Node(val) #빈 리스트일 때, 맨 앞에 삽입 if mylist.head == None: if idx == 0 : mylist.head = mylist.tail = new else ...
762160255407b07332c92638dde07d1179c31669
yz5308/Python_Leetcode
/Algorithm-Easy/270_Closest_Binary_Search_Tree_Value.py
1,285
4.09375
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 closestValue(self, root, target): """ :type root: TreeNode :type target: float :rtype: int ""...
4eb4c1e4f4a312d63c6bcc47599d8f7fc9b86a39
yz5308/Python_Leetcode
/Algorithm-Easy/53_Maximum_Subarray.py
822
3.96875
4
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if max(nums) < 0: return max(nums) local_max, global_max = 0, 0 for x in nums: local_max = max(0, local_max + x) global_max = max(global...
ed2c28ef9d00c4fd4dfe4465b07c123beb802966
yz5308/Python_Leetcode
/Algorithm-Medium/2_Add_Two_Numbers.py
1,635
4
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 == None: ...
303114dd4989f67a0ba1cfb78246a0b9ea350e62
yz5308/Python_Leetcode
/Algorithm-Easy/256_Paint_House.py
1,363
3.734375
4
class Solution: def minCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ if not costs: return 0 n = len(costs) for i in range(1, n): costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]) costs[i][1] += min...
555e54f3e59f5405b343af263899683dc78b74f7
yz5308/Python_Leetcode
/Algorithm-Easy/67_Add_Binary.py
922
3.921875
4
class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ result, carry, val = "", 0, 0 for i in range(max(len(a), len(b))): val = carry if i < len(a): val += int(a[-(i + 1)]) i...
5651499124c41a07112ab3ae02d71076204266eb
yz5308/Python_Leetcode
/Algorithm-Medium/151_Reverse_Words_in_a_String.py
2,029
4.03125
4
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ arr = list(s) self.reverse_string(arr, 0, len(arr)-1) self.reverse_word(arr) word = self.trim_sides(arr) res = self.trim_space(word) return ''.join(res)...
72edb4f61de020da6eda4d59d8b5db912e11c36e
yz5308/Python_Leetcode
/Algorithm-Easy/66_Plus_One.py
1,026
3.828125
4
class Solution: def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ for i in reversed(range(len(digits))): if digits[i] == 9: digits[i] = 0 else: digits[i] += 1 return digits ...
e5511381b340cdd4d2eeda575844c786ad8624c3
yz5308/Python_Leetcode
/Algorithm-Easy/14_Longest_Common_Prefix.py
843
4.0625
4
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" for i in range(len(strs[0])): for string in strs[1:]: if i >= len(string) or string[i] != strs[0][i]: ...
6bc9ecbe6900dab9089fdaa59ee4a91ec9959c65
yz5308/Python_Leetcode
/Algorithm-Easy/234_Palindrome_Linked_List.py
2,011
4.09375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ #判断回文主要是前半部分和后半部分的比较,若能将前半部分压栈,再依次出栈与后半部分比较,则可判断是否回文。 ...
53fb1a65f0bbc4d5aa33b4bc6fb195f0e60a9f18
linsonglnkd/coursera-algo-007
/week_2/QuickSort.py
1,295
3.703125
4
def IsSorted(a) : if len(a) == 1 : return True for i in range(1,len(a)) : if a[i-1] > a[i] : return False return True # a: array, l: left, r:right, howto_pivot: first, last def Partition(a, l, r, howto_pivot) : if howto_pivot == 'last' : swap = a[r] a[r] = a[l] a[l] = swap if howto_pivot == "median-o...
17353ae53003b3de4aabebea4ea9d86ba1fa7bd8
alu-rwa-prog-1/final_project_part1-brenda_josphine
/pythonProject4/main_customer_test.py
1,407
3.84375
4
# Authors: Brenda & Josephine import unittest from main_customer import * ## This are tests for the main customer class class Customer_file(unittest.TestCase): def test_customer_name(self):#this will test the name entered by customer customer_name = Customer('Jane', 2547983456, 'Kenya') ...
8bcc6447fd6de3a3f5d52e0fd7d3bf77693018f2
Kazhuu/movelister
/pythonpath/movelister/format/filter.py
882
4.03125
4
def filterRows(function, rows): """ Filter rows with given filter function and return only rows that returns true. """ return [y for y in rows if function(y)] def groupRows(rows, column): """ Group rows from given column so that they contain the same column data. Consecutive data from ...
8cb0330f88caaf8c95f6889d02176ee68caf4dc4
SeanyDcode/codechallenges
/dailychallenge1014.py
735
3.6875
4
# from dailycodingproblem.com # # Daily Challenge #1014 # Given a start word, an end word, and a dictionary of valid words, find the shortest transformation sequence from start to end such # that only one letter is changed at each step of the sequence, and each transformed word exists in the dictionary. If there is no ...
59c3124cfccc7d2fbb6c9640f8d0ac5a56fa5180
SeanyDcode/codechallenges
/dailychallenge231.py
296
3.953125
4
# from dailycodingproblem.com # # Daily Challenge #231 # Given a string with repeated characters, rearrange the string so that no two adjacent characters are # the same. If this is not possible, return None. # # For example, given "aaabbc", you could return "ababac". Given "aaab", return None.
1a3d9f41e5118d553dd34aae39424ca78b910618
SeanyDcode/codechallenges
/dailychallenge511.py
489
3.578125
4
# from dailycodingproblem.com # # Daily Challenge #511 # You are given an array of integers, where each element represents the maximum number of steps that can be # jumped going forward from that element. Write a function to return the minimum number of jumps you must # take in order to get from the start to the end ...
e26251744a3a2f0f95b4fea5cdb63408c06642b2
SeanyDcode/codechallenges
/completed/dailychallenge1.py
908
3.859375
4
# From dailycodingproblem.com # # Daily Challenge 1 # Given a list of numbers and number k, return whether any two numbers from the list add up to k. # # For example, give [10, 15, 3, 7] and k of 17, return true since 10 + 7 = 17. array = [10, 15, 3, 7] k = 17 def check_total(array, k): length = len(array) ...
c9c4d41230eaba1023c2a059d199d3d7e91d6e5a
SeanyDcode/codechallenges
/dailychallenge378.py
363
3.703125
4
# from dailycodingproblem.com # # Daily Challenge #378 # Write a function that takes in a number, string, list, or dictionary and returns its JSON encoding. It # should also handle nulls. # # For example, given the following input: # # [None, 123, ["a", "b"], {"c":"d"}] # You should return the following, as a string:...
450175f1d39a75e02d548059f15896b2b850014b
SeanyDcode/codechallenges
/dailychallenge367.py
407
4.03125
4
# from dailycodingproblem.com # # Daily Challenge #367 # Given two sorted iterators, merge it into one iterator. # # For example, given these two iterators: # # foo = iter([5, 10, 15]) # bar = iter([3, 8, 9]) # You should be able to do: # # for num in merge_iterators(foo, bar): # print(num) # # 3 # 5 # 8 # 9 # 10 #...
5bf26c722feea6557dee249f2204c3f7933fd491
SeanyDcode/codechallenges
/dailychallenge170.py
742
3.578125
4
# from dailycodingproblem.com # # Daily Challenge #170 # Given a start word, an end word, and a dictionary of valid words, find the shortest transformation sequence # from start to end such that only one letter is changed at each step of the sequence, and each transformed word # exists in the dictionary. If there is ...
df0a90f3e98efa935637e35e5bfeb2812744b4b4
SeanyDcode/codechallenges
/dailychallenge113.py
294
3.921875
4
# from dailycodingproblem.com # # Daily Challenge #113 # Given a string of words delimited by spaces, reverse the words in string. For example, given "hello world here", # return "here world hello" # # Follow-up: given a mutable string representation, can you perform this operation in-place?
02c340c13e1f9fb5421043182ddd5eea0fae1078
archeranimesh/python3_OOPs
/SRC/Chapter_06-Python-Data-Structures/05_default_dict.py
715
3.90625
4
from collections import defaultdict def letter_frequency(sentence): frequencies = {} for letter in sentence: frequency = frequencies.setdefault(letter, 0) frequencies[letter] = frequency + 1 return frequencies def letter_dict_frequency(sentence): frequencies = defaultdict(int) fo...
9c0177ced6c9c03d2e843274fbb0026d2b53b0d3
archeranimesh/python3_OOPs
/SRC/Chapter_05-When-To-Use-Object-Oriented-Programming/06_silly.py
514
3.53125
4
class Silly(object): def _get_silly(self): print("You are getting silly") return self._silly def _set_silly(self, value): print("You are making silly {}".format(value)) self._silly = value def _del_silly(self): print("Whoah, you killed silly") del self._sill...
b4ca091c8aaf1dc5050b596fe47d5b8d6b51c6d2
archeranimesh/python3_OOPs
/SRC/Chapter_02-Objects-In-Python/secretstring.py
759
4.09375
4
class SceretString(object): """A not at all secure way to store a secret string.""" def __init__(self, plain_text, pass_phrase): self.__plain_string = plain_text self.__pass_phrase = pass_phrase def decrypt(self, pass_phrase): """Only Show the string if the pass_phrase is correct "...
7f0d16bff7f1e68e099add10455a79c56732932d
franciscoquinones/Python
/Clase3/ejemplos/ejem1.py
1,048
4.21875
4
# -*- coding: utf-8 -*- """ @author: Francixco """ #Recursion #usar una misma funcion dentro de otra es decir dentro # de l a funcion declarada, volver a llaamr a la mimsa funcion #%% def repetir(TEXTO,n): if n==0: return print (TEXTO) repetir(TEXTO,n-1) palabra=input("In...
63436f1d447c4c8ce8fdc6fb9c33bdc886fde049
franciscoquinones/Python
/Clase2/ACtividades/adivinar.py
729
3.84375
4
# -*- coding: utf-8 -*- """ @author: Francixco """ #%% #%reto import getpass #palabra="manzana" palabra1 = getpass.getpass("Ingrese Palabra: ") palabra1=range(len(palabra)) for i in range(len(palabra)): palabra1[i]="_" print "Adivine la palabra " for n in range(10): val=raw_in...
740635026ebca2f24ed0e13b6fab5ddb2c91ce79
taylorreece/code_competitions
/advent-of-code/2019/03/part1/solution.py
1,026
3.53125
4
#!/usr/bin/env python3 def get_locations(directions): position = [0,0] locations = set() for d in directions: direction = d[0] distance = int(d[1:]) for i in range(distance): if direction == 'L': position[0] -= 1 if direction == 'R': ...
5b5d72111fe06615406d57acd7071db856f419ea
taylorreece/code_competitions
/advent-of-code/2015/08/solution.py
276
3.546875
4
#!/usr/bin/python with open('input.txt', 'r') as f: total_chars = 0 total_string_chars = 0 for line in f: line = line.strip('\n') total_chars = total_chars + len(line) total_string_chars = total_string_chars + len(eval(line)) print total_chars - total_string_chars
025ed49de1742a3357b6d135d92e2f347e42654a
taylorreece/code_competitions
/advent-of-code/2016/01/solution2.py
1,319
3.8125
4
#!/usr/bin/python class Santa: def __init__(self): self.x = 0 self.y = 0 self.d = 0 # North... East is 1, south is 2, west is 3 self.history = [(0,0)] def move(self, movement): direction = movement[0] distance = int(movement[1:]) if direction == 'R': self.d = (self.d + 1) % 4 if direction == 'L': ...
b875ba83033e0e97b58a81bbc370ca415ade63af
taylorreece/code_competitions
/facebook-hacker-cup/2017/qualification/1/solution.py
1,018
3.59375
4
#!/usr/bin/env python3 import os # Deals with printing to stdout, and to a file class P: def __init__(self): if os.path.exists('output.txt'): os.unlink('output.txt') def out(self, s): print(s) with open('output.txt', 'a') as f: f.write('{}\n'.format(s)) p = P() ...
ed9dd87ee7a09797985898598a1ef2fc0e680684
taylorreece/code_competitions
/advent-of-code/2016/07/solution1.py
454
3.71875
4
#!/usr/bin/python import re count = 0 reverse_pair = lambda pair: pair[0] == pair[3] and pair[1] == pair[2] and pair[0] != pair[1] def valid(line): for substr in re.findall(r'\[[a-z]*\]', line): for i in range(len(substr)-4): if reverse_pair(substr[i:i+4]): return False for i in range(len(line)-4): if ...
c3df8e684f3b5984d49292cf7195379c6a94a005
hsiangawang/Computer-Security-2019Fall
/Crypto/sol_3.1.2.1.py
618
3.6875
4
import sys if __name__ == '__main__': ciphertext_file = sys.argv[1] key_file = sys.argv[2] output_file = sys.argv[3] with open(sys.argv[2]) as key_file: line = key_file.read().strip() decode_dict = {c: chr(ord('A') + i) for i, c in enumerate(line)} with open(ciphertext_file) as cipher_file: line =...
97d2f4f26ab32c8fdee4469f2d99fc2936560970
yamasy1549/nlp100
/python/3/22.py
208
3.53125
4
import re from functions3 import * article = gzip2dic()["イギリス"] categories = re.findall(r"\[{2}Category:(.*?)(?:\|.*)*\]{2}", article) if categories: for category in categories: print(category)
9370004c9a639765db0c6a0176ff1b4f49c81a58
yamasy1549/nlp100
/python/1/08.py
221
3.734375
4
def cipher_char(char): return chr(219 - ord(char)) if char.islower() else char def cipher(s): return ''.join(map(cipher_char, s)) s = input() print(cipher(s)) print(cipher(cipher(s))) # tr A-Za-z N-ZA-Mn-za-m
02a46063961e8d43ae9400f5235f0837b6cd7b78
jerryxcoke/python-learning
/4/04.distinct.py
434
3.640625
4
def isInList(listem, elem) : j = 0 while j < len(listem) and elem != listem.keys()[j]: j = j + 1 return j < len(listem) animalWeights = {'fluffy': 425, 'dogee': 3452, 'sanyi': 2732, "csillag":113854} myAnimals = list(['fluffy', 'sanyi']) results = [] counter = 0 for animal in animalWeights: i...
ff4a5e2ede0270ac8184e403792a30c6c44f02d1
jerryxcoke/python-learning
/2/homework.py
202
3.84375
4
import math inputNumber = input('give me a number: ') number = int(inputNumber) toNumber = math.floor(int(number)/2+1) for value in range(2,toNumber): if number % value == 0: print(value)
ac71b3b880db3d570fbfe90a609c59e5b310c4a0
zifeiyu0531/LeetCode_Python
/15. 加一.py
729
3.609375
4
# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 # 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。 # 你可以假设除了整数 0 之外,这个整数不会以零开头。 # 示例 1: # 输入: [1,2,3] # 输出: [1,2,4] # 解释: 输入数组表示数字 123。 # 示例 2: # 输入: [4,3,2,1] # 输出: [4,3,2,2] # 解释: 输入数组表示数字 4321。 class Solution: def plusOne(self, digits: List[int]) -> List[int]: if digits[-1] < 9: ...
2f0b3cdcacdc58e1f4ec2e35873ee18f8b69e6fb
zifeiyu0531/LeetCode_Python
/排序算法/1插入排序.py
585
4.09375
4
# 直接插入排序 # 把待排序的记录按其关键码值的大小逐个插入到一个已经排好序的有序序列中,直到所有的记录插入完为止,得到一个新的有序序列。 def straight_insertion_sort(nums: list): for i in range(1, len(nums)): temp = nums[i] j = i - 1 while j >= 0 and temp < nums[j]: nums[j + 1] = nums[j] j = j - 1 nums[j + 1] = temp def mai...
7b3b822a231cbd788eee940f945986f8f83154ae
zifeiyu0531/LeetCode_Python
/40. 求众数.py
685
3.609375
4
# 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 # 你可以假设数组是非空的,并且给定的数组总是存在众数。 # 示例 1: # 输入: [3,2,3] # 输出: 3 # 示例 2: # 输入: [2,2,1,1,1,2,2] # 输出: 2 class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ dicts = {} for ...
a9ee8511d0457a43fdbb6802b02da130cb9281d6
zifeiyu0531/LeetCode_Python
/72. 反转字符串中的单词 III.py
712
3.921875
4
# 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 # 示例 1: # 输入: "Let's take LeetCode contest" # 输出: "s'teL ekat edoCteeL tsetnoc"  # 注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ temp = '' tar...
fdb02b36004d9f8dce1bc9cb4e3b96e7c91aca6a
zifeiyu0531/LeetCode_Python
/71. 按奇偶排序数组.py
701
3.8125
4
# 给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。 # 你可以返回满足此条件的任何数组作为答案。 #   # 示例: # 输入:[3,1,2,4] # 输出:[2,4,3,1] # 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。 #   # 提示: # 1 <= A.length <= 5000 # 0 <= A[i] <= 5000 class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] ...
9971df442a9db1a355f81c3f7e2cd6ba78851e31
cp4011/Algorithms
/Course/Homework_3/6_分治法解最近对问题.py
6,621
4.15625
4
'''分治法解最近对问题 Description 最近对问题:使用分治算法解决最近对问题。 Input 第一行为测试用例个数。后面每一行表示一个用例,一个用例为一些平面上点的集合,点与点之间用逗号隔开,一个点的两个坐标用空格隔开。坐标值都是正数。 Output 对每一个用例输出两个距离最近的点(坐标使用空格隔开),用逗号隔开,先按照第一个坐标大小排列,再按照第二个坐标大小排列。如果有多个解,则按照每个解的第一个点的坐标排序,连续输出多个解,用逗号隔开。 Sample Input 1 1 1 1,2 2,3 3,4 4,5 5,1.5 1.5 Sample Output 1 1 1,1.5 1.5,1.5 1.5,2 2 ''' ""...
8f7762995c9bbf26e48b3d5c74a2f50afa0b35a0
cp4011/Algorithms
/LeetCode/链表/19_删除链表的倒数第N个节点.py
1,401
3.703125
4
"""给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 示例: 给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5. 说明:给定的 n 保证是有效的。 进阶: 你能尝试使用一趟扫描实现吗? """ '''一次遍历(双指针法、快慢指针) 1. 添加虚拟头结点方便删除第一个节点 2. 找到倒数第n个节点的前一个节点(也就是倒数n+1节点) 指向倒数第n个节点的下一个节点 使用两个指针p,q, q先走n+1步,然后p,q一起走直到q走完整条链表,最后p指向的就是倒数n+1个节点 ''' class ...
b83ec622543f95b521b58bc2048143d3f9b30e31
cp4011/Algorithms
/Tree/12_二叉树的深度.py
1,022
4.03125
4
"""输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。""" class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def TreeDepth(self, pRoot): # 【层次遍历】 if not pRoot: return 0 depth = 0 ...
1d18ea36961f5a346d05bd4daa7662720b724ce6
cp4011/Algorithms
/LeetCode/54_螺旋矩阵.py
708
3.75
4
"""给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5] 输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7] """ class Solution: def spiralOrder(self, matrix): ans = [] while matrix: ...
ac0045ee4abb07cc9076e6352e2eff3d1f05eeb4
cp4011/Algorithms
/剑指offer/28_字符流中的第一个不重复的字符.py
1,249
3.65625
4
"""请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符 是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 输出描述:如果当前字符流没有存在出现一次的字符,返回#字符。 """ ''' 用例:"google" 对应输出应该为:"ggg#ll" 在后台循环调用函数,每次return只输出一个字符char ''' class Solution: def __init__(self): self.s = '' self.dict1 = {} def F...
9e56bbaa8c7c425d5727127638dc7f305765943c
cp4011/Algorithms
/Course/Practice_4(动态规划)/3_按照要求保留数组元素使得和最大.py
2,126
3.9375
4
'''按照要求保留数组元素使得和最大 Description Given an array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence of Ai-1 (if exists) and Ai each from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of selected ...
235848567f794020ed37f1cb77cec45dba426a92
cp4011/Algorithms
/LeetCode/25_k个一组反转链表.py
3,811
3.796875
4
"""给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。 k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。 示例 : 给定这个链表:1->2->3->4->5 当 k = 2 时,应当返回: 2->1->4->3->5 当 k = 3 时,应当返回: 3->2->1->4->5 说明 : 你的算法只能使用常数的额外空间。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 """ class ListNode: def __init__(self, x): self.val = x self.next =...
3783a4f55b15d4be67e0a9370209dd9a3d511615
cp4011/Algorithms
/LeetCode/22_括号生成.py
3,069
3.90625
4
"""给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n = 3,生成结果为: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] """ # 回溯法:时间和空间复杂度都为:O(4^n / n^0.5) '''只有在我们知道序列仍然保持有效时才添加 '(' or ')',而不是像 暴力法 那样每次添加。我们可以通过跟踪到目前为止放置的左括号 和右括号的数目来做到这一点,如果我们还剩一个位置,我们可以开始放一个左括号。 如果它不超过左括号的数量,我们可以放一个右括号。''' class Solutio...
45333860ec32a29d36054b9bfcfb4a9f679dea0c
cp4011/Algorithms
/Tree/7_二叉搜索树的后序遍历序列.py
1,836
3.875
4
"""输入一个整数数组,判断该数组是不是某二叉搜索树BST的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意 两个数字都互不相同。 """ '''BST的后序序列的合法序列是,对于一个序列S,最后一个元素是x (也就是根),如果去掉最后一个元素的序列为T,那么T满足: T可以分成两段,前一段(左子树)小于x,后一段(右子树)大于x,且这两段(子树)都是合法的后序序列。完美的递归定义。 ''' class Solution: def VerifySquenceOfBST(self, sequence): length = len(sequence) if length ...
1f208c8b54d2ef05b8e93daa4555661df3949f57
cp4011/Algorithms
/热题/279_完全平方数.py
2,127
3.734375
4
"""给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 示例 1: 输入: n = 12 输出: 3 解释: 12 = 4 + 4 + 4. 示例 2: 输入: n = 13 输出: 2 解释: 13 = 4 + 9. """ class Solution: # 定正整数n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少 def numSquares(self, n): # BFS """例如的13,我们要前往0,我们的第一步有两...
31daed8fd85e989400142afed205c995e3efc302
cp4011/Algorithms
/牛客/18_发巧克力.py
1,872
3.75
4
"""老师购买了与学生数量相同的巧克力,每位同学按照学号顺序依次独自进入他的办公室,他会随机给一定数量的巧克力给进入他办公室 的学生(最少1块,学号靠后的同学可能拿不到巧克力) 小招的学号是1,他第一个进入办公室。他希望从老师那里拿到至少6块巧克力。你帮他算一下他拿到至少6块巧克力的方案数一共是多少 (如果最终方案中,某个学号的同学拿到的巧克力数不一样则认为是不同的方案) 最终的结果可能很大,输出对666666666取模后的结果 输入描述: 一个整数n,代表学生的人数 输出描述: 一个整数按时,代表总方案数对666666666取模后的结果 输入 6 输出 1 输入 8 输出 4 说明:可能的方案有 8 7 1 6 2 6 ...
3b823caf784ff3fb503ce669b26b7ff5f0e1df09
cp4011/Algorithms
/牛客/2_最高分是多少.py
2,667
3.546875
4
"""老师想知道从某某同学当中,分数最高的是多少,现在请你编程模拟老师的询问。当然,老师有时候需要更新某位同学的成绩. 输入描述: 输入包括多组测试数据。 每组输入第一行是两个正整数N和M(0 < N <= 30000,0 < M < 5000),分别代表学生的数目和操作的数目。 学生ID编号从1编到N。 第二行包含N个整数,代表这N个学生的初始成绩,其中第i个数代表ID为i的学生的成绩 接下来又M行,每一行有一个字符C(只取‘Q’或‘U’),和两个正整数A,B,当C为'Q'的时候, 表示这是一条询问操作,他询问ID从A到B (包括A,B)的学生当中,成绩最高的是多少 当C为‘U’的时候,表示这是一条更新操作,要求把ID...
929d9947abf7a53cad28234f43f5cd31b25071ba
cp4011/Algorithms
/Study/哈希算法(高效存储和查找关键字)/4_单词替换(词根).py
2,951
4.1875
4
"""LeetCode 648 在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。 例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。现在,给定一个由许多词根组成的词典和一个句子。 你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。 你需要输出替换之后的句子。 示例 1: 输入: dict(词典) = ["cat", "bat", "rat"] sentence(句子) = "the cattle was rattled by the battery" 输出...
ad860306843f096700be9a63d04b193430a863ef
cp4011/Algorithms
/LeetCode/113_路径总和 II.py
1,012
3.671875
4
"""给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。 说明: 叶子节点是指没有子节点的节点。 示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 返回: [ [5,4,11,2], [5,8,4,5] ] """ def pathSum(root, sum): # 给定一个二叉树和一个目标和,找到所有...
f8be1c227b196dfb29add52ebde63e2aeff9dacf
cp4011/Algorithms
/Course/Homework_3/4_棋盘覆盖问题.py
4,415
3.765625
4
'''棋盘覆盖问题 Description 棋盘覆盖问题:给定一个大小为2^n2^n个小方格的棋盘,其中有一个位置已经被填充,现在要用一个L型(22个小方格组成的大方格中去掉 其中一个小方格)形状去覆盖剩下的小方格。求出覆盖方案,即哪些坐标下的小方格使用同一个L型格子覆盖。注意:坐标从0开始。 左上方的第一个格子坐标为(0,0),第一行第二个坐标为(0,1),第二行第一个为(1,0),以此类推。 Input 输入第一行为测试用例个数,后面每一个用例有两行,第一行为n值和特殊的格子的坐标(用空格隔开),第二行为需要查找其属于同一个L型格子的格子坐标。 Output 输出每一行为一个用例的解,先按照行值从小到大、再按照列值从小到大的顺序...
4de9f57a16ff7a5bb5cd4609c4b61a55cb351d15
cp4011/Algorithms
/Study/回溯算法/3_查找单词问题.py
1,882
3.609375
4
class Solution: def wordSearch(self, board, word): for i in range(len(board)): for j in range(len(board[0])): # 遍历盘面 if self.helper(board, word, i, j): # 调用helper方法 return True return False ...
67e1b447dd052be23c9907add973ca3fa7188a26
cp4011/Algorithms
/Study/最短路径问题/2_弗洛伊德算法Floyd.py
3,386
3.6875
4
""" 时间复杂度:O(n^3) 空间复杂度:O(n^2) 1,从任意一条单边路径开始。所有两点之间的距离是边的权,如果两点之间没有边相连,则权为无穷大。 2,对于每一对顶点 u 和 v,看看是否存在一个顶点 w 使得从 u 到 w 再到 v 比已知的路径更短。如果是更新它。 Floyd算法适用于【多源最短路径】【边权可正可负】,是一种动态规划算法,稠密图效果最佳。此算法简单有效, 由于三重循环结构紧凑,对于稠密图,效率要高于执行|V|次Dijkstra算法,也要高于执行|V|次SPFA算法。 优点:容易理解,可以算出任意两个节点之间的最短距离,代码编写简单。 缺点:【时间复杂度比较高】,不适合计算大量数据...
8d3887ac7e07cd0f89cb674568c107644c39cbfa
cp4011/Algorithms
/LeetCode/123_买卖股票的最佳时机 III.py
2,478
4.03125
4
"""给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 【两笔】 交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例 1: 输入: [3,3,5,0,0,3,1,4] 输出: 6 解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。   随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。 示例 2: 输入: [1,2,3,4,5] 输出: 4 ...
583e703ecf2d031a2e2be884fa3dd03dab890e52
cp4011/Algorithms
/LeetCode/55_跳跃游戏.py
1,015
3.703125
4
"""给定一个非负整数数组,你最初位于数组的第一个位置。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个位置。 示例 1: 输入: [2,3,1,1,4] 输出: true 解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。 示例 2: 输入: [3,2,1,0,4] 输出: false 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。 """ class Solution: def canJump(self, nums): n = len(nums) ...
c04c52379639f0415af8b8e509320f0e24acee68
cp4011/Algorithms
/LeetCode/98_验证二叉搜索树.py
1,397
3.671875
4
"""给定一个二叉树,判断其是否是一个有效的二叉搜索树。假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1: 输入: 2 / \ 1 3 输出: true 示例 2: 输入: 5 / \ 1 4 / \ 3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4 。 """ # class TreeNode: # 给定一个二叉树,判断其是...
90278cd2d31669f22228e45fe9b28c5896e6a6e9
cp4011/Algorithms
/LeetCode/61_旋转链表.py
1,392
3.53125
4
"""给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL 示例 2: 输入: 0->1->2->NULL, k = 4 输出: 2->0->1->NULL 解释: 向右旋转 1 步: 2->0->1->NULL 向右旋转 2 步: 1->2->0->NULL 向右旋转 3 步: 0->1->2->NULL 向右旋转 4 步: 2->0->1->NULL ""...
d0c5470e9a9e7b3a45ee5035f3ce7c83e36cde0c
cp4011/Algorithms
/热题/146_LRU缓存机制.py
2,517
4.15625
4
"""运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前 删除最近最少使用的数据值,从而为新的数据值留出空间。 进阶: 你是否可以在 O(1) 时间复杂度内完成这两种操作? 示例: LRUCache cache = new LRUCache( 2 /* 缓存容量 */ ); cache.put(1, 1); ...
70f35e5ffbcbeeb5ff8036f003533aa041af1933
cp4011/Algorithms
/LeetCode/10_正则表达式匹配.py
2,350
3.96875
4
"""给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 说明: s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。 示例 1: 输入: s = "aa" p = "a" 输出: false 解释: "a" 无法匹配 "aa" 整个字符串。 示例 2: 输入: s = "aa" p = "a*" 输出: true 解释: '*' 代表可匹配零个或多个前面的元素, 即可以匹配 'a' 。因此, 重复 ...
8e9d51f9ead9a5c54208410ba588e69839e434e2
cp4011/Algorithms
/Course/Homework_2/5_冒泡排序.py
1,971
3.9375
4
'''冒泡排序 Description 实现冒泡排序。 Input 输入的每一行表示一个元素为正整数的数组,所有值用空格隔开,第一个值为数值长度,其余为数组元素值。 Output 输出的每一行为排序结果,用空格隔开,末尾不要空格。 Sample Input 1 13 24 3 56 34 3 78 12 29 49 84 51 9 100 Sample Output 1 3 3 9 12 24 29 34 49 51 56 78 84 100 ''' try: while True: def bubble_sort(array): for i in range(len(array)...
895891e2ffce25982614a9cc4db5b27052c7533b
cp4011/Algorithms
/Study/深度优先遍历算法/2_二叉树中的最大路径和.py
2,754
3.765625
4
"""LeetCode 124 给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。 示例 1: 输入: [1,2,3] 1 / \ 2 3 输出: 6 示例 2: 输入: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 输出: 42 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): ...
6c8d2b1f96e5041616d977cad36b5cc00bd46eb4
cp4011/Algorithms
/Interview_problem/图问题/广度优先遍历图.py
7,777
3.671875
4
'''广度优先遍历图 Description 按照给定的起始顶点广度优先遍历图,每一次通过字母顺序选择顶点查找下一层邻接点,打印遍历顺序。 Input 输入第一行为测试用例个数,后面每一个用例用多行表示,用例第一行是节点个数n和开始顶点,用空格隔开,后面n+1行为图的邻接矩阵,其中第一行为节点名称。值之间使用空格隔开。 Output 输出遍历顺序,用空格隔开 Sample Input 1 1 4 a a b c d a 0 1 1 0 b 1 0 1 0 c 1 1 0 1 d 0 0 1 0 Sample Output 1 a b c d ''' # 方法1 class Graph(object): def __ini...
125284539350bd9d5f84895d77b5ee202cc947e2
cp4011/Algorithms
/Course/Practice_5(贪心算法)/1_管道网络.py
2,237
3.984375
4
"""管道网络 Description Every house in the colony has at most one pipe going into it and at most one pipe going out of it. Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no ou...
c8442c95ddeee52f35eb1ec9756a20f0e7d05ba1
cp4011/Algorithms
/牛客/10_走棋盘.py
2,677
3.734375
4
"""机器人走方格I 有一个XxY的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角。请设计一个算法,计算机器人有多少种走法。 给定两个正整数int x,int y,请返回机器人的走法数目。保证x+y小于等于12。 测试样例: 2,2 返回:2 """ # 递归 def countWays(x, y): if x == 1 or y == 1: # 既然是递归,再考虑退出条件:当整个矩阵只有一行 或 一列的时候只有一种走法 return 1 else: return countWays(x-1, y) + countWays(x, y-1) # ...
b258c7894386e276703b8b711840edba1d52a9b9
cp4011/Algorithms
/LeetCode/动态规划/9_击鼓传花.py
2,610
3.5
4
"""游戏规则是这样的:n个同学坐着围成一个圆圈,指定一个同学手里拿着一束花,主持人在旁边背对着大家开始击鼓,鼓声开始之后 拿着花的同学开始传花,每个同学都可以把花传给自己左右的两个同学中的一个(左右任意),当主持人停止击鼓时,传花停止,此时, 正拿着花没传出去的那个同学就要给大家表演一个节目。 聪明的小赛提出一个有趣的问题:有多少种不同的方法可以使得从小赛手里开始传的花,传了m次以后,又回到小赛手里。对于传递的 方法当且仅当这两种方法中,接到花的同学按接球顺序组成的序列是不同的,才视作两种传花的方法不同。比如有3个同学1号、2号、3号, 并假设小赛为1号,花传了3次回到小赛手里的方式有1->2->3->1和1->3->2->1,共...
5e0c014b11cfe071821872c236a4f007d34bc0c2
cp4011/Algorithms
/LeetCode/62_不同路径.py
999
3.6875
4
"""一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 说明:m 和 n 的值均不超过 100。 示例 1: 输入: m = 3, n = 2 输出: 3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -> 向右 -> 向下 2. 向右 -> 向下 -> 向右 3. 向下 -> 向右 -> 向右 示例 2: 输入: m = 7, n = 3 输出: 28 """ class Solution: def uniquePaths...
bd95eec352ae896d3d024e57b56d013240d48bef
brianspiering/smart-cards
/parse_syllabus.py
2,559
3.609375
4
def parse_syllabus(syllabus_text): '''extract keywords from user syllabus ''' import nltk from nltk.corpus import stopwords import pandas as pd import numpy as np def split_lexicon_keywords(lexicon): lst = [] for keyword in lexicon: try: for token...
f1214e4cb2a18ecf0f6b1623d586dfbe501b4fd6
AMICI-dev/AMICI
/python/sdist/amici/conserved_quantities_rref.py
2,784
3.5
4
"""Find conserved quantities deterministically""" from typing import List, Literal, Optional, Union import numpy as np def rref( mat: np.array, round_ndigits: Optional[Union[Literal[False], int]] = None ) -> np.array: """ Bring matrix ``mat`` to reduced row echelon form see https://en.wikipedia.org...
7713ee85ee193360194817b0297785b74b4b3f84
divyam-khandelwal/matrix_eigenvalues
/coproject.py
5,932
3.546875
4
#from bruteforce import bruteforce as br def f(x,coef): #print coef ex = len(coef)#highest exponent power fun = 0 for i in range(ex): ini = 1 for m in range(i):#the first time i==0 so x is multiplied 0 times and so on.. ini *= x #the number of times x is multiplied...
bf63f144ddceac0b75dbfcb1620b8b28f1b970ef
ErikGartner/love-letter
/loveletter/card.py
2,350
3.984375
4
# -*- coding: utf-8 -*- """ Love Letter Card tools Functions and constants to facilitate working with cards, which are represented as integers. """ import numpy as np class Card(): """Static Card class""" noCard = 0 guard = 1 priest = 2 baron = 3 handmaid = 4 prince = 5 king = 6 c...
7e54548659964d172d564373422f1ea780d25374
ZhuoXu-CSE/SocketProgramming
/Server.py
3,961
3.515625
4
import socket import sys import os PORT = 0 BUF_SIZE = 1024 BASE_ADD = "" if len(sys.argv) == 2: PORT = sys.argv[1] print("\n Server is listening on port :", PORT, "\n") else: print("\n Run the program like:\n python3 Server.py <Port number>\n") exit(1) def upload(connection): # Receive filename ...
3dada162b34942be0a3238ec8f04042722839260
ashishgopalhattimare/Python3-Course
/Competitve Codes/list.py
788
3.921875
4
if __name__ == '__main__': result = [] for _ in range(int(input())): statement = input().split(" ") if statement[0] == "insert": result.insert(int(statement[1]), int(statement[2])) elif statement[0] == "print": print (result) ...
66d50c413ab93cae6bfc4cb59587d14fbe9b0f10
ashishgopalhattimare/Python3-Course
/Competitve Codes/swapCase.py
327
4.09375
4
def swap_case(s): word = list(s) for i in range(len(word)): if word[i] == word[i].upper(): word[i] = word[i].lower() else: word[i] = word[i].upper() return "".join(word) if __name__ == '__main__': s = input() result = swap_case(s) print(...
76d3f970beb39d0d8d2eae8ba6cb203af44cc34f
ashishgopalhattimare/Python3-Course
/Competitve Codes/prime_factorization.py
510
3.78125
4
def get_num(arr): # your code here actualNum = 1 for x in arr: actualNum *= x factor = 2 small, large, count = 0, 0, 1 while factor+factor <= actualNum: if actualNum % factor == 0: if small == 0: small = factor large = factor...
c7b88fe94530a49b8d7fb75da28741bcf7ae7269
gitdownagain/HackerRank
/Day_16_Python_Exceptions_String_to_Integer.py
512
4.34375
4
#!/bin/python3 import sys def convert_to_int(data): try: data = int(data) print(data) except: print("Bad String") return data S = input().strip() convert_to_int(S) # Task # Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String. ...