blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
2188d1d163483a69e48b74ba08531f5cdbccfca2
ICESDHR/Bear-and-Pig
/Practice/Interview/12.矩阵中的路径.py
2,107
3.53125
4
# -*- coding:utf-8 -*- # 矩形中是否存在包含某字符串的路径 # TODO 需要好好看看,自己想了好久才想出来一个很麻烦的方案 def hasPath(matrix, rows, cols, path): for i, s in enumerate(matrix): if s==path[0] and visit([(i//cols, i%cols)], matrix, rows, cols, path): return True return False def visit(ans, matrix, rows, cols, path): if len(ans)==len(path): return True i,j = ans[-1] nex = [(ii,jj) for ii,jj in [(i,j-1),(i,j+1),(i-1,j),(i+1,j)] if 0<= ii <rows and 0<= jj <cols and (ii,jj) not in ans and matrix[ii*cols +jj]==path[len(ans)]] return sum([visit(ans+[x], matrix, rows, cols, path) for x in nex]) def HasPath(matrix, rows, cols, path): for i in range(rows): for j in range(cols): if matrix[i*cols+j] == path[0]: if HasChild(matrix, rows, cols, path[1:], [(i, j)]): return True return False def HasChild(matrix, rows, cols, path, flag): if len(path) == 0: return True row,col = flag[-1] if row+1 < rows and matrix[(row+1)*cols+col] == path[0] and (row+1,col) not in flag: if HasChild(matrix, rows, cols, path[1:], flag+[(row+1,col)]): return True if row-1 >= 0 and matrix[(row-1)*cols+col] == path[0] and (row-1,col) not in flag: if HasChild(matrix, rows, cols, path[1:], flag+[(row-1,col)]): return True if col+1 < cols and matrix[row*cols+col+1] == path[0] and (row,col+1) not in flag: if HasChild(matrix, rows, cols, path[1:], flag+[(row,col+1)]): return True if col-1 >= 0 and matrix[row*cols+col-1] == path[0] and (row,col-1) not in flag: if HasChild(matrix, rows, cols, path[1:], flag+[(row,col-1)]): return True return False if __name__ == '__main__': matrix = "ABCEHJIGSFCSLOPQADEEMNOEADIDEJFMVCEIFGGS" rows,cols = 5,8 paths = ["SLHECCEIDEJFGGFIE","ABCB"] for path in paths: if HasPath(matrix, rows, cols, path): print("Bingo") else: print("Sad")
57d704ed878922cca593c1f20db0bfdd48d3253d
ICESDHR/Bear-and-Pig
/Practice/Interview/17.打印从1到最大的n位数.py
279
3.78125
4
# -*- coding:utf-8 -*- # 输入n,打印从1到最大的n位数 def Print(pre,n): if n < 1: if pre > '0': print(int(pre)) return for i in range(10): Print(pre+str(i),n-1) if __name__ == '__main__': test = [3, -1, 0] for n in test: print('n =',n) Print('', n)
987dc44588b92c0db14ca21def89ab5aad3e22d5
ICESDHR/Bear-and-Pig
/Practice/Sort/HeapSort.py
778
4.09375
4
# -*- coding:utf-8 -*- # 本代码为建立大根堆 def HeapAdjust(heap,length,i): min = i if 2*i+1 < length and heap[2*i+1] > heap[min]: min = 2*i+1 if 2*i+2 < length and heap[2*i+2] > heap[min]: min = 2*i+2 if min != i: heap[i],heap[min] = heap[min],heap[i] HeapAdjust(heap,length,min) def HeapSort(heap): # 构建大根堆 for i in range(len(heap)//2-1,-1,-1): HeapAdjust(heap,len(heap),i) # 将根节点取出与最后一位做对调,对前面剩余节点继续进行对调整 for i in range(len(heap)-1,0,-1): heap[0],heap[i] = heap[i],heap[0] HeapAdjust(heap,i,0) return heap if __name__ == '__main__': a = [1, 7, 3, 9, 14, 2, 5, 9, 6, 10] HeapSort(a) print(a)
6e8ac507b80dd1641922f895a1d06bba718065c3
ICESDHR/Bear-and-Pig
/笨蛋为面试做的准备/leetcode/Algorithms and Data Structures/sort/bubble_sort.py
343
4.15625
4
def bubble_sort(lists): if len(lists) <= 1: return lists for i in range(0, len(lists)): for j in range(i + 1, len(lists)): if lists[i] > lists[j]: lists[j], lists[i] = lists[i], lists[j] return lists if __name__ == "__main__": lists = [9, 8, 7, 6, 5] print(bubble_sort(lists))
0ff9201f5970cca2af58757d2d855446994e0335
ICESDHR/Bear-and-Pig
/Practice/Interview/16.数值的整数次方.py
1,054
4.3125
4
# -*- coding:utf-8 -*- # 看似简单,但是情况要考虑周全 def Pow(base,exponent): if exponent == 0: return 1 elif exponent > 0: ans = base for i in range(exponent-1): ans *= base return ans else: if base == 0: return 'Error!' else: ans = base for i in range(-exponent-1): ans *= base return 1/ans # 对算法效率进行优化,采用递归,同时用位运算代替乘除运算及求余运算 # 但是不能处理底数为浮点数的运算 def Pow2(base,exponent): if exponent == 0: return 1 elif exponent == 1: return base elif exponent > 1: ans = Pow2(base, exponent>>1) # 右移代替整除 ans *= ans if exponent & 1 == 1: # 用位运算判断奇偶 ans *= base return ans else: if base == 0: return 'Error!' ans = Pow2(base, (-exponent)) return 1.0/ans if __name__ == '__main__': test = [(2,3),(0,-5),(-2,-3),(0.5,2)] for base,exponent in test: print('base =', base, ',exponent =', exponent) print(Pow(base, exponent), end='\t') print(Pow2(base, exponent))
583808a25f0bed187352495d1e9d4e239a1e989d
ICESDHR/Bear-and-Pig
/Practice/Interview/10-2.青蛙跳台阶问题.py
1,292
4
4
# -*- coding:utf-8 -*- # TODO 难点是发现这是一个Fibonacci问题 def JumpFloor(number): count = [1,2] if number > 2: for i in range(2,number): count.append(count[i-1]+count[i-2]) return count[number-1] # 变态跳台阶问题 青蛙一次可跳无数节台阶 # TODO 不仅可以找出简单的递归规律;还可以变为组合问题,对其进行总结计算 def JumpFloorII(number): count = [1, 2] for i in range(2, number): count.append(2*count[i-1]) return count[number-1] # TODO 还可以用位移操作解决,震惊 def JumpFloorII2(number): return 2**(number-1) # 超变态跳台阶问题 青蛙一次最多可跳指定台阶数 def SuperJumpFloor(number,n): count = [1,2] if number <= n: for i in range(2,number): temp = sum(count) count.append(temp+1) else: for i in range(2,n): temp = sum(count) count.append(temp+1) for i in range(n,number): temp = 0 for j in range(i-n,i): temp += count[j] count.append(temp) return count[number-1] if __name__ == '__main__': print(JumpFloor(3)) print(JumpFloorII(3)) print(JumpFloorII2(3)) print(SuperJumpFloor(5,3))
571400657495936c96d31a67b1bc2afeeeaa1bf6
ICESDHR/Bear-and-Pig
/Practice/Interview/24.反转链表.py
1,016
4.34375
4
# -*- coding:utf-8 -*- class ListNode: def __init__(self,value): self.value = value self.next = None # 没思路 def ReverseList(root): pNode,parent,pHead = root,None,None while pNode: child = pNode.next if child is None: pHead = pNode pNode.next = parent parent = pNode pNode = child return pHead # 递归方法,需要返回两个值 def ReverseList2(root): if root and root.next: pHead,parent = ReverseList2(root.next) parent.next = root root.next = None return pHead,root return root,root def Build(): root = ListNode(0) node1 = ListNode(1) root.next = node1 node2 = ListNode(2) node1.next = node2 node3 = ListNode(3) node2.next = node3 node4 = ListNode(4) node3.next = node4 return root def Print(root): temp = root while temp: print(temp.value) temp = temp.next if __name__ == '__main__': test = [] root = Build() print('The List is:') Print(root) print('After reverse:') Print(ReverseList(root)) # pHead,parent = ReverseList2(root) # Print(pHead)
b432f5b8f81d0f56fdd591415233a374aea94c78
davistardif/ist4-pcp
/old/tandem/dup.py
3,187
4.09375
4
class Dup(object): """ Dup is a binary string that can be duplicated recursively """ def __init__(self, val_in, distance_in): """ seed_in: (string) starting seed for string self.distance: (int) how many mutations/duplications from seed self.val: (string) string after mutating/duplicating string """ assert (type(val_in) == str), "val_in must be string" assert (type(distance_in) == int), "distance_in must be int" self.parent = None self.val = val_in self.distance = distance_in def duplicate(self, i, j): """ i: (int) starting index for substring to duplicate j: (int) ending index for substring to duplicate tandem duplicates a substring of self.val and increases distance by 1 """ assert (type(i) == type(j) == int), "i and j must be int" assert (0 <= i <= j <= len(self.val)), "i and j not in bounds" d = Dup(self.val[:j+1] + self.val[i:j+1] + self.val[j+1:], \ self.distance + 1) d.set_parent(self) return d def set_parent(self, d): """ d: (dup) the string that self was duplicated from (used to get tree of duplications) """ assert (type(d) == Dup), "parent must be of type Dup" self.parent = d def get_family_tree(self): """ returns the path of duplications from the seed string to self """ tree = [self] descendant = self while descendant.parent != None: tree.append(descendant.parent) descendant = descendant.parent return tree[::-1] def __str__(self): """ returns the value of the string and the distance from the seed """ return "(" + self.val + " ; " + str(self.distance) + ")" def generate_duplicates(intermediates, target): """ intermediates = [list of dup] target = (string) the target string this method generates all possible ways to tandem duplicate given intermediates so they can still be tandem duplicated to the target later """ intermediates_out = [] done = True for d in intermediates: for i in range(0, len(d.val)): for j in range(i, len(d.val)): e = d.duplicate(i,j) if (e.val.count("0") <= target.count("0")) and \ (e.val.count("1") <= target.count("1")): intermediates_out.append(e) done = False if e.val == target: return [e], True if not done: return intermediates_out, False else: return intermediates, True def find_distance(seed, target): """ seed (string) a binary string seed target (string) a binary string target Generates all paths from seed to target, and finds the closest one """ seed = Dup(seed, 0) intermediates = [seed] done = False while not done: intermediates, done = generate_duplicates(intermediates, target) closest = intermediates[0] print closest.distance for d in closest.get_family_tree(): print d
492ce186a2dd6508446c900e06806601be40bd39
hemanthkumarbattula/python-tasks
/Python-basics/2-PartD_1.py
153
3.625
4
a_list=list(range(1000,2001)) result_list=[] for item in a_list: if item%7 == 0 and item%5 != 0: result_list.append(item) print(result_list)
a41531f880884df1712ee311a2b41095ffcd1fd5
hemanthkumarbattula/python-tasks
/Python-basics/AssignmentA4_partB.py
1,013
3.640625
4
import nltk def count_words(text): d={} for i in text: if not i in d: d[i] = text.count(i) return d def fraction_dist(numerator_dist,denominator_dist): temp_dict={} for key in denominator_dist.keys(): if key in numerator_dist: temp_dict[key]=numerator_dist[key]/denominator_dist[key] else: temp_dict[key]=0 ''' I am not sure,(unable to find in the question) how to handle words from the denominator distribution that do not occur in the numerator distribution. so just made their ratio zero. ''' for w in sorted(temp_dict, key=temp_dict.get, reverse=False): print(temp_dict[w]," ",w) if __name__ == "__main__": alice_text = nltk.corpus.gutenberg.words('carroll-alice.txt') deno_dist=count_words([x.lower() for x in alice_text[:len(alice_text)//2] if x.isalpha()]) nume_dist=count_words([x.lower() for x in alice_text[len(alice_text)//2:] if x.isalpha()]) fraction_dist(nume_dist,deno_dist)
c6b04d386907dea30e837a546627754edf90c294
ChristianJdeVries/Phycharm
/Week_2/Exercises.py
365
4.09375
4
print(5 % 2) print(12%15) print(0%7) print((14+51)%24) current_time_str = input("What is the time now?") current_time_int = int(current_time_str) waiting_time_str = input("How long do you have to wait?") waiting_time_int = int(waiting_time_str) time_after = (current_time_int+waiting_time_int) % 24 print("After the waiting time, it is", time_after, "O'clock")
c247ba288604b38dafbb692aa49acf8b74ebd353
izdomi/python
/exercise10.py
482
4.25
4
# Take two lists # and write a program that returns a list that contains only the elements that are common between the lists # Make sure your program works on two lists of different sizes. Write this using at least one list comprehension. # Extra: # Randomly generate two lists to test this import random list1 = random.sample(range(1,15), 10) list2 = random.sample(range(1,30), 8) common = [i for i in list1 if i in list2] print(f'list1 = {list1} \nlist2 = {list2}') print(common)
086daed19d3d5115b9be43430c74c52d4cda4e15
izdomi/python
/exercise24.py
1,385
4.375
4
# Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s # print statement. def board_draw(height, width): top = "┌" + "┬".join(["─"*4]*width) + "┐\n" bottom = "└" + "┴".join(["─"*4]*width) + "┘" middle = "├" + "┼".join(["─"*4]*width) + "┤\n" print(top + middle.join( "│" + "│".join(' '.format(x * width + y + 1) for y in range(width)) + "│\n" for x in range(height)) + bottom) print(board_draw(4,3)) def board_draw(height, width): square = 0 print(" --- " * width) for x in range(height): line = "| " for i in range(0, width): line += format(square, '02d') + " | " square += 1 print(line) print(" --- " * width) heightinp= int(input("Enter the height of the board: ")) widthinp= int(input("Enter the width of the board: ")) board_draw(heightinp,widthinp) def drawboard(size): size = int(size) i = 0 top = "--- " middle = "| " top = top * size middle = middle * (size+1) while i < size+1: print(top) if not (i == size): print(middle) i += 1 print(drawboard(4)) a = '---'.join(' ') b = ' '.join('||||') print('\n'.join((a, b, a, b, a, b, a)))
698212d5376c53e07b4c5410dfd77aac16e97bd2
izdomi/python
/exercise5.py
703
4.21875
4
# Take two lists, # and write a program that returns a list that contains only the elements that are common between the lists. # Make sure your program works on two lists of different sizes. # Extras: # Randomly generate two lists to test this # Write this in one line of Python lst1 = [] lst2 = [] num1 = int(input("length of list 1: ")) for i in range(num1): element1 = int(input("Element for list 1: ")) lst1.append(element1) num2 = int(input("length of list 2: ")) for j in range(num2): element2 = int(input("Element for list 2: ")) lst2.append(element2) if num1 < num2: common = [i for i in lst1 if i in lst2] else: common = [j for j in lst2 if j in lst1] print(common)
98750a28db7b40433921a21fdcaa04c3d720df41
ggteixeira/Plural-Generator
/plural-generator.py
1,040
4.03125
4
from desacentuador import desacento palavra = str(input("Digite: \n")) # Letras que formam substantivos plurais em PB: a = ["s"] e = ["s"] i = ["s"] m = ["ns"] n = ["s"] o = ["s"] r = ["es"] s = ["es"] u = ["s"] z = ["es"] ''' Casos especiais: Segundo HUBACK (2017), plurais terminados em "ão" ("avião" / "aviões"), em "-l" ("anel" /"anéis") e em ditongo em "u" ("chapéu"/ "chapéus") constituem um grupo de plurais irregulares em PB. ''' l = ["es", "is"] ão = ["ões"] def plural(palavra): # Letra a: if palavra[-1] == "a": # Talvez dicionários melhores que listas print(f"{palavra}{a[0]}") # Letra s: if palavra[-1] == "s": if palavra[-2] == "í": print(f"{palavra}{s[0]}") elif palavra[-2] == "ê": palavra = desacento(palavra) print(f"{palavra}{s[0]}") else: print(f"{palavra}") plural(palavra) desacento(palavra) acentuadas = ["á", "â", "é", "ê", "í", "ó", "ô", "ú"] vogais = ["a", "a", "e", "e", "i", "o", "o", "u"]
42ab31504a289208aaa7c94f0f3bb77dc25f4bb7
chriswilde/GuiZero
/LED_Button.py
514
3.546875
4
from guizero import App, PushButton import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(3, GPIO.OUT) GPIO.output(3, GPIO.LOW) def light_Switch(): if GPIO.input(3): GPIO.output(3, GPIO.LOW) LED_Control["text"] = "SWITCH LED ON" print("LED is now off") else: GPIO.output(3, GPIO.HIGH) LED_Control["text"] = "SWITCH LED OFF" print("LED is now on") app = App(title = "LED Play") LED_Control = PushButton(app, command = light_Switch, text = "SWITCH LED ON") app.display()
901157751c3e3ece45cc47225bc6fdb046976892
ivanoviicrm/pdf_to_txt_py
/main.py
1,319
3.546875
4
import PyPDF2 from os import listdir def ask_path(): path = input("Introduce CARPETA para pasar TODOS los documentos PDF a TXT:\n") return path def get_files_in_path(path): pdf_files = [] for file in listdir(path): if file.endswith("pdf"): pdf_files.append(file) return pdf_files def create_text_files(path, files): print("Creando los archivos txt...") for file in files: stream = open(path + file, "rb") reader = PyPDF2.PdfFileReader(stream) file_pages = reader.getNumPages() text_file_name = path + file[:-4] + ".txt" # Con [:-4] quito .pdf y le agrego .txt print("Creando archivo ", text_file_name) txt_file = open(text_file_name, "w") for page in range(0, file_pages): page_content = reader.getPage(page).extractText() txt_file.write(page_content + "\n --end page--\n\n") if __name__ == "__main__": path = ask_path() files = get_files_in_path(path) if len(files) > 0: print("Los documentos PDF encontrados en %s son:" %(path)) for file in files: print(file) answer = input("¿Desea pasarlos a TXT? [s / n]: \n") if answer == "s": create_text_files(path, files)
7430632ea4b68e882041666683aac0988146ce6b
luvkrai/learnings
/hash_map_with_List_Node.py
1,135
3.5
4
class Node: def __init__(self,key,value): self.key = key self.value = value class myhash(): def __init__(self): self.store = [None for _ in range(16)] self.size = 16 def get(self,key): index = self._hash(key) if self.store[index] is None: return None else: found = False for item in self.store[index]: if item.key == key: found = True return item.value if not found: return None def put(self,key,value): n = Node(key,value) index = self._hash(key) if self.store[index] is None: self.store[index] = [n] else: added = False for item in self.store[index]: if item.key == key: item.value = value added = True break if not added: self.store[index].append(n) def _hash(self, key): hash = 0 for char in str(key): hash += ord(char) print(hash) return hash % self.size hm = myhash() hm.put("1", "sachin") hm.put("2", "sehwag") hm.put("a","luv") print(hm.get("1")) print(hm.get("2")) print(hm.get("a")) print(hm.get("1")) print(hm.store)
b57c5e402e5a1c8f34536da10f3440825c0033bf
luvkrai/learnings
/multiprocessing_Sync_2.py
600
3.984375
4
#https://www.geeksforgeeks.org/synchronization-pooling-processes-python/ import multiprocessing def add(balance): for i in range(10000): balance.value += 1 def withdraw(balance): for i in range(10000): balance.value -= 1 # This variable is shared between the processes p1 p2 balance = multiprocessing.Value('i',500) print("Starting balance is: {}".format(balance.value)) p1 = multiprocessing.Process(target=add,args=(balance,)) p2 = multiprocessing.Process(target=withdraw,args=(balance,)) p1.start() p2.start() p1.join() p2.join() print("Final balance is: {}".format(balance.value))
dc1c450c70c473c22cc66f1b76c854f113d5aa08
luvkrai/learnings
/second_maximum.py
220
3.71875
4
arr = [1,2,3,4,5,6,7] max1=max2=-1 for i in range(0,len(arr)): if arr[i] > max1: max2 = max1 max1 = arr[i] elif arr[i] < max1 and arr[i] > max2 and arr[i] != max2: max2 = arr[i] print(max2)
adc35b4cad40e5e6ac3788e8ed0696f7858eeabf
luvkrai/learnings
/iterator.py
910
3.96875
4
class my: def __init__(self): self.l = [1,2,3,4,5] self.index = -1 def __iter__(self): # When iter() is called on the object of this class, and iterator is returned return self def __next__(self): self.index+=1 if self.index < len(self.l): return self.l[self.index] else: raise StopIteration o = my() """ NOTE: "for" will automatically/implicitly call iter() on the object so below example is similar to this t = iter(o) for i in t: print(i) and also for i in iter(o): print(i) So basically "for" will make an iterable object(list,tuple,set,dict) an iterator by calling iter() which means the iterable object must support __iter__() and then it just a matter of calling next() next()....and so on until StopIteration is encountered for Lists, dict tuples etc __iter__ and __next__ method is overidden by "for" automatically/implicitly """ for i in o: print(i)
bbe7ebd67d6d3e90ac238ceb47d4446e8905e22c
luvkrai/learnings
/Hourglass.py
681
3.625
4
#https://www.hackerrank.com/challenges/30-2d-arrays/problem A = [[1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 2, 4, 4, 0], [0, 0, 0, 2, 0, 0], [0, 0, 1, 2, 4, 0]] def calculate_hour_glass(A,row_start,row_end,col_start,col_end): t_sum = 0 row=1 for l in range(row_start,row_end): col=1 for m in range(col_start,col_end): if not (row == 2 and col==1) and not (row==2 and col==3): print(A[l][m],end=" ") t_sum+=A[l][m] col+=1 row+=1 print("") return t_sum result = [] for i in range(4): for j in range(4): result.append(calculate_hour_glass(A,i,i+3,j,j+3)) print(max(result))
61494f69e465e8da2c0193823e18f08c0ad0ba59
muyisanshuiliang/python
/leet_code/643. 子数组最大平均数 I.py
1,236
3.6875
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : 643. 子数组最大平均数 I.py @Contact : muyisanshuiliang@hotmail.com @Modify Time @Author @Version ------------ ------- -------- 2021/2/4 12:06 muyisanshuiliang 3.9 @Desciption: --------------------------------------------------------------- 给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数。 示例: 输入:[1,12,-5,-6,50,3], k = 4 输出:12.75 解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75 提示: 1 <= k <= n <= 30,000。 所给数据范围 [-10,000,10,000]。 ''' # import lib from typing import List class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: if not nums or k == 0 or len(nums) == 0: return 0 total = sum(nums[:k]) total_max = total for item_inx in range(k, len(nums)): total = total - nums[item_inx - k] + nums[item_inx] if total > total_max: total_max = total return total_max / k solution = Solution() # print(solution.findMaxAverage([0, 1, 1, 3, 3], k=4)) print(solution.findMaxAverage([0,4,0,3,2],1))
0ddf4a4c5226563201b4ed3de4aba5f3acb0e2d2
muyisanshuiliang/python
/leet_code/24. 两两交换链表中的节点.py
1,227
3.609375
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: # # 中间节点,记录 pre = ListNode() pre.next = temp_head = head while temp_head and temp_head.next : pre.next = temp_head.next temp_head.next = pre.next.next pre.next.next = temp_head if head == temp_head: head = pre.next pre = temp_head temp_head = temp_head.next return head # dummyHead = ListNode(0) # dummyHead.next = head # temp = dummyHead # while temp.next and temp.next.next: # node1 = temp.next # node2 = temp.next.next # temp.next = node2 # node1.next = node2.next # node2.next = node1 # temp = node1 # return dummyHead.next # print(Solution().swapPairs([])) l1 = ListNode(1) l2 = ListNode(2) l1.next = l2 l3 = ListNode(3) l2.next = l3 l4 = ListNode(4) l3.next = l4 l5 = ListNode(5) l4.next = l5 l6 = ListNode(6) l5.next = l6 l7 = ListNode(7) l6.next = l7 print(Solution().swapPairs(l1))
810d32aa878a2f114ee57200d6747d35a4a045e1
muyisanshuiliang/python
/leet_code/217. 存在重复元素.py
558
3.765625
4
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ if not nums: return False length = len(nums) if length == 1: return False nums_dict = {} for item in nums: if nums_dict.get(item, 0) == 1: return True else: nums_dict[item] = 1 return False nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2] solution = Solution() print(solution.containsDuplicate(nums))
ebe72f3cbb58dba2d08cbffbb0eb0766f43d22f7
muyisanshuiliang/python
/leet_code/1356. 根据数字二进制下 1 的数目排序.py
1,070
3.515625
4
from typing import List class Solution: def sortByBits(self, arr: List[int]) -> List[int]: # 原始方法 # 针对每个数字统计1的个数 def count_one(num) -> [int, int]: # 用于统计1的数量 count = 0 temp = num if num == 0: return [num, count] while True: num = num & (num - 1) count += 1 if num == 0: return [temp, count] i = list(map(count_one, arr)) # 先根据1的个数升序,再根据数据本身升序 # sort = sorted(i, key=lambda t: (t[1], t[0])) i.sort(key=lambda t: (t[1], t[0])) # print(i) return [item[0] for item in i] # 骚操作,先根据1的个数升序,再根据数据本身升序 # return sorted(arr, key=lambda x: (bin(x).count('1'), x)) print(Solution().sortByBits([0, 1, 2, 3, 4, 5, 6, 7, 8])) print(Solution().sortByBits([1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1])) print(bin(-256))
c6c19fd1306d112560e1b663ee095fb54d75765f
muyisanshuiliang/python
/leet_code/LCP 01. 猜数字.py
1,326
3.640625
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : LCP 01. 猜数字.py @Contact : muyisanshuiliang@hotmail.com @Modify Time @Author @Version ------------ ------- -------- 2021/3/12 12:22 muyisanshuiliang 3.9 @Description: --------------------------------------------------------------- 小A 和 小B 在玩猜数字。小B 每次从 1, 2, 3 中随机选择一个,小A 每次也从 1, 2, 3 中选择一个猜。他们一共进行三次这个游戏,请返回 小A 猜对了几次? 输入的guess数组为 小A 每次的猜测,answer数组为 小B 每次的选择。guess和answer的长度都等于3。 示例 1: 输入:guess = [1,2,3], answer = [1,2,3] 输出:3 解释:小A 每次都猜对了。 示例 2: 输入:guess = [2,2,3], answer = [3,2,1] 输出:1 解释:小A 只猜对了第二次。 限制: guess 的长度 = 3 answer 的长度 = 3 guess 的元素取值为 {1, 2, 3} 之一。 answer 的元素取值为 {1, 2, 3} 之一。 通过次数70,717提交次数83,902 ''' # import lib from typing import List class Solution: def game(self, guess: List[int], answer: List[int]) -> int: return sum(guess[i] == answer[i] for i in range(len(guess))) solution = Solution() print(solution.game(guess=[1, 2, 3], answer=[1, 2, 3]))
34519d2fe10929981a8d84e2e5a10e81ec5fbb9c
muyisanshuiliang/python
/leet_code/547. 省份数量.py
9,681
3.703125
4
EXTEND = [1].extend([]) class Solution(object): # def findCircleNum(self, isConnected): # """ # :type isConnected: List[List[int]] # :rtype: int # """ # if isConnected is None or len(isConnected) == 0: # return 0 # length = len(isConnected) # neighbor = [] # for i in list(range(length)): # first_neighbor = self.__get_first_neighbor(isConnected=isConnected, index=i, length=length) # neighbor.append(first_neighbor) # print(neighbor) # result = [] # for index in list(range(0, len(neighbor))): # print('==============index = %d=====================' % (index)) # print(neighbor) # if len(neighbor[index]) == 0: # continue # temp = neighbor[index] # neighbor[index] = [] # inner_index = index + 1 # while inner_index < length: # if len(neighbor[inner_index]) == 0: # pass # elif len(set(temp) & set(neighbor[inner_index])) != 0: # temp = set(temp) | set(neighbor[inner_index]) # neighbor[inner_index] = [] # inner_index += 1 # for inner_index in list(range(len(result))): # if len(set(result[inner_index]) & set(temp)) != 0: # result[inner_index] = set(result[inner_index]) | set(temp) # temp = [] # break # print(temp) # print(neighbor) # if len(temp) != 0: # result.append(set(temp)) # print(result) # return len(result) # # def __get_first_neighbor(self, isConnected, index, length): # j = 0 # first_neighbor = set() # while j < length: # if isConnected[index][j] == 1: # first_neighbor.add(j) # j += 1 # return first_neighbor def find(self, p, x): if p[x] != x: p[x] = self.find(p, p[x]) return p[x] def merge(self, p, a, b): p[self.find(p, a)] = self.find(p, b) def findCircleNum(self, isConnected): """ :type isConnected: List[List[int]] :rtype: int """ n = len(isConnected) p = [i for i in range(n + 1)] print(p) for i in range(n): for j in range(i, n): if isConnected[i][j] == 1: self.merge(p, i + 1, j + 1) res = set() for i in range(1, n + 1): res.add(self.find(p, i)) return len(res) def dfs(self, isConnected): neighbor = [] count = 0 is_visited = [False] * len(isConnected) for item_inx in list(range(len(isConnected))): if not is_visited[item_inx]: count += 1 neighbor.append(item_inx) while len(neighbor) != 0: pop = neighbor.pop() # 如果该节点已经进行了查找,则不再进行临接节点的获取 if is_visited[pop]: continue else: # city.append(pop) is_visited[pop] = True # 邻接节点压入栈 neighbor.extend(self.__get_first_neighbor(isConnected, pop)) # print(city) return count def bfs(self, isConnected): neighbor = [] # outer_city = list() count = 0 is_visited = [False] * len(isConnected) for item_inx in list(range(len(isConnected))): if not is_visited[item_inx]: count += 1 neighbor.append(item_inx) city = [] while len(neighbor) != 0: pop = neighbor.pop(0) # 如果该节点已经进行了查找,则不再进行临接节点的获取 # if city.__contains__(pop): if is_visited[pop]: continue else: city.append(pop) is_visited[pop] = True # 邻接节点压入栈 neighbor.extend(self.__get_first_neighbor_head(isConnected, pop)) # print(city) # print(is_visited) # if len(city) != 0: # outer_city.append(city) # print(outer_city) # return len(outer_city) return count def __get_first_neighbor(self, isConnected, index): j = len(isConnected) - 1 first_neighbor = [] while j >= 0: if isConnected[index][j] == 1 and j != index: first_neighbor.append(j) j -= 1 return first_neighbor def __get_first_neighbor_head(self, isConnected, index): first_neighbor = [] for item in list(range(len(isConnected))): if isConnected[index][item] == 1 and item != index: first_neighbor.append(item) return first_neighbor isConnected = [ # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], # 1 [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 2 [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 3 [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], # 4 [0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], # 5 [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0], # 6 [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], # 7 [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], # 8 [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0], # 9 [0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], # 10 [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0], # 11 [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], # 12 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # 13 [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], # 14 [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # 15 ] def dfs(isConnected): # 获取当前节点的邻居节点 def _get_first_neighbor(isConnected, cur_point): j = len(isConnected) - 1 neighbor = [] while j >= 0: if isConnected[cur_point][j] == 1 and cur_point != j: neighbor.append(j) j -= 1 return neighbor result = '' # 存储邻居节点 neighbor_stack = [] # 存储节点的访问状态,默认都是未被访问状态 is_visited = [False] * len(isConnected) for cur_point in range(len(isConnected)): # 如果当前节点已经被访问,则对下一个节点进行访问 if is_visited[cur_point]: continue # 当前节点置为已被访问状态 is_visited[cur_point] = True result = result + str(cur_point) + '------>' # 当前节点的所有邻居节点压入栈中 neighbor_stack.extend(_get_first_neighbor(isConnected, cur_point)) # 如果邻居节点为空,说明当前已经是最后的一个节点,否则依次对灵雎节点进行处理 while neighbor_stack.__len__() != 0: # 获取邻居节点 pop = neighbor_stack.pop() # 如果邻居节点已经被访问,则继续处理下一个邻居节点 if is_visited[pop]: continue else: # 对邻居节点进行遍历 result = result + str(pop) + '------>' # 修改邻居节点的访问状态为已访问 is_visited[pop] = True # 获取邻居节点的邻居节点 neighbor_stack.extend(_get_first_neighbor(isConnected, pop)) return result def bfs(isConnected): # 获取当前节点的邻居节点 def _get_first_neighbor(isConnected, cur_point): j = 0 neighbor = [] while j < len(isConnected): if isConnected[cur_point][j] == 1 and cur_point != j: neighbor.append(j) j += 1 return neighbor result = '' # 存储邻居节点 neighbor_stack = [] # 存储节点的访问状态,默认都是未被访问状态 is_visited = [False] * len(isConnected) for cur_point in range(len(isConnected)): # 如果当前节点已经被访问,则对下一个节点进行访问 if is_visited[cur_point]: continue # 当前节点置为已被访问状态 is_visited[cur_point] = True result = result + str(cur_point) + '------>' # 当前节点的所有邻居节点压入栈中 neighbor_stack.extend(_get_first_neighbor(isConnected, cur_point)) # 如果邻居节点为空,说明当前已经是最后的一个节点,否则依次对灵雎节点进行处理 while neighbor_stack.__len__() != 0: # 获取邻居节点 pop = neighbor_stack.pop(0) # 如果邻居节点已经被访问,则继续处理下一个邻居节点 if is_visited[pop]: continue else: # 对邻居节点进行遍历 result = result + str(pop) + '------>' # 修改邻居节点的访问状态为已访问 is_visited[pop] = True # 获取邻居节点的邻居节点 neighbor_stack.extend(_get_first_neighbor(isConnected, pop)) return result # isConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]] # solution = Solution() # print(solution.findCircleNum(isConnected)) # print(solution.dfs(isConnected)) print("dfs结果:" + dfs(isConnected)) print("dfs结果:" + bfs(isConnected))
7b9a073898d2fcd5854326707e0ce0bd464449e1
muyisanshuiliang/python
/function/param_demo.py
2,612
4.1875
4
# 函数的参数分为形式参数和实际参数,简称形参和实参: # # 形参即在定义函数时,括号内声明的参数。形参本质就是一个变量名,用来接收外部传来的值。 # # 实参即在调用函数时,括号内传入的值,值可以是常量、变量、表达式或三者的组合: # 定义位置形参:name,age,sex,三者都必须被传值,school有默认值 def register(name, age, sex, school='Tsinghua'): print('Name:%s Age:%s Sex:%s School:%s' % (name, age, sex, school)) def foo(x, y, z=3, *args): print(x) print(y) print(z) print(args) return def foo1(x, y, z=3, **args): print(x) print(y) print(z) print(args) return # 用*作为一个分隔符号,号之后的形参称为命名关键字参数。对于这类参数,在函数调用时,必须按照key=value的形式为其传值,且必须被传值 # 另外,如果形参中已经有一个args了,命名关键字参数就不再需要一个单独的*作为分隔符号了 def register1(name, age, *args, sex='male', height): # def register1(name, age, *, sex, height): print('Name:%s Age:%s Sex:%s Height:%s Other:%s' % (name, age, sex, height, args)) x = 1 def outer(): # 若要在函数内修改全局名称空间中名字的值,当值为不可变类型时,则需要用到global关键字 # global x x = 2 def inner(): # 函数名inner属于outer这一层作用域的名字 # 对于嵌套多层的函数,使用nonlocal关键字可以将名字声明为来自外部嵌套函数定义的作用域(非全局) nonlocal x x = 3 print('inner x:%s' % x) inner() print('outer x:%s' % x) print("全局变量修改前 x = %d" % x) outer() print("全局变量修改后 x = %d" % x) # register() # TypeError:缺少3个位置参数 # register(sex='male', name='lili', age=18) # register('lili', sex='male', age=18, school="Peking University") # 正确使用 # 实参也可以是按位置或按关键字的混合使用,但必须保证关键字参数在位置参数后面,且不可以对一个形参重复赋值 # register(name='lili',18,sex='male') #SyntaxError: positional argument follows keyword argument:关键字参数name=‘lili’在位置参数18之前 # register('lili',sex='male',age=18,name='jack') #TypeError: register() got multiple values for argument 'name':形参name被重复赋值 # foo(1, 2, 3, 4, 5, 6, 7) # L = [3, 4, 5] # foo(1, 2, *L) # foo(1, 2, L) # dic = {'a': 1, 'b': 2} # foo1(1, 2, **dic) # register1('lili', 18, height='1.8m')
142ccd55e9c47a386005d77ba332334e6c9d18ab
muyisanshuiliang/python
/leet_code/面试题 17.07. 婴儿名字.py
6,702
3.671875
4
""" 每年,政府都会公布一万个最常见的婴儿名字和它们出现的频率,也就是同名婴儿的数量。有些名字有多种拼法 例如,John 和 Jon 本质上是相同的名字,但被当成了两个名字公布出来。给定两个列表,一个是名字及对应的频率, 另一个是本质相同的名字对。设计一个算法打印出每个真实名字的实际频率。 注意,如果 John 和 Jon 是相同的,并且 Jon 和 Johnny 相同,则 John 与 Johnny 也相同,即它们有传递和对称性。 在结果列表中,选择 字典序最小 的名字作为真实名字。 示例: 输入:names = ["John(15)","Jon(12)","Chris(13)","Kris(4)","Christopher(19)"], synonyms = ["(Jon,John)","(John,Johnny)","(Chris,Kris)","(Chris,Christopher)"] 输出:["John(27)","Chris(36)"] """ import re from typing import List class Solution: def trulyMostPopular(self, names: List[str], synonyms: List[str]) -> List[str]: # names = dict(zip([re.search(r'[a-zA-Z]+', item).group() for item in names], # [int(re.search(r'\d+', item).group()) for item in names])) # print(names) # # synonyms = [item.replace('(', '').replace(',', ' ').replace(')', '').split(' ') for item in synonyms] # print(synonyms) # # result = {} # dict_name = {} # for item_key, item_val in names.items(): # dict_name[item_key] = item_key # print(dict_name) # # def __find_root(key: str) -> str: # while True: # if key == dict_name.get(key): # return key # else: # key = dict_name.get(key) # # for item in synonyms: # if not dict_name.__contains__(item[0]): # dict_name[item[0]] = item[0] # if not dict_name.__contains__(item[1]): # dict_name[item[1]] = item[1] # temp_root = __find_root(item[0]) # temp_val = __find_root(item[1]) # if temp_root >= temp_val: # dict_name[temp_root] = temp_val # else: # dict_name[temp_val] = temp_root # print(dict_name) # # for item_key, item_val in names.items(): # # 获取根名字对应的根 # root = __find_root(item_key) # result[root] = result.get(root, 0) + item_val # # return [item_key + '(' + str(item_val) + ')' for item_key, item_val in result.items()] # 这道题不采用普通并查集class(数组)写是因为父亲数组需要动态变化 # hashmap可以灵活的增加元素 # 这道题容易忽视的corner case是names里面的两个name 通过中间的不曾出现过的name链接起来 # 譬如names里面a:14 d:13 连接关系(a,b)(b,c)(c,d)可以把ad合并 # 但是其他人的代码里都没体现这一点 f, cnt = {}, {} for name in names: n, c = name.split("(") f[n], cnt[n] = n, int(c[:-1]) # 并查集查找同类根 def find(x): if f[x] != x: f[x] = find(f[x]) return f[x] for s in synonyms: name1, name2 = s[1:-1].split(",") # 不存在的话 仍然需要在f和cnt里进行增加 因为连接关系仍有用 if name1 not in f: f[name1] = name1 cnt[name1] = 0 if name2 not in f: f[name2] = name2 cnt[name2] = 0 p1, p2 = find(name1), find(name2) if p1 == p2: # 父亲一样 那么此时什么都不做 continue # 父亲不一样 需要合并 字典序小的作为父亲 freq = cnt[p1] + cnt[p2] fa = min(p1, p2) ch = max(p1, p2) f[ch] = fa cnt[ch] = 0 cnt[fa] = freq ans = {} for k, v in f.items(): if k == v and cnt[k] != 0: ans[k] = cnt[k] return [k + '(' + str(v) + ')' for k, v in ans.items()] # print(Solution().trulyMostPopular(names=["John(15)", "Jon(12)", "Chris(13)", "Kris(4)", "Christopher(19)"], # synonyms=["(Jon,John)", "(John,Johnny)", "(Chris,Kris)", "(Chris,Christopher)"])) names = ["Fcclu(70)", "Ommjh(63)", "Dnsay(60)", "Qbmk(45)", "Unsb(26)", "Gauuk(75)", "Wzyyim(34)", "Bnea(55)", "Kri(71)", "Qnaakk(76)", "Gnplfi(68)", "Hfp(97)", "Qoi(70)", "Ijveol(46)", "Iidh(64)", "Qiy(26)", "Mcnef(59)", "Hvueqc(91)", "Obcbxb(54)", "Dhe(79)", "Jfq(26)", "Uwjsu(41)", "Wfmspz(39)", "Ebov(96)", "Ofl(72)", "Uvkdpn(71)", "Avcp(41)", "Msyr(9)", "Pgfpma(95)", "Vbp(89)", "Koaak(53)", "Qyqifg(85)", "Dwayf(97)", "Oltadg(95)", "Mwwvj(70)", "Uxf(74)", "Qvjp(6)", "Grqrg(81)", "Naf(3)", "Xjjol(62)", "Ibink(32)", "Qxabri(41)", "Ucqh(51)", "Mtz(72)", "Aeax(82)", "Kxutz(5)", "Qweye(15)", "Ard(82)", "Chycnm(4)", "Hcvcgc(97)", "Knpuq(61)", "Yeekgc(11)", "Ntfr(70)", "Lucf(62)", "Uhsg(23)", "Csh(39)", "Txixz(87)", "Kgabb(80)", "Weusps(79)", "Nuq(61)", "Drzsnw(87)", "Xxmsn(98)", "Onnev(77)", "Owh(64)", "Fpaf(46)", "Hvia(6)", "Kufa(95)", "Chhmx(66)", "Avmzs(39)", "Okwuq(96)", "Hrschk(30)", "Ffwni(67)", "Wpagta(25)", "Npilye(14)", "Axwtno(57)", "Qxkjt(31)", "Dwifi(51)", "Kasgmw(95)", "Vgxj(11)", "Nsgbth(26)", "Nzaz(51)", "Owk(87)", "Yjc(94)", "Hljt(21)", "Jvqg(47)", "Alrksy(69)", "Tlv(95)", "Acohsf(86)", "Qejo(60)", "Gbclj(20)", "Nekuam(17)", "Meutux(64)", "Tuvzkd(85)", "Fvkhz(98)", "Rngl(12)", "Gbkq(77)", "Uzgx(65)", "Ghc(15)", "Qsc(48)", "Siv(47)"] synonyms = ["(Gnplfi,Qxabri)", "(Uzgx,Siv)", "(Bnea,Lucf)", "(Qnaakk,Msyr)", "(Grqrg,Gbclj)", "(Uhsg,Qejo)", "(Csh,Wpagta)", "(Xjjol,Lucf)", "(Qoi,Obcbxb)", "(Npilye,Vgxj)", "(Aeax,Ghc)", "(Txixz,Ffwni)", "(Qweye,Qsc)", "(Kri,Tuvzkd)", "(Ommjh,Vbp)", "(Pgfpma,Xxmsn)", "(Uhsg,Csh)", "(Qvjp,Kxutz)", "(Qxkjt,Tlv)", "(Wfmspz,Owk)", "(Dwayf,Chycnm)", "(Iidh,Qvjp)", "(Dnsay,Rngl)", "(Qweye,Tlv)", "(Wzyyim,Kxutz)", "(Hvueqc,Qejo)", "(Tlv,Ghc)", "(Hvia,Fvkhz)", "(Msyr,Owk)", "(Hrschk,Hljt)", "(Owh,Gbclj)", "(Dwifi,Uzgx)", "(Iidh,Fpaf)", "(Iidh,Meutux)", "(Txixz,Ghc)", "(Gbclj,Qsc)", "(Kgabb,Tuvzkd)", "(Uwjsu,Grqrg)", "(Vbp,Dwayf)", "(Xxmsn,Chhmx)", "(Uxf,Uzgx)"] print(Solution().trulyMostPopular(names, synonyms)) for item in synonyms: if item.__contains__('Chycnm') or item.__contains__('Dwayf') or item.__contains__('Vbp'): print(item)
b593a711496277b0d6e07c9737e65be58398bdd1
muyisanshuiliang/python
/leet_code/203. 移除链表元素.py
739
3.59375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: sentinel = ListNode(0) sentinel.next = head prev, curr = sentinel, head while curr: if curr.val == val: prev.next = curr.next else: prev = curr curr = curr.next return sentinel.next l1 = ListNode(1) l2 = ListNode(2) l1.next = l2 l3 = ListNode(3) l2.next = l3 l4 = ListNode(4) l3.next = l4 l5 = ListNode(5) l4.next = l5 l6 = ListNode(6) l5.next = l6 # l7 = ListNode(7) # l6.next = l7 Solution().removeElements(l1, 6)
271be56c8d2ef15d8833c1e73d38bf1277696112
muyisanshuiliang/python
/leet_code/179. 最大数.py
673
3.75
4
import functools from typing import List class Solution: def largestNumber(self, nums: List[int]) -> str: if not nums: return '' class LargerNumKey(str): def sort_key(a, b): return a + b > b + a # nums.sort(key=functools.cmp_to_key(sort_key)) # if nums[0] == 0: # return '0' # # print(nums) # nums = [str(item) for item in nums] # return ''.join(nums) largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey,reverse=True)) return '0' if largest_num[0] == '0' else largest_num print(Solution().largestNumber(nums=[3, 30, 34, 5, 9]))
73b964bcfd79d45c732188ef41e7bb073547a0bc
muyisanshuiliang/python
/leet_code/56. 合并区间.py
1,090
3.609375
4
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if not intervals or len(intervals) == 1: return intervals # 对元素的根据收个元素进行排序 intervals.sort(key=lambda item: item[0]) result = [] pre = None max_index = len(intervals) - 1 for item_inx, item_val in enumerate(intervals): # 第一次对前值赋值 if pre is None: pre = item_val # 如果当前区间的第一个值大于前一区间的尾值,则分开放入列表 elif item_val[0] > pre[1]: result.append(pre) pre = item_val else: # 否则对区间进行合并 pre[1] = item_val[1] if item_val[1] > pre[1] else pre[1] # 最后一次,把最后一个元素追加到结果集中 if item_inx == max_index: result.append(pre) return result print(Solution().merge([[1, 3], [8, 10], [2, 6], [10, 18]]))
94d80b130c10f27a1b8f6c19ec872870a13d0e66
muyisanshuiliang/python
/leet_code/674. 最长连续递增序列.py
1,324
3.671875
4
""" 给定一个未经排序的整数数组,找到最长且连续递增的子序列,并返回该序列的长度。 连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] , 那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。 示例 1: 输入:nums = [1,3,5,4,7] 输出:3 解释:最长连续递增序列是 [1,3,5], 长度为3。 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。 示例 2: 输入:nums = [2,2,2,2,2] 输出:1 解释:最长连续递增序列是 [2], 长度为1。   提示: 0 <= nums.length <= 104 -109 <= nums[i] <= 109 """ from typing import List class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: if len(nums) <= 1: return len(nums) result = temp_result = 1 for item_inx in range(len(nums) - 1): if nums[item_inx + 1] > nums[item_inx]: temp_result += 1 else: result = max(temp_result, result) temp_result = 1 return max(temp_result, result) print(Solution().findLengthOfLCIS(nums=[1, 3, 5, 7])) print(Solution().findLengthOfLCIS(nums=[2, 2, 2, 2, 2]))
01c6bce8f39004fd8285a1db0bca6d8d2fdf10e0
muyisanshuiliang/python
/leet_code/189. 旋转数组.py
1,591
3.59375
4
class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. """ # 1、python技巧 # if nums is None or len(nums) == 0 or k == 0: # return nums # index = 0 # while index < k: # tail = nums.pop() # nums.insert(0, tail) # index += 1 # return nums # 2、借用临时数组 # if nums is None or len(nums) == 0 or k == 0: # return nums # n = len(nums) # # 获取实际移动位置 # k = k % n # generator = (x for x in nums) # temp_array = list(generator) # for index in list(range(n)): # nums[(index + k) % n] = temp_array[index] # return nums # 3、数组翻转 if nums is None or len(nums) == 0 or k == 0: return nums nums.reverse() n = len(nums) start_index = k % n trance_count = int((n - start_index) / 2) x = 0 while x < trance_count: temp = nums[n - x - 1] nums[n - x - 1] = nums[start_index + x] nums[start_index + x] = temp x += 1 x = 0 while x < int(start_index / 2): temp = nums[start_index - x - 1] nums[start_index - x - 1] = nums[x] nums[x] = temp x += 1 return nums nums = [1, 2, 3, 4, 5, 6, 7] k = 1 solution = Solution() print(solution.rotate(nums, k))
ab46aed706af71ae97b65481899722a0c5f96c99
muyisanshuiliang/python
/function/002-FunctionalProgramDemo.py
5,162
4
4
from functools import reduce print("===============函数式编程===============") print("===============1、map函数===============") def power(x): return x * x # map()传入的第一个参数是f,即函数对象本身 list_number = [1, 2, 3, 4, 5] # 结果iterator是一个Iterator,Iterator是惰性序列 iterator = map(power, list_number) # 通过list()函数让它把整个序列都计算出来并返回一个list list_number = list(iterator) print(list_number) # 将列表的所有元素转换成string print(list(map(str, list_number))) print("===============2、reduce函数===============") # reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算 def add(a, b): return a + b def append(a, b): if not isinstance(a, str): a = str(a) if not isinstance(b, str): b = str(b) return a + b def total(a, b): return a * 10 + b def char2num(s): digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return digits[s] list_number = [1, 2, 3, 4, 5] number = reduce(add, list_number) print(number) print(reduce(append, list_number)) print(reduce(total, list_number)) # 字符串转数字 print(reduce(total, map(char2num, "13579"))) print("===============3、filter函数===============") # 和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素 from math import sqrt def odd(c): return c % 2 == 1 def all_in_prime(n): prime_number = [] if n == 1: return prime_number else: list_number = list(range(2, n)) list_number.append(n) prime_number = list(filter(is_prime, list_number)) return prime_number def is_prime(n): # 素数的概念:大于1,只能被自身和1整除的数据为素数 max = int(sqrt(n)) + 1 for x in range(2, max): if n % x == 0: return False return True print(list(range(2, 2))) list_number = [1, 2, 3, 4, 5] # 返回的是一个Iterator,Iterator是惰性序列,需要通过list把整个序列都计算出来并返回一个list print(list(filter(odd, list_number))) print("%s 以内的素数:%s" % (11, all_in_prime(11))) print("===============3、sorted函数===============") # 默认升序,可以通过 reverse=True 控制排序方式为降序 print(sorted([36, 5, -12, 9, -21], reverse=True)) print(sorted([36, 5, -12, 9, -21])) # 可以自定义函数进行排序,如下按照绝对值进行排序 print(sorted([36, 5, -12, 9, -21], key=abs)) print(sorted([36, 5, -12, 9, -21], key=abs, reverse=True)) # 默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面 print("正常排序 %s" % sorted(['bob', 'about', 'Zoo', 'Credit'])) print("逆序排序 %s" % sorted(['bob', 'about', 'Zoo', 'Credit'], reverse=True)) print("忽略大小写 %s" % sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)) def sortedDictValues1(adict): keys = adict.keys() # l = sorted(keys) return [value for key, value in keys] # L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] L = {'Bob': 75, 'Adam': 92, 'Bart': 66, 'Lisa': 88} # print(sortedDictValues1(L)) print("通过key进行升序:%s" % sorted(L.items(), key=lambda item: item[0])) print("通过value进行升序:%s" % sorted(L.items(), key=lambda item: item[1])) print("通过key进行降序:%s" % sorted(L.items(), key=lambda item: item[0], reverse=True)) print("通过value进行降序:%s" % sorted(L.items(), key=lambda item: item[1], reverse=True)) print("===============4、函数作为返回值===============") # 在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量, # 当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中,这种称为“闭包(Closure)”的程序结构拥有极大的威力。 def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum list_number = [1, 2, 3, 4, 5] function = lazy_sum(*list_number) print("function的类型:%s" % type(function)) print("调用function = %s" % function()) # 每次调用都会返回一个新的函数,即使传入相同的参数 another_function = lazy_sum(*list_number) print(function == another_function) print("===============5、装饰器===============") # 在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。 def now(): print('2020-04-21') function = now print("函数名称:%s" % function.__name__) print("函数名称:%s" % now.__name__) # 调用function函数 function() # 函数作为一个参数进行传递 def print_now(fun): fun() # 调用函数 print_now(now)
1633d5677fbf97155489dc3cb2be67eb5a67af4c
muyisanshuiliang/python
/leet_code/976. 三角形的最大周长.py
418
3.8125
4
from typing import List class Solution: def largestPerimeter(self, A: List[int]) -> int: if not A: return 0 A.sort() r_inx = len(A) - 3 while r_inx >= 0: if A[r_inx] + A[r_inx + 1] > A[r_inx + 2]: return sum(A[r_inx:r_inx + 3]) else: r_inx -= 1 return 0 print(Solution().largestPerimeter([3, 6, 2, 3]))
1a0607a83d8a5b4b3a1769f78b62a1383aa8c664
a-rhodes-vcu/Python-Physical-Implementation-of-Databases
/Project3.py
3,907
4.21875
4
import sys import time class Binary_Search_Tree: """Base Class representing a Binary Search Tree Structure""" # Jet fuel can't melt binary trees # class _BST_Node: """Private class for storing linked nodes with values and references to their siblings""" def __init__(self, value): """Node Constructor with 3 attributes""" self._value = value # value being added self._left = None # left sibling node (if val less than parent) self._right = None # right sibling node (if val greater than parent) def __init__(self): """Binary Tree Constructor (creates an empty binary tree)""" self._root = None # Binary tree root def get_root(self): return self._root def insert_element(self, value): """Method to insert an element into the BST""" if self._root is None: # if there is a root in the tree self._root = Binary_Search_Tree._BST_Node(value) # create a new root equal to value else: self._insert_element(value, self._root) # insert an element, calls recursive function def _insert_element(self, value, node): """Private method to Insert elements recursively""" # if node._value == value: # if we come across a value already in the list # raise ValueError if value < node._value: if node._left is not None: # if a left node child node exists return self._insert_element(value, node._left) # call the insert element function again to evaluate next node else: node._left = Binary_Search_Tree._BST_Node(value) # after recursively crawling through the tree add value to left leaf else: if node._right is not None: # if a right node child node exists return self._insert_element(value, node._right) # call the insert element function again to evaluate next node else: node._right = Binary_Search_Tree._BST_Node(value) # after recursively crawling through the tree add value to right leaf def find(self, value): """Return the if value is in tree""" current_node = self._root while current_node is not None: if value == current_node._value: print( end ="True ") return "True" elif value < current_node._value: current_node = current_node._left else: current_node = current_node._right print(end ="False ") return "False" if __name__ == '__main__': P1 = Binary_Search_Tree() size_of_data_array = sys.argv[1] size_of_query_array = sys.argv[2] a = int(size_of_data_array) # cast to int b = int(size_of_query_array) # cast to int Data_array = [0] * a # inilitzing a new array with the length from the user input Query_array = [0] * b #################################### adding values to arrays ################### start = 0 end = 0 while True: for i in range(len(Data_array)): item = int(input()) start = time.clock() P1.insert_element(item) end = time.clock() else: break new_query_array = [] for i in range(len(Query_array)): item = int(input()) new_query_array.append(item) print("Total Prep Time " + "%.2gs" % (end - start)) while True: for i in range(len(new_query_array)): start = time.clock() P1.find(new_query_array[i]) end = time.clock() print( "%.2gs" % (end - start)) else: break
a06b7d3f65cfd52de14c87a537df8178c19e91ae
TheCDC/arcade
/arcade/utils.py
2,252
4.03125
4
import math import random from pymunk import Vec2d def lerp(v1: float, v2: float, u: float) -> float: """linearly interpolate between two values""" return v1 + ((v2 - v1) * u) def vec_lerp(v1: Vec2d, v2: Vec2d, u: float) -> Vec2d: return Vec2d( lerp(v1.x, v2.x, u), lerp(v1.y, v2.y, u) ) def rand_in_rect(bottom_left: Vec2d, width: float, height: float) -> Vec2d: return Vec2d( random.uniform(bottom_left.x, bottom_left.x + width), random.uniform(bottom_left.y, bottom_left.y + height) ) def rand_in_circle(center: Vec2d, radius: float) -> Vec2d: """Generate a point in a circle, or can think of it as a vector pointing a random direction with a random magnitude <= radius Reference: http://stackoverflow.com/a/30564123 Note: This algorithm returns a higher concentration of points around the center of the circle""" # random angle angle = 2 * math.pi * random.random() # random radius r = radius * random.random() # calculating coordinates return Vec2d( r * math.cos(angle) + center.x, r * math.sin(angle) + center.y ) def rand_on_circle(center: Vec2d, radius: float) -> Vec2d: """Note: by passing a random value in for float, you can achieve what rand_in_circle() does""" angle = 2 * math.pi * random.random() return Vec2d( radius * math.cos(angle) + center.x, radius * math.sin(angle) + center.y ) def rand_on_line(pos1: Vec2d, pos2: Vec2d) -> Vec2d: u = random.uniform(0.0, 1.0) return vec_lerp(pos1, pos2, u) def rand_angle_360_deg(): return random.uniform(0.0, 360.0) def rand_angle_spread_deg(angle: float, half_angle_spread: float) -> float: s = random.uniform(-half_angle_spread, half_angle_spread) return angle + s def rand_vec_spread_deg(angle: float, half_angle_spread: float, length: float) -> Vec2d: a = rand_angle_spread_deg(angle, half_angle_spread) v = Vec2d().ones() v.length = length v.angle_degrees = a return v def rand_vec_magnitude(angle: float, lo_magnitude: float, hi_magnitude: float) -> Vec2d: mag = random.uniform(lo_magnitude, hi_magnitude) v = Vec2d().ones() v.length = mag v.angle_degrees = angle return v
cedacc649bba0403d67724a7eefe65007ac84f4d
spiewakm/SuDoKu
/sudoku/AboutGame.py
3,101
4.03125
4
""" Class with game's information """ about = """\ SuDoKu is a simple Sudoku game, developed by Martyna Śpiewak in Python. """ keys = [ ('Up arrow', 'Move cursor up'), ('Down arrow', 'Move cursor down '), ('Right arrow', 'Move cursor right'), ('Left arrow', 'Move cursor left'), ('Backspace/Delete', 'Delete a digit from the cell'), ('Ctrl+C', 'Check the solution'), ('Ctrl+M', "Show the one cell's solution"), ('Ctrl+S', "Show the game's solution"), ('Ctrl+R', 'Restart game'), ('Ctrl+N', 'New game'), ('Ctrl+O', 'Options game'), ('Ctrl+Q', 'Quit'), ('F1', 'About SuDoKu'), ] rules = """\ Each puzzle consists of a 9x9 grid containing given clues in various places. The object is to fill all empty squares so that the numbers 1 to 9 appear exactly once in each row, column and 3x3 box. """ from PyQt4 import QtGui from PyQt4 import QtCore import qdarkstyle class AboutGame(QtGui.QDialog): def __init__(self): super(AboutGame, self).__init__() self.setWindowTitle('About SuDoKu') self.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False)) aboutPage = QtGui.QWidget(self) logo = QtGui.QLabel() pixmap = QtGui.QPixmap('sudoku/sudoku.png') logo.setPixmap(pixmap) aboutLabel = QtGui.QLabel(about) aboutLayout = QtGui.QVBoxLayout() aboutLayout.addSpacing(30) aboutLayout.addWidget(logo, 0, QtCore.Qt.AlignCenter) aboutLayout.addWidget(aboutLabel, 0, QtCore.Qt.AlignCenter) aboutPage.setLayout(aboutLayout) sudoku = QtGui.QLabel() pixmap2 = QtGui.QPixmap('sudoku/sudoku2.png') sudoku.setPixmap(pixmap2) rulePage = QtGui.QWidget(self) ruleLabel = QtGui.QLabel(rules) ruleLayout = QtGui.QVBoxLayout() ruleLayout.addWidget(sudoku, 0, QtCore.Qt.AlignCenter) ruleLayout.addSpacing(30) ruleLayout.addWidget(ruleLabel) keysPage = QtGui.QWidget(self) keysLayout = QtGui.QGridLayout() i = 0 for key, desc in keys: keysLayout.addWidget(QtGui.QLabel(key), i, 0) keysLayout.addWidget(QtGui.QLabel(desc), i, 1) i += 1 keysPage.setLayout(keysLayout) rulePage.setLayout(ruleLayout) tabs = QtGui.QTabWidget(self) tabs.addTab(aboutPage, 'About') tabs.addTab(rulePage, 'Game Rules') tabs.addTab(keysPage, 'Keys') okbutton = QtGui.QPushButton('OK') self.connect(okbutton, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('accept()')) bbox = QtGui.QHBoxLayout() bbox.addStretch() bbox.addWidget(okbutton) bbox.addStretch() layout = QtGui.QVBoxLayout() layout.addWidget(tabs) layout.addLayout(bbox) self.setLayout(layout) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) dialog = AboutGame() dialog.exec_()
3a53ab12f8144942fbfcb56bbb56d407c32bdf3e
autumnalfog/computing-class
/Week 2/a21_input_int.py
345
4.21875
4
def input_int(a, b): x = 0 while x != "": x = input() if x.isdigit(): if int(x) >= a and int(x) <= b: return x print("You should input a number between " + str(a) + " and " + str(b) + "!") print("Try once more or input empty line to cancel input check.")
82e3a0d0c83396db73fada0aec0c57c6d8885104
MatthieuDasnoy/python-developer-roadmap
/Automate the Boring Stuff/Chapter 05 – Dictionaries and Structuring Data/fantasy_game_inventory.py
634
3.75
4
player_inventory = {'gold coin': 42, 'rope': 1} dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def displayInventory(some_dict): items_total = 0 print('Inventory:') for k, v in some_dict.items(): print(v, k) items_total += v print('Total number of items: ' + str(items_total)) def addToIventory(some_dict, some_list): for i in some_list: some_dict.setdefault(i, 0) some_dict[i] += 1 return some_dict player_inventory = addToIventory(player_inventory, dragon_loot) displayInventory(player_inventory)
fe36781d1eb5e83a0019831ed114b6faf242e87c
MatthieuDasnoy/python-developer-roadmap
/Automate the Boring Stuff/Chapter 10 – Debugging/debugging_coin_toss.py
900
3.609375
4
import random, logging logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') logging.debug('Start of program') guess = '' while guess not in ('heads', 'tails'): print('Guess the coin toss! Enter heads or tails: ') guess = input() logging.debug('guess = ' + guess) coin = {0: 'tails', 1: 'heads'} # Correction to BUG 1 toss = coin[random.randint(0, 1)] logging.debug('toss = ' + toss) if toss == guess: # BUG 1: Was comparing int with string . print('You got it!') else: print('Nope! Guess again!') guess = input() # BUG 2: Guess was typed with 3 s characters logging.debug('guess = ' + guess) logging.debug('toss = ' + toss) if toss == guess: print('You got it!') else: print('Nope. You are really bad at this game.')
283bac14f295c0e353eac3d97d435d48520b87fe
Kzarama/LabIA
/01-python/Strassen/strassen.py
1,086
3.578125
4
import numpy as np def strassen(A, B): if type(A) is not np.ndarray or type(B) is not np.ndarray: raise Exception('Inputs are not numpy ndarrays') # if : # raise Exception('Inputs are not bidimensional') # if True: # raise Exception('Matrices are not squared') # if True: # raise Exception('Matrices are not of n power of two') else: print("ok") # n = len(A) # ​ # if n == 2: # return A @ B # ​ # h = n//2 # ​ # A11 = # slice A # A12 = # slice A # A21 = # slice A # A22 = # slice A # B11 = # slice B # B12 = # slice B # B21 = # slice B # B22 = # slice B # ​ # M1 = # call strassen with corresponding matrices # M2 = # call strassen with corresponding matrices # M3 = # call strassen with corresponding matrices # M4 = # call strassen with corresponding matrices # M5 = # call strassen with corresponding matrices # M6 = # call strassen with corresponding matrices # M7 = # call strassen with corresponding matrices # ​ # C = numpy.zeros((n,n)) # # set C values # ​ # return C
b82f8105ecb02e6681e1fcbddc3a5ca6054f3908
Natnaelh/Algorithm-Problems
/Data Structures/Stack.py
1,209
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 14 10:26:32 2020 @author: natnem """ class Stack(object): def __init__(self, stacksize): self.stacksize = stacksize self.array = [0]*stacksize self.size = 0 def isFull(self): return self.size == self.stacksize def isEmpty(self): return self.size == 0 def TopIndex(self): return self.size - 1 def Push(self, item): if self.isFull(): raise Exception("Stack is Full") else: self.size += 1 self.array[self.TopIndex()] = item def Pop(self): if self.isEmpty(): raise Exception('Stack is Empty') else: top = self.array[self.TopIndex()] self.array[self.TopIndex()] = 0 self.size -= 1 return top def Peek(self): if self.isEmpty(): raise Exception("Stack is Empty") else: return self.array[self.TopIndex()] mystack = Stack(10) print(mystack.array) mystack.Push(5) mystack.Push(10) mystack.Push(15) print(mystack.array) print(mystack.Pop()) print(mystack.array)
32aedfa5bf23dffc98aa06e1b7cf028e5e285448
Natnaelh/Algorithm-Problems
/Dynamic Programming/TextJustification.py
907
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 9 23:41:59 2020 @author: natnem """ mytext = 'helo there this' words = mytext.split(" ") n = len(words) memo = {} parent = {} def textjust(i): if i >= n: return 0 elif i in memo: return memo[i] else: bad = float("inf") for j in range(i+1, n+1): newval = textjust(j) + badness(i,j) if newval < bad: bad = newval parent[i] = j print(j,memo) memo[i] = bad return bad def badness(i , j): pagewidth = 10 totalwidth = 0 for chars in words[i:j+1]: totalwidth += len(chars) totalwidth += (j-i) print("tot = "+ str(totalwidth)) if totalwidth > pagewidth: return float('inf') else: return pow(pagewidth - totalwidth,3) print(textjust(0))
dadffe77bb6d8d8f4e1eda4db97cd3d41bec4307
Natnaelh/Algorithm-Problems
/Graph Algorithms/dfs.py
2,235
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 27 13:50:34 2020 @author: natnem """ #class graph(object): # def __init__(self): # self.adj = {"a":["s","z"], "s":["x"],"z":["a"],"x":["d","c"], # "d":["c","f"],"c":["f","v"],"f":["v"],"v":["g"],"n":["m"]} # def itervertices(self): # return self.adj.keys() # def neighbors(self,v): # return self.adj[v] # # #class dfsResult(object): # """Object Oriented way""" # def __init__(self): # self.parent = {} # self.order = [] # #def dfs(g): # results = dfsResult() # for vertex in g.itervertices(): # if vertex not in results.parent: # dfsVisit(g,vertex,results) # return results.parent #def dfsVisit(g,v,results,parent =None): # results.parent[v] = parent # if v in g.adj.keys(): # for n in g.neighbors(v): # if n not in results.parent: # dfsVisit(g,n,results,v) # results.order.append(v) # #g = graph() #print(dfs(g)) #def DfsVisit(Adj , s , parent): # if s in Adj.keys(): # for neighbours in Adj[s]: # if neighbours not in parent: # parent[neighbours] = s # DfsVisit( Adj , neighbours, parent) # return parent #def dfs(V, Adj): # parent = {} # for vertex in V: # if vertex not in parent: # parent[vertex] = None # DfsVisit( Adj, vertex, parent) # return parent # #Adj = {"a":["s","z"], "s":["x"],"z":["a"],"x":["d","c"], # "d":["c","f"],"c":["f","v"],"f":["v"], # "v":["g"], # "n":["m"]} #V = [keys for keys in Adj.keys()] #parent = {"a": None} #print(dfs(V,Adj)) parent = {} def dfsvisit(adj, s): if s in adj.keys(): for v in adj[s]: if v not in parent: parent[v] = s dfsvisit(adj,v) def dfs(adj): order = [] for v in adj.keys(): if v not in parent: parent[v] = None dfsvisit(adj,v) order.append(v) return parent Adj = {"a":["s","z"], "s":["x"],"z":["a"],"x":["d","c"], "d":["c","f"],"c":["f","v"],"f":["v"], "v":["g"], "n":["m"]} print(dfs(Adj))
3ef1f0c470ef47b14c3dbd303edc8adf0078df15
Natnaelh/Algorithm-Problems
/Data Structures/Stack_Two.py
3,902
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 23 12:01:58 2020 @author: natnem """ class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def stacksize(self): return len(self.items) def pop(self): if self.isEmpty(): raise Exception("Stack is Empty") top = self.items.pop() return top def peek(self): return self.items[self.stacksize() - 1] def push(self,item): self.items.append(item) def stack(self): return self.items #mystack = Stack() #mystack.push("cat") #mystack.push("dog") #mystack.push("yay") #print(mystack.stack()) #print(mystack.peek()) #mystack.pop() #mystack.pop() #mystack.pop() #mystack.pop() #print(mystack.stack()) def ReverseString(mystring): #using a stack mystack = Stack() for i in mystring: mystack.push(i) print(mystack.stack()) reverse = '' for k in range(len(mystring)): reverse += mystack.pop() return reverse print(ReverseString("ABCDEF")) def BaseConvertion(dec , base): digits = "0123456789ABCDEF" s = Stack() while dec > 0: rem = dec % base s.push(rem) dec = dec//base print(rem, dec, s.stack()) b = "" while not s.isEmpty(): b += (digits[s.pop()]) return b print(BaseConvertion(233,8)) def ParCheckerGeneral(symbol): mystack = Stack() opens = "({[" closes = ")}]" for i in symbol: if i in "({[": mystack.push(i) print(i) else: print(i) if mystack.isEmpty() and symbol[symbol.index(i):] != "": return False else: top = mystack.pop() if opens.index(top) != closes.index(i): return False if mystack.stack() == []: return True else: return False print(ParCheckerGeneral('[{()}]')) #INPUT THE INFIX EXPRESSION AS A STRING SEPARATED BY SPACES def InfixToPostfix(infixExp): s = Stack() infixList = infixExp.split(" ") OutputList = [] # operator = "*/+-" operand = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" precedence = {"*":3, "/":3 , "+":2 , "-":2, "(":1} for token in infixList: if token in operand: OutputList.append(token) elif token == "(" : s.push(token) elif token == ")" : while not s.isEmpty(): top = s.pop() if top =="(" : break else: OutputList.append(top) else: if s.isEmpty(): s.push(token) else: opr = s.peek() if precedence[opr] >= precedence[token]: OutputList.append(opr) s.pop() s.push(token) else: s.push(token) while not s.isEmpty(): t = s.pop() OutputList.append(t) return "".join(OutputList) INFIX = "( 5 * 2 ) - 2" print(InfixToPostfix(INFIX)) def PostfixEvaluation(infix): result = Stack() postfix = InfixToPostfix(infix) for token in postfix: if token not in "*/+-": result.push(int(token)) else: opr1 = result.pop() opr2 = result.pop() if token == "*": result.push(opr2 * opr1) elif token == "/": result.push(opr2/opr1) elif token == "+": result.push(opr2+opr1) else: result.push(opr2-opr1) return result.peek() print(PostfixEvaluation(INFIX))
ee5d68a33596446738ea4f73f65c43e2efbbf55d
Natnaelh/Algorithm-Problems
/Document Distance/Document DistnaceFirst.py
905
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 18 14:42:39 2019 @author: natnem """ import math D1 = ["the" , "cat" , "was" , "outside"] D2 = ["the" , "cat" , "is" , "outside"] def CountFreq(l): count = {} for word in l: if word in count: count[word] += 1 else: count[word] = 1 return count #print(CountFreq(D1)) def dotProd(l1, l2): freqL1 = CountFreq(l1) freqL2 = CountFreq(l2) Prod = 0 for word in freqL1: if word in freqL2: Prod += freqL1[word] + freqL2[word] return Prod def arcCos(D1,D2): thing = dotProd(D1,D2) / math.sqrt((dotProd(D1,D1)*dotProd(D2,D2))) return math.acos(thing) def main(): print("The First List: \n" , D1) print("The Second List: \n" , D2) print("Distance between them in radian = " ,arcCos(D1 , D2 )) main()
c1e7ce19fac8f6d3ee4e8005d69e054aac8d4f64
Natnaelh/Algorithm-Problems
/Data Structures/DoublyLinkedList.py
2,524
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 27 13:26:06 2020 @author: natnem """ """ IMPLMENTATION OF AN UNSORTED DOUBLY LINKED LIST""" class Node(object): def __init__(self, key): self.key = key self.next = None self.prev = None def getPrev(self): return self.prev def getNext(self): return self.next def getKey(self): return self.key def setPrev(self, newPrev): self.prev = newPrev def setNext(self , newNext): self.next = newNext def setKey(self, newKey): self.key = newKey class DoublyLinked(Node): def __init__(self): self.head = None # self.first = None # self.Last = None def isEmpty(self): return self.head == None def search(self , k): """finds the first element with key k in list L by a simple linear search, returning a pointer to this element. If no object with key k appears in the list, then the procedure returns NIL""" cur = self.head while cur != None and cur.key != k: cur = cur.next if cur == None: raise Exception("Key not Found") else: return cur def insert(self, k): """Given an element k whose key attribute has already been set, the NSERT procedure “splices” k onto the front of the linked list""" newNode = Node(k) newNode.setNext(self.head) if self.head != None: self.head.setPrev(newNode) self.head = newNode # self.first = newNode newNode.setPrev(None) def delete(self, x): """removes an element given its key x from a linked list""" if self.isEmpty(): raise Exception("List is Empty") else: cur = self.search(x) if cur.prev != None: cur.prev.setNext(cur.next) else: self.head = cur.next if cur.next != None: cur.next.setPrev(cur.prev) def __str__(self): L = [] cur = self.head while cur != None: L.append(cur.key) cur = cur.next return str(L) #mydoublelist = DoublyLinked() #mydoublelist.insert(5) #mydoublelist.insert(0) #mydoublelist.insert(3) #mydoublelist.insert(10) #mydoublelist.delete(5) #print(mydoublelist)
714acb7788822dec6a517513db12e584b4fd2f78
AquaMagnet/python
/armstrong-numbers/armstrong_numbers.py
188
3.890625
4
def is_armstrong_number(number): number = str(number) armstrong = 0 for item in number: armstrong += int(item)**len(number) return(armstrong == int(number))
9fdc839e30c4eccbb829abfa30178545f2f3f7b3
sheayork/02A-Control-Structures
/E02a-Control-Structures-master/main06.py
719
4.5
4
#!/usr/bin/env python3 import sys assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') color = input("What is my favorite color? ") if (color.lower().strip() == 'red'): print('Correct!') else: print('Sorry, try again.') ##BEFORE: Same as before, but some people may put spaces in-between letter or right after typing something ## (I know I have a bad habit of doing the latter when it comes to typing papers). So basically the program ## will remove those spaces and change everything to lowercase letters to tell if the answer ## is right or not. ##AFTER: It didn't do it for spaces in-between letters, but otherwise I was correct.
6959a455d7027b83f7d3f08b699ba3833c513bfa
larspli/bug-free-happiness
/sirkelberegning.py
289
3.90625
4
import math radius=input("Verdien til radius?\n>") radius=float(radius) diameter= 2*radius areal=math.pi*radius*radius omkrets=2*math.pi*radius print("\nDiameter: {0: .2f}".format(diameter)) print("Areal: {0: .2f}".format(areal)) print("Omkrets: {0: .2f}".format(omkrets))
55663511a862c190b307d3f19d9423e95f860ce1
wjosew1984/python
/funcion7.py
446
3.84375
4
#lo hice con dos "for" def mayormenor(lista): k=lista[0] for x in range(len(lista)): if lista[x]>k: k=lista[x] z=lista[0] for x in range(len(lista)): if lista[x]<z: z=lista[x] print("El elemento mayor es", k," y el elemento menor es ",z) lista=[] for x in range (5): v=int(input("Ingrese 5 enteros: ")) lista.append(v) mayormenor(lista)
289f3eb1ea1df526769a1a39423882c493b03953
wjosew1984/python
/practicaoperaciones.py
497
3.96875
4
n1 = 5 n2 = 20 resultado = (n1 + n2) print("La suma es ", + resultado) n1 = 5 n2 = 20 resultado = (n1 - n2) print("La resta es ", + resultado) n1 = 5 n2 = 20 resultado = (n1 / n2) print("La division es ", + resultado) n1 = 5 n2 = 20 resultado = (n1 * n2) print("La multiplicacion es ", + resultado) n1 = 5 n2 = 20 resultado = (n1 % n2) print("El promedio es ", + resultado) n1 = 5 n2 = 20 resultado = (n1 ** n2) print("El exponencial es ", + resultado)
5365df676239be0b5c4690b6cc95d4b4b3e2eb7d
wjosew1984/python
/diccionario7.py
1,135
3.703125
4
def carga(): responde="si" productos={} while responde=="si": codigo=input("ingrese codigo de producto: ") desc=input("ingrese nombre producto: ") prec=int(input("ingrese precio producto: ")) stock=int(input("ingrese cantidad en stock: ")) productos[codigo]=(desc,prec,stock) responde=input("desea cargar?(si/no)") return productos def impr(productos): for codigo in productos: print("Codigo: {0}, nombre: {1}, precio: {2}, stock: {3}".format(codigo,productos[codigo][0],productos[codigo][1],productos[codigo][2])) def consulta(productos): palabra=input("Ingrese codigo a buscar: ") if palabra in productos: print( "Nombre %s Precio %d En stock %d"%(productos[palabra][0],productos[palabra][1],productos[palabra][2])) def sinstock(productos): for codigo in productos: if productos[codigo][2]==0: print("No hay stock de: %s"%productos[codigo][0]) lista_productos=carga() impr(lista_productos) consulta(lista_productos) sinstock(lista_productos)
14707821e0ad81c599c7e2c7d9c8011c2eda550a
wjosew1984/python
/ejerc7.py
148
3.828125
4
n1=float(input("ingresar n1: ")) n2=float(input("ingresar n2: ")) if n1>n2: print("n1 es mayor a n2") else: print("n2 es mayor a n1")
c6597db9f0e60f4813b3d5f9b678dddeb4e6a1bc
wjosew1984/python
/nuevobis.py
473
3.96875
4
""" sueldo=int(input("Ingrese su sueldo burto por favor")) if>30000: print("Debe pagar impuesto a las ganancias") else<29999 print("Debe pagar impuesto a las ganancias") ##### nombre_alumno = input("Escriba el nombre de un alumno: ") if nombre_alumno == "": print("Error: no ha ingresado un nombre válido.") else: print("Has ingresado el alumno correctamente.") """ n=5 if n > 2 print("Es mayor que dos") print("Fin del programa")
458490153bd4f387052ac9e6efe0462611c8ae65
wjosew1984/python
/lista_26_4.py
674
3.765625
4
#Crear y cargar una lista con 5 enteros por teclado, mostrar el menor valor de la lista y la posición doónde se encuentra: lista=[] t=0 for x in range(5): v = int(input("Ingrese entero: ")) lista.append(v) t=t+lista[x] print(f"La lista contiene {lista} y {[len(lista)]} elementos") k=lista[0]#nombro k al 1er elemento de la lista for x in range(1,len(lista)):#compara con k del 1 en adelante con el resto de la lista(len) if lista[x]<k:#acá es donde pasa si es mayor o menor en la lista k=lista[x]#guarda en k el elemento mayor o menor print("El elemento menor es: ",k, "Se encuentra en la posición:",(lista.index(k)))
36065308743f3347b51f0284367a2fe1de392474
wjosew1984/python
/clase1.py
8,646
4.0625
4
Introducción a la programación: Un poco de Historia e introducción al Lenguaje Surge en los años 90. Creado por el Holandes Guido van Rossum. Lenguaje alto nivel: Cercano al ser humano. Lenguaje de bajo nivel: Cercano a codigo binario. 1 y ceros. Python esta orientado a objetos tal como Java. Lo único que mas sencillo. La POO es una filosofía en la resolución de problemas. Hay otros tipos de Programacion (funcional, recursiva). Python es multi-paradigma. Tambien es multi-plataforma (se puede correr en Windows, Linux, Unix, y otras). Puede ser multi-plataforma por que es un lenguaje interpretado. El interprete es un programa que me permite interpretar el lenguaje de programación y poder ser ejecutado en el sistema operativo. Python se usa: Analisis de datos. Seguridad. Automatizacion de Procesos. Robotizacion. Rutinas diarias. Programacion Web. Y es de tipado dinamico (lo veremos en variables). La ultima clase haremos una aplicación de escritorio con un entorno grafico. Que es programar? Es decirle a una computadora lo que tiene que hacer. El programador es el que diseña esas instrucciones según las reglas de un lenguaje de programación en particular. Y esas instrucciones serán el programa o aplicación (codigo). Entonces programar puede pensarse como un proceso de comunicación, donde hay un emisor y receptor. Y el medio de comunicación es el lenguaje. Programa o Aplicación: Mensaje codificado según las reglas de un lenguaje de programación. Codigo Maquina. => precisamos un Traductor: convierte instrucciones escritas a codigo maquina. En donde Python (programa) es el interprete. El interprete es lo que nos referimos cuando decimos instalar Python. Python el programa es el interprete que traduce el lenguaje de Python en lenguaje de maquina. El dispositivo programable por su parte interpreta codigo binario (ceros y unos). Caracteristica de Python: Sintaxis sencilla y clara. Ejemplo de aplicaciones: Dispositivos mobiles, Web (Python), de escritorio (Python), de consola (Python). Tipos de Aplicaciones que nos enfocaremos: De consola, y de escritorio (contiene una interfaz grafica). Preparación del entorno. Vemos la guía de instalación de Python. Version 2 de Python, caduco en el 2018 y con soporte hasta 2020. Las bibliotecas que estaban pensadas para Python 2 no van a tener actualizaciones. Los scripts de Python 2 no van a poder correr en Python 3. Al Instalar Python recordar ubicar el path en una ruta amigable, ej c:/. Editor de codigo: IDE. => nos permiten programar. => Ej: Geany, block de notas Extensión .py => codigo fuente. Expresiones Es una porción de codigo que ejecuta una operación o tarea determinada. Y obtiene un resultado. Operaciones aritméticas: son ejemplo de expresion. => 7 + 5, se ejecuto y obtiene un resultado. Print(“Hola Mundo”): también es una expresion. Sintaxis: orden y la relación de los términos de un lenguaje necesarios para que una instrucción sea comprendida. Para la suma la sintaxis es: 7 + 5 (colocamos esta sintaxis en Geany) Por que no muestra nada? Como les parece que hacemos para que muestre el resultado?. “ “ : interpreta de forma literal y no como codigo de Python. Por eso cuando ingresamos print(“7 + 5”) lo muestra literalmente Entonces volviendo a nuestra expresion 7 + 5. Expresion: Es un fragmento de codigo que retorna un resultado. Retornar significa reemplazar en ese fragmento de codigo por su resultado. Entonces print ( 7 + 5) es igual a print (12). Primero resuelve la expresion y en el lugar donde esta escrita la expresion reemplaza con el resultado. print ( 7 + 5 + 10): resuelve de izquierda a derecha. Primero 7 + 5 y luego 12 + 10. El termino “reemplazar” se usa a fines didácticos para comprender el concepto de expresion. Variables Que es una variable? Es un lugar en memoria que el interprete crea para guardar un determinado dato. variable = 10 variable Sintaxis: nombre_variable = expresion (minúsculas sin espacios) a = 7 + 5 Creacion de una variable => 1. Definicion y 2. Asignacion Ej: a = 7 + 5 print (a) Creo otras expresiones en base a la variable previa a = 7 + 5 print (a + 10) Y también puedo crear otras variables. a = 7 + 5 b = a + 10 print(b) Las variables son en si mismas expresiones. Esto significa que Python reemplazara a por 12 en toda ocurrencia de a. Y para una variable saludo que contiene el valor “Hola mundo”. Tipo de datos: En otros lenguajes debemos definir el tipo de dato. Tipado Dinámico: No hace falta declarar el tipo de dato en Python. Se pueden sobreescribir los valores. Ej: a= 10; a = 10.5; a=’hola’ Consola Interactiva “>>>” No sirve para hacer programas, simplemente es una interacción (charla) con el interprete. Nos permite escribir codigo Python sin necesidad de guardarlo en un archivo .py. Es una forma de probar codigo Python y probarlo rápidamente. Windows + R => Python 7 + 7: muestra el resultado. String: print(“hola mundo”) Modulo: Explicamos Resto. % Ej: 10%2 9%2 type(a) IDE - GEANY Seteo 1 Espacios => Documento – Tipo de Sangria – Espacios Seteo 2 espacios => Editar – Preferencias – Editor – Sangria – Seleccionar “Espacios” Este seteo evita que luego tengamos problemas en algun programa cuando se mezclen espacios y tabulaciones. Primer Programa “Hola Mundo” Con Geany. En general es el 1er programa que se ejecuta cuando aprendemos programación. Guardamos el archivo en nuestra carpeta de trabajo, borramos el codigo previo y escribimos: #!/usr/bin/env python # -*- coding: utf-8 -*- #!/usr/bin/env Python (llama al interprete en Linux) buscará el ejecutable del comando python de acuerdo a las rutas definidas en el $PATH de tu entorno (cuando se trata de Unix o Linux). Para Windows no aplica. Los caracteres #! se los conoce como shebang (Unix). La segunda linea se refiere a la codificación en español de ciertos caracteres especiales. print("Hola mundo") Ejecutar o F5 Lo guardamos como hola.py. Consola: Windows + R => CMD Terminal como aplicacion. Vemos la diferencia entre movernos con el explorador y con la consola. Y también la diferencia en como ejecutamos desde el explorador y desde la consola. dir: me permite ver el contenido de una carpeta. cd (change directory) vamos al archivo donde se encuentra nuestra aplicación. Acceder a una ruta que contiene espacios => con comillas. Ej cd “c:\Program Files (x86)\Geany” ping: programa para saber si una dirección de ip o dominio esta corriendo. Solo hay 2 operaciones (ingresar instrucciones, output de mensajes en consecuencia a las instrucciones) => ping www.mercadolibre.com.ar Probamos ejecutar el archivo hola.py desde la ruta C:\Users\lrlopez\Desktop\PYTHON\CLASE 1> con el cmd. python hola.py Algunas consideraciones Doble click del programa desde el origen. Y la diferencia que hay corriéndolo desde un IDE. Script: Conjunto de instrucciones guardadas en un archivo con extensión .py. Formas de ejecutar un script en Python: 1. Desde el IDE. 2. Con el archivo 3. Desde la consola o terminal. Al finalizar la linea no es necesario poner “;” como otros lenguajes. Ejercitacion desde Geany r = 10 + 30 print(r) Hacemos el ejercicio de Laboratorio entre todos. Estructura de un programa Programar es como redactar una receta de cocina. Debemos indicarle a la maquina lo que debe hacer. La receta es el programa o aplicación. Editor de codigo: Es un programa diseñado para permitirnos escribir codigo que crearan nuevos programas. Por ejemplo Flujo del programa: Recorrido del codigo por el cual las instrucciones se redactan y se interpretan de arriba hacia abajo y de izquierda a derecha. Algoritmo: conjunto de operaciones que solucionan un problema determinado. Ej: El procedimiento por el cual se resuelve una ecuación de 2do grado. #palabras reservadas Un bucle while permite repetir la ejecución de un grupo de instrucciones mientras se cumpla una condición (es decir, mientras la condición tenga el valor True). La ejecución de esta estructura de control while es la siguiente: Python evalúa la condición: si el resultado es True se ejecuta el cuerpo del bucle. #La sentencia condicional if Se usa para tomar decisiones, este evaluá básicamente una operación lógica, es decir una expresión que de como resultado True o False , y ejecuta la pieza de código siguiente siempre y cuando el resultado sea verdadero.
deaa298d5be9815b2fba7560a11f046b2cadf194
wjosew1984/python
/pedir2ntecladoymostrarnumerospares.py
184
3.859375
4
numero1 = int(input("Introduce el primer numero: ")) numero2 = int(input("Introudce el segundo numero: ")) for n in range(numero1, numero2+1): if n % 2 == 0: print(n)
02eb2a3b3528e57b0217f2ec2e1586c249115639
wjosew1984/python
/main.py
1,764
3.9375
4
"""a=2 b=3 c=a+b print("El resultado es", c) nombre="Adrian" apellido="Jusid" print(nombre+" "+apellido) print(nombre, apellido) edad=36 print("soy" , nombre , apellido , "y tengo ", edad , "años") a=100 b=1000 c=10000 print(a>b) print(True and True) print(True and False) print(False and True) print(False and False) num=int(input("Ingrese un numero por favor:")) if num==100: print("numero igual a cien") else: if num > 100: print("numero mayor a cien") else: print("numero menor a cien") #print("Se ejecuta siempre, fuera del bloque") tuplas ordenadas y no se pueden modificar tupla=(10,20,30,40,50,60) print(tupla[3]) t1=(5,6) t2=(7,8) t3=t1+t2 print(t3) #listas no son ordenadas y se pueden modificar lista=[10,20,30,40,50] print(lista[2]) lista[2]=35 print(lista) lista=[10,20,30,40,50] lista.append(60) print(lista) lista.insert(2,25) print(lista) lista.remove(60) print(lista) quitado=lista.pop(4) print(quitado) print(lista) lista.pop(4) print(lista) print(len(lista)) lista=[10,20,30,40,50] for elemento in lista: print(elemento) #range(desde, hasta, incremento) i=3 for i in range(0,5,1) range(0,5,1) -> [0,1,2,3,4,] range(0,5) range(0,5,2) -> [0,2,4,] range(1,10,1) -> [1,2,3,4,5,6,7,8,9] range(5,-1,-1) -> [5,4,3,2,1,0] lista=[] valor=0 for i in range(0,4,1): valor=valor+10 lista.append(valor) print(lista) for valor in range(0,4,1): valor=valor+10 lista.append(valor) print(lista) matriz=[["a","b","c"], ["d","e","f"]] for lista in matriz: for elemento in lista: print(elemento) """ num=1 while num<10: print(num) num+=1 if num==5: break
6616b708b1aab6bb1b9db91e5d42094fc3597b68
wjosew1984/python
/ejerc15.py
486
3.671875
4
cantp=int(input("ingrese la cantidad de personas: ")) km=int(input("ingrese la cantidad de km por recorrer: ")) micro=input("ingrese el tipo de micro: a, c ó b ") if micro=="a": pkg=km*2 else: if micro=="b": pm=km*2*5 else: pm=km*3 preciototal=pm*cantp if cantp>20: precioind=preciototal/cantp else: precioind=preciototal/20 print("el precio total del viaje es de: $",preciototal,"el precio individual es de: $",precioind)
e9f735bcf71d70e868e32e16705e07cc12ef8e92
wjosew1984/python
/ejerc4.py
118
3.5
4
vd=int(input("ingrese un valor: ")) cp=int(input("ingrese un valor: ")) td=cp/vd print("El total dolar es :",td)
6951f7e3f45c70a2cb4b542ba6ec2df0bd6eabbb
wjosew1984/python
/funcion10.py
849
3.75
4
def carga(): sueldo=[] for x in range(3): f=int(input("Ingrese valor: ")) sueldo.append(f) return sueldo def impsueldo(sueldo): print("lista de sueldos: ") for x in range(len(sueldo)): print(sueldo[x]) def mayor40k(sueldo): tot=0 for x in range(len(sueldos)): if sueldo[x]>40000: tot=tot+1 print(tot) def prom(sueldo): tot=0 for x in range(len(sueldo)): tot=tot+sueldo[x] prom=tot/len(sueldo) return prom def inferprom(sueldo): p=prom(sueldo) print("inferior a 40000: ") for x in range(len(sueldo)): if sueldo[x]<p: print (sueldo[x]) sueldos=carga() impsueldo(sueldos) mayor40k(sueldos) inferprom(sueldos)
36357b7e13e3e49b7dc1d0eea90f19c0c383502d
YanrongXu/Leetcode
/Binary Search/230. Kth Smallest Element in a BST.py
941
3.546875
4
# In-order Traversal class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: self.tree_list = [] self.inOrder(root) if k <= 0: return None print(self.tree_list) return self.tree_list[k-1] def inOrder(self, root): if not root: return if not root.left and not root.right: self.tree_list.append(root.val) return self.inOrder(root.left) self.tree_list.append(root.val) self.inOrder(root.right) # In-order Iterative class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: stack = [] while True: while root: stack.append(root) root = root.left root = stack.pop() k -= 1 if not k: return root.val root = root.right
c27f9020cb6bfa7ce8e03fbec2eeb6b4983ba19d
aimemalaika/intro-to-python
/basics I/dataconversion.py
175
3.515625
4
a = 100 # convert to string b = str(a) print(a) print(type(a)) print(b) print(type(b)) # convert to int a = 100 # convert to string c = int(b) print(c) print(type(c))
d17fcba1a1a7a73b08bf6e3c8208318b4661d148
manuelklug/learning
/Python UNSAM/Clase 2/tabla_informe.py
1,791
3.53125
4
# tabla_informe.py import csv # Funcion leer_camion def leer_camion(nombre_archivo): camion = [] with open(nombre_archivo) as file: rows = csv.reader(file) headers = next(rows) for row in rows: record = dict(zip(headers, row)) cajon = { 'nombre': record['nombre'], 'cajones': int(record['cajones']), 'precio': float(record['precio']) } camion.append(cajon) return camion # Funcion leer precios def leer_precios(nombre_archivo): precios = {} with open(nombre_archivo) as file: rows = csv.reader(file) for row in rows: try: fruta = row[0] precio = float(row[1]) precios[fruta] = precio except: print("Una fila no pudo ser leída") return precios # Hacer informe def hacer_informe(cajones, precios): lista = [] for dic in cajones: nombre = dic['nombre'] cajones = dic['cajones'] precio = dic['precio'] cambio = precios[nombre] - dic['precio'] tupla = (nombre, cajones, precio, cambio) lista.append(tupla) return lista camion = leer_camion('Data/camion.csv') precios = leer_precios('Data/precios.csv') informe = hacer_informe(camion, precios) # Tabla headers = ('Nombre', 'Cajones', 'Precio', 'Cambio') header_espaciado = '' for valor in headers: header_espaciado += f'{valor:>10s} ' separacion = '' for x in range(len(headers)): separacion += '---------- ' print(header_espaciado) print(separacion) for nombre, cajones, precio, cambio in informe: print(f'{nombre:>10s} {cajones:>10d} {precio:>10.2f} {cambio:>10.2f}')
5800638df7e06468ddfaf0fc870fbcae926b5838
ptetalicoder/Final-Project--CIS2348
/Homework 3 - 11.22.py
183
3.5625
4
#Pranav Tetali #ID 1541822 #Homework 3 11.22 words = input().split() for word in words: count = 0 for w in words: if w == word: count += 1 print(word, count)
240ef926f2383e9a91f63c086c02b32d7d36b13b
ptetalicoder/Final-Project--CIS2348
/Homework 3 - 10.17 Part 1.py
1,562
4.03125
4
#Pranav Tetali #ID 1541822 #Homework 3 10.17 class ItemToPurchase: # EX #1 def __init__(self): # variables # given values self.item_name = "none" self.item_price = 0 self.item_quantity = 0 #items def print_item_cost(self): #It should display the item name, quantity and price in that order print(self.item_name + " " + str(self.item_quantity) + " @ $" + str(self.item_price) + " = $" + str( self.item_price * self.item_quantity )) if __name__ == "__main__": # Ex #2 # This is the main function # It should print the item1 depending on item given print("Item 1") item1 = ItemToPurchase() item2 = ItemToPurchase() # it should prompt and read the item1 details from the user item1.item_name = input('Enter the item name:\n') item1.item_price = int(input('Enter the item price:\n')) item1.item_quantity = int(input('Enter the item quantity:\n')) print("\nItem 2") # it should prompt the user and read the item2 details from the user item2.item_name = input('Enter the item name:\n') item2.item_price = int(input('Enter the item price:\n')) item2.item_quantity = int(input('Enter the item quantity:\n')) print("\nTOTAL COST") # Ex #3 item1.print_item_cost() item2.print_item_cost() # it should add up the cost of items total = (item1.item_price*item1.item_quantity)+(item2.item_price * item2.item_quantity) # it should display the total cost at the bottom print("\nTotal: $" + str(total))
50b76bec203e5922cc4419fff9deb5ddd5e6cb62
braraki/logical-options-framework
/simulator/object.py
10,367
3.75
4
import numpy as np from numpy.random import randint from collections import OrderedDict import random """ Author: Brandon Araki This file contains classes that describe "objects" in the environment. Objects have a state space, a state, and update rules. """ # describe the Agent as an object class AgentObj(object): """AgentObj Describe the agent as an object. """ def __init__(self, name, color, state_space): """ Initialize the agent. Args: name (str): name of the agent object (e.g., 'agent') color (list): [r, g, b] array describing the color of the agent for plotting, 0-255 state_space (list): [x, y, ...] describing the state space of the agent """ self.name = name self.color = np.array(color) self.state = None # [x, y, h] --> h for if it's holding something # state space must be a list self.state_space = state_space def create(self, x_range, y_range, exclude_from_x_range=[], exclude_from_y_range=[]): def random_num(i_range, exclude_from_range): i = None if isinstance(i_range, int): # randint will return i if list is [i, i+1] i_range = [i_range, i_range+1] i = randint(*i_range) while i in exclude_from_range: i = randint(*i_range) return i x = random_num(x_range, exclude_from_x_range) y = random_num(y_range, exclude_from_y_range) h = 0 state = [x, y, h] self.state = state return state def create_with_mask(self, x_range, y_range, mask=None): x = random.choice(x_range) y = random.choice(y_range) if mask is not None: while mask[x, y] == 1: x = random.choice(x_range) y = random.choice(y_range) h = 0 state = [x, y, h] self.state = state return state def set_state(self, x): if type(x).__name__ == 'list': x = x[0] self.state[0] = x def get_state(self): return [self.state[0]] def step(self, env, action): self.apply_action(env, action) self.apply_dynamics(env) def apply_action(self, env, action): if action == 0: # do nothing pass elif action == 1: # move left if self.state[0] > 0: self.state[0] = self.state[0] - 1 elif action == 2: # move right if self.state[0] < env.dom_size[0] - 1: self.state[0] = self.state[0] + 1 elif action == 3: # grip pass elif action == 4: # drop pass else: raise ValueError('action {} is not a valid action'.format(action)) def apply_dynamics(self, env): return class GridAgentObj(AgentObj): """GridAgentObj Describes an agent object for gridworld environments. In particular, the state is [x, y] and the actions are 'nothing', 'left', 'right', 'up', and 'down'. """ def __init__(self, name, color, state_space): super().__init__(name, color, state_space) def set_state(self, x): self.state[:2] = x def get_state(self): return self.state[:2] def apply_action(self, env, action): if action == 0: # do nothing pass # note: the agent cannot wrap around the environment elif action == 1: # move left if self.state[0] > 0: self.state[0] = self.state[0] - 1 else: self.state[0] = self.state[0] # env.dom_size[0] - 1 elif action == 2: # move right if self.state[0] < env.dom_size[0] - 1: self.state[0] = self.state[0] + 1 else: self.state[0] = self.state[0] # 0 elif action == 3: # up if self.state[1] > 0: self.state[1] = self.state[1] - 1 else: self.state[1] = self.state[1] # env.dom_size[0] - 1 elif action == 4: # down if self.state[1] < env.dom_size[1] - 1: self.state[1] = self.state[1] + 1 else: self.state[1] = self.state[1] # 0 else: raise ValueError('action {} is not a valid action'.format(action)) class LocObj(object): """LocObj Describes a stationary object associated with a single state. """ def __init__(self, name, color, state_space): self.name = name self.color = np.array(color) # [r, g, b] 0-255 self.state = None # [x, y, h] --> h is whether or not it's being held self.state_space = state_space def __repr__(self): return self.name + ", " + type(self).__name__ + ", LocObj, " + hex(id(self)) def set_state(self, state): self.state = state def get_state(self): return self.state def create(self, x_range, y_range, exclude_from_x_range=[], exclude_from_y_range=[]): ''' x_range, y_range: int or [int, int] from which x and y will be randomly selected (optional) exclude_from_x/y_range: list of ints which will be passed over ''' def random_num(i_range, exclude_from_range): i = None if isinstance(i_range, int): # randint will return i if list is [i, i+1] i_range = [i_range, i_range+1] i = randint(*i_range) while i in exclude_from_range: i = randint(*i_range) return i x = random_num(x_range, exclude_from_x_range) y = random_num(y_range, exclude_from_y_range) h = 0 state = [x, y, h] self.state = state return state def create_with_mask(self, x_range, y_range, mask=None): x = random.choice(x_range) y = random.choice(y_range) if mask is not None: while mask[x, y] == 1: x = random.choice(x_range) y = random.choice(y_range) h = 0 state = [x, y, h] self.state = state return state def step(self, env, action): self.apply_action(env, action) self.apply_dynamics(env) def apply_action(self, env, action): return NotImplementedError def apply_dynamics(self, env): return NotImplementedError class GridGoalObj(LocObj): """GridGoalObj Describes LocObjs with [x, y] states. """ def apply_action(self, env, action): return def apply_dynamics(self, env): return def set_state(self, x): self.state[:2] = x def get_state(self): return self.state[:2] class StaticObj(object): """StaticObj Static objects are ones with trivial dynamics that don't change. Instead of being associated with a single state, for convenience they can be associated with many states in the state space. (e.g., obstacles) """ def __init__(self, name, color, dom_size): self.name = name self.color = np.array(color) # [r, g, b] 0-255 self.dom_size = dom_size self.state = np.zeros(self.dom_size) def __repr__(self): return self.name + ", " + type(self).__name__ + ", StaticObj, " + hex(id(self)) def step(self, env, action): self.apply_action(env, action) self.apply_dynamics(env) def apply_action(self, env, action): return def apply_dynamics(self, env): return class ObstacleObj(StaticObj): """ObstacleObj A StaticObj that represents obstacles in the environment. Has a number of helper functions for creating obstacles. """ def __init__(self, name, color, dom_size, mask=None, size_max=None): super().__init__(name, color, dom_size) self.mask = None self.size_max = None def add_random_obstacle(self, x_range, y_range, exclude_from_x_range=[], exclude_from_y_range=[]): def random_num(i_range, exclude_from_range=[]): i = None if isinstance(i_range, int): # randint will return i if list is [i, i+1] i_range = [i_range, i_range+1] i = randint(*i_range) while i in exclude_from_range: i = randint(*i_range) return i x = random_num(x_range, exclude_from_x_range) y = random_num(y_range, exclude_from_y_range) self.state[x, y] = 1 def add_obstacle_grid(self, obstacle_size=1, offset_from_edge=0): for i in range(obstacle_size): for j in range(obstacle_size): self.state[(i+offset_from_edge)::(obstacle_size+1), (j+offset_from_edge)::(obstacle_size+1)] = 1 def check_mask(self, dom=None): # Ensure goal is in free space if dom is not None: return np.any(dom[self.mask[:, 0], self.mask[:, 1]]) else: return np.any(self.dom[self.mask[:, 0], self.mask[:, 1]]) def insert_rect(self, x, y, height, width): # Insert a rectangular obstacle into map state_try = np.copy(self.state) state_try[x:x+height, y:y+width] = 1 return state_try def add_rand_obs(self): # Add random (valid) obstacle to map rand_height = int(np.ceil(np.random.rand() * self.size_max)) rand_width = int(np.ceil(np.random.rand() * self.size_max)) randx = int(np.ceil(np.random.rand() * (self.dom_size[1]-1))) randy = int(np.ceil(np.random.rand() * (self.dom_size[1]-1))) state_try = self.insert_rect(randx, randy, rand_height, rand_width) if self.check_mask(state_try): return False else: self.state = state_try return True def create_n_rand_obs(self, mask=None, size_max=None, num_obs=1): # each row of the mask is a different goal if mask is None: self.mask = np.array([]) else: if mask.ndim == 1: # handle the 1-goal case mask = mask[None, :] self.mask = mask self.size_max = size_max or np.max(self.dom_size) / 4 # Add random (valid) obstacles to map count = 0 for i in range(num_obs): if self.add_rand_obs(): count += 1
7cff6fe881137bc81dcc5540efc806eb8ab75bc4
maxsolberg/ORSuite
/or_suite/envs/ambulance/ambulance_metric.py
7,150
3.53125
4
''' Implementation of a basic RL environment for continuous spaces. Includes three test problems which were used in generating the figures. ''' import numpy as np import gym from gym import spaces import math from .. import env_configs #------------------------------------------------------------------------------ '''An ambulance environment over [0,1]. An agent interacts through the environment by picking a location to station the ambulance. Then a patient arrives and the ambulance most go and serve the arrival, paying a cost of travel.''' class AmbulanceEnvironment(gym.Env): """ Custom Environment that follows gym interface. This is a simple env where the arrivals are always uniformly distributed """ metadata = {'render.modes': ['human']} def __init__(self, config = env_configs.ambulance_metric_default_config): ''' For a more detailed description of each parameter, see the readme file epLen - number of time steps arrival_dist - arrival distribution for calls over the space [0,1] alpha - parameter for proportional difference in costs starting_state - a list containing the starting locations for each ambulance num_ambulance - the number of ambulances in the environment ''' super(AmbulanceEnvironment, self).__init__() self.config = config self.epLen = config['epLen'] self.alpha = config['alpha'] self.starting_state = config['starting_state'] self.state = np.array(self.starting_state, dtype=np.float32) self.timestep = 0 self.num_ambulance = config['num_ambulance'] self.arrival_dist = config['arrival_dist'] self.viewer = None # The action space is a box with each ambulances location between 0 and 1 self.action_space = spaces.Box(low=0, high=1, shape=(self.num_ambulance,), dtype=np.float32) # The observation space is a box with each ambulances location between 0 and 1 self.observation_space = spaces.Box(low=0, high=1, shape=(self.num_ambulance,), dtype=np.float32) def reset(self): """ Reinitializes variables and returns the starting state """ # Initialize the timestep self.timestep = 0 self.state = self.starting_state return self.starting_state def get_config(self): return self.config def step(self, action): ''' Move one step in the environment Args: action - float list - list of locations in [0,1] the same length as the number of ambulances, where each entry i in the list corresponds to the chosen location for ambulance i Returns: reward - float - reward based on the action chosen newState - float list - new state done - 0/1 - flag for end of the episode ''' old_state = np.array(self.state) # The location of the new arrival is chosen randomly from the arrivals # distribution arrival_dist new_arrival = self.arrival_dist(self.timestep) # The closest ambulance to the call is found using the l-1 distance close_index = np.argmin(np.abs(old_state - new_arrival)) # Update the state of the system according to the action taken and change # the location of the closest ambulance to the call to the call location action = np.array(action, dtype=np.float32) new_state = action.copy() new_state[close_index] = new_arrival # print("Old", old_state) # print("Action", action) # print("Close Index", close_index) # print("New Arrival", new_arrival) # print("New", new_state) # The reward is a linear combination of the distance traveled to the action # and the distance traveled to the call # alpha controls the tradeoff between cost to travel between arrivals and # cost to travel to a call # The reward is negated so that maximizing it will minimize the distance # print("alpha", self.alpha) reward = -1 * (self.alpha * np.sum(np.abs(old_state - action)) + (1 - self.alpha) * np.sum(np.abs(action - new_state))) # The info dictionary is used to pass the location of the most recent arrival # so it can be used by the agent info = {'arrival' : new_arrival} if self.timestep != self.epLen - 1: done = False else: done = True self.state = new_state self.timestep += 1 return self.state, reward, done, info # def render(self, mode='console'): # if mode != 'console': # raise NotImplementedError() def render(self, mode='human'): screen_width = 600 screen_height = 400 #world_width = self.x_threshold * 2 #scale = screen_width/world_width #carty = 100 # TOP OF CART #polewidth = 10.0 #polelen = scale * (2 * self.length) #cartwidth = 50.0 #cartheight = 30.0 if self.viewer is None: from gym.envs.classic_control import rendering self.viewer = rendering.Viewer(screen_width, screen_height) # l, r, t, b = -cartwidth / 2, cartwidth / 2, cartheight / 2, -cartheight / 2 # axleoffset = cartheight / 4.0 # cart = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)]) # self.carttrans = rendering.Transform() # cart.add_attr(self.carttrans) line_0 = (50, 100) line_1 = (550, 100) self.number_line = rendering.Line(line_0, line_1) self.number_line.set_color(0, 0, 0) self.viewer.add_geom(self.number_line) # self.viewer.add_geom(cart) # l, r, t, b = -polewidth / 2, polewidth / 2, polelen - polewidth / 2, -polewidth / 2 # pole = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)]) # pole.set_color(.8, .6, .4) # self.poletrans = rendering.Transform(translation=(0, axleoffset)) # pole.add_attr(self.poletrans) # pole.add_attr(self.carttrans) # self.viewer.add_geom(pole) # self.axle = rendering.make_circle(polewidth/2) # self.axle.add_attr(self.poletrans) # self.axle.add_attr(self.carttrans) # self.axle.set_color(.5, .5, .8) # self.viewer.add_geom(self.axle) # self.track = rendering.Line((0, carty), (screen_width, carty)) # self.track.set_color(0, 0, 0) # self.viewer.add_geom(self.track) # self._pole_geom = pole if self.state is None: return None # Edit the pole polygon vertex # pole = self._pole_geom # l, r, t, b = -polewidth / 2, polewidth / 2, polelen - polewidth / 2, -polewidth / 2 # pole.v = [(l, b), (l, t), (r, t), (r, b)] # x = self.state # cartx = x[0] * scale + screen_width / 2.0 # MIDDLE OF CART # self.carttrans.set_translation(cartx, carty) # self.poletrans.set_rotation(-x[2]) return self.viewer.render(return_rgb_array=mode == 'rgb_array') def close(self): pass
b93667bb58dfc610850d6ffa407ee418af6f44b0
Mamedefmf/Python-Dev-Course-2021
/magic_number/main.py
1,233
4.15625
4
import random def ask_number (min, max): number_int = 0 while number_int == 0: number_str = input(f"What is the magic number ?\nType a number between {min} and {max} : ") try: number_int = int(number_str) except: print("INPUT ERROR: You need to type a valid number") else: if number_int < min or number_int > max: print(f"INPUT ERROR: You must give a number between {min} and {max}") number_int = 0 return number_int MIN_NUMBER = 1 MAX_NUMBER = 10 MAGIC_NUMBER = random.randint(MIN_NUMBER, MAX_NUMBER) NB_LIVES = 4 number = 0 lives = NB_LIVES while not number == MAGIC_NUMBER and lives > 0: print(f"You have {lives} attempts left") number = ask_number(MIN_NUMBER, MAX_NUMBER) if number > MAGIC_NUMBER: print(f"{number} is greater than the Magic Number") lives -= 1 # subtract 1 live elif number < MAGIC_NUMBER: print(f"{number} is lower than the Magic Number") lives = lives - 1 # subtract 1 live else: print(f"You Won! the Magic Number is {MAGIC_NUMBER}\n Congratulations !!!") if lives == 0: print(f"You Lost!\nThe magic number was: {MAGIC_NUMBER}")
e8b2e2de913f442512a58987a99cce6371849ae9
pranavkaul/Coursera_Python_for_Everybody_Specialization
/Course-3-Using Python to Access Web Data/Assignment7-JSON.py
1,739
3.9375
4
#In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps. #API End Points #To complete this assignment, you should use this API endpoint that has a static subset of the Google Data: #http://py4e-data.dr-chuck.net/json? #This API uses the same parameter (address) as the Google API. This API also has no rate limit so you can test as often as you like. If you visit the URL with no parameters, you get "No address..." response. #To call the API, you need to include a key= parameter and provide the address that you are requesting as the address= parameter that is properly URL encoded using the urllib.parse.urlencode() function as shown in http://www.py4e.com/code3/geojson.py #Make sure to check that your code is using the API endpoint is as shown above. You will get different results from the geojson and json endpoints so make sure you are using the same end point as this autograder is using. import json import urllib import urllib.request,urllib.parse,urllib.error serviceurl = "http://py4e-data.dr-chuck.net/json?" while True: address = input('Enter Location') if len(address) < 1: break url = serviceurl + urllib.parse.urlencode({'key': 42, 'address': address}) print('Retrieving:',url) url_info = urllib.request.urlopen(url).read().decode() try: js = json.loads(url_info) except: js = None print('Retrieved', len(url_info)) print('Place_ID',js['results'][0]['place_id'])
2a2ae134cceba04732db0f61fb19f83221ca3f1d
pranavkaul/Coursera_Python_for_Everybody_Specialization
/Course-1-Programming for everybody-(Getting started with Python/Assignment_6.py
999
4.3125
4
#Write a program to prompt the user for hours and rate per hour using input to compute gross pay. #Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. #Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. #The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). #You should use input to read a string and float() to convert the string to a number. #Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. #Do not name your variable sum or use the sum() function. def computepay(h,r): if h > 40: total = (((1.5 * r) * (h-40)) + (40 * r)) else: total = h * r return total hours = input('Hours') h = float(hours) rate = input('Rate') r = float(rate) total = computepay(h,r) print ("Pay",total)
1fd47db24f772cf140ea6cf2ee5808b4398fcbed
annafleming/Python-Training
/Recursion/exercises/tests/examples_test.py
660
3.890625
4
import unittest from .. import examples class RecursionExamplesTestCase(unittest.TestCase): def test_should_return_true_if_value_is_found(self): sequence = [1, 4, 6, 7, 8, 9, 10] self.assertTrue(examples.in_list(sequence, 9)) sequence = [1, 4, 6, 7, 8, 9, 10, 11] self.assertTrue(examples.in_list(sequence, 11)) sequence = [1, 4, 6, 7, 8, 9, 10, 11] self.assertTrue(examples.in_list(sequence, 1)) def test_should_return_false_if_value_is_not_found(self): sequence = [1, 4, 6, 7, 8, 9, 10] self.assertFalse(examples.in_list(sequence, 5)) if __name__ == '__main__': unittest.main()
d955e9fa46e5738527334d40c6c068eb1e81abe1
annafleming/Python-Training
/Python Primer/exercises/reinforcement.py
628
3.734375
4
from random import randrange def is_multiple(n, m): return n % m == 0 def is_even(n): while n >= 2: n -= 2 return False if n == 1 else True def minmax(data): min_item = max_item = data[0] for item in data: if item < min_item: min_item = item if item > max_item: max_item = item return min_item, max_item def get_sum_of_squares(n): return sum([i**2 for i in range(n)]) def get_sum_of_squares_of_odd_numbers(n): return sum([i ** 2 for i in range(n) if i % 2 == 1]) def get_rand_element(seq): return seq[randrange(0, len(seq) - 1, 1)]
b6be97451439d9a72f9304e49a0164c3e3a74ea0
gabriel-portuga/Exercicios_Python
/ex067_tabuada.py
418
3.71875
4
while True: num = int(input('Quer ver a tabuada de qual valor: ')) if num < 0: break print('-'*20) for i in range(1, 11): print(f'{num} x {i:>2} = {num * i}') print('-'*20) continua = 's' while continua in 'sS': continua = str(input('Deseja continua? [S/N] ')).strip().upper()[0] if continua in 'sS': break if continua in 'nN': break
d7855d43a0db8895af9eb431fe334c3369bce5d1
gabriel-portuga/Exercicios_Python
/ex038_comparandonumeros.py
399
3.671875
4
print('\033[7;30m-=\033[m'*15) print(' \033[7;30m Bem vindo ao APP Go!Sys \033[m') print('\033[7;30m-=\033[m'*15) # Inico do condigo n1 = int(input(('\nDigite um número: '))) n2 = int(input('Digite outro valor: ')) if n1 > n2: print('O primeiro valor é maior!') elif n2 > n1: print('O segundo número é maior!') elif n1 == n2: print('Não existe valor maior, os dois são iguais!')
00e4fb1dca49a8e5dcd5657b43edc6e4691ba45a
gabriel-portuga/Exercicios_Python
/ex065_maioremenor.py
1,050
4.0625
4
""" num = soma = cont = media = maior = menor = i = 0 while i != 1: num = int(input('Digite um número: ')) soma += num cont += 1 media = float(soma / cont) if cont == 1: menor = num if num > maior: maior = num elif num < menor: menor = num i = int(input('Digite uma opção \n[ 1 ] Sair \n[ 2 ] Continuar\n')) print('A média entre os números digitador foi {:.2f}, o maior número é' ' {} e o menor número é {}.'.format(media, maior, menor)) """ resp = 'S' soma = quant = media = maior = menor = 0 while resp in 'Ss': num = int(input('Digite um número: ')) soma += num quant += 1 if quant == 1: maior = menor = num else: if num > maior: maior = num if num < menor: menor = num resp = str(input('Quer continuar? [S/N] ')).upper().strip()[0] media = soma / quant print('você digitou {} números e a média foi {}.'.format(quant, media)) print('O maior valor foi {} e o menor valor foi {}.'.format(maior, menor))
10fd72a743b1d9398be5d213f88cc7f927b12a3f
gabriel-portuga/Exercicios_Python
/ex062_superprogressao.py
828
3.9375
4
""" ERRADO primeiro = int(input('Primeiro termo: ')) razao = int(input('Razão da PA: ')) termo = primeiro cont = 1 escolha: int = 1 while escolha != 0: while cont <= 10: print('{} -> '.format(termo), end='') termo += razao cont += 1 escolha = int(input('Deseja mostrar mais quantos termos: ')) cont = 1 print('FIM') """ primeiro = int(input('Primeiro termo: ')) razao = int(input('Razão da PA: ')) termo = primeiro cont: int = 1 total: int = 0 escolha: int = 10 while escolha != 0: total = total + escolha while cont <= total: print('{} -> '.format(termo), end='') termo += razao cont += 1 print('PAUSA') escolha = int(input('Deseja mostrar mais quantos termos: ')) print('Progressão finalizada com {} termos mostrados.'.format(total)) print('FIM')
eee62591903f3920aea6dbbfeb6c4966f5714966
gabriel-portuga/Exercicios_Python
/ex080_ListaOrdenada.py
514
4.03125
4
numeros = list() for i in range(0, 5): n = int(input('Digite um valor: ')) if i == 0 or n > numeros[-1]: numeros.append(n) print('Adicionado ao final da lista...') else: posicao = 0 while posicao < len(numeros): if n <= numeros[posicao]: numeros.insert(posicao, n) print(f'Adicionado na posição {posicao} da lista...') break posicao += 1 print(f'Os valores digitados em ordem foram: {numeros}')
bf394547b09f92d6ef9fa0133d3385f2edba8d99
gabriel-portuga/Exercicios_Python
/ex064_tratandovalores.py
298
3.828125
4
"""num: int = 0 cont: int = 0 soma: int = 0""" num = cont = soma = 0 while num != 999: num = int(input('Digite um número[999 para parar]: ')) if num != 999: soma += num cont += 1 print('Foram digitador {} números e a soma entre eles é: {}.' ''. format(cont, soma))
15bc4f04dfb5dafdb153a7a060a21bb1602492ff
gabriel-portuga/Exercicios_Python
/ex030_pariouimpar.py
223
3.78125
4
from time import sleep num = int(input('Me diga um número qualquer: ')) print('Processando...') sleep(2) if num % 2 == 0: print('O número {} é PAR!'.format(num)) else: print('O número {} é IMPAR!'.format(num))
fdaa9ff1d96bf5473826045d769273d40e25428a
gabriel-portuga/Exercicios_Python
/ex013_reajustesalarial.py
198
3.765625
4
s1 = float(input('Digite o salário do funcionário para aplicar o aumento: R$')) print('O funcionário recebia R${:.2f} e agora recebera com o aumento de 15%, R${:.2f}.'.format(s1, s1+(s1*15/100)))
afcae7c47574afbac769255bbee6b21acb085b54
raubana/Pancake_Script_Tests
/V5/pancake/compiler/subroutine_finder.py
3,755
3.640625
4
""" The purpose of the gotoifyer is to place TYPE_GOTO tokens into the script where they're needed. TYPE_GOTO tokens are necessary for if-else chains, while loops, and breaks to work. """ from tokenizer import Token from constants import * from common import find_endblock_token_index, find_startblock_token_index, increment_gotos_pointing_after_here, decrement_gotos_pointing_after_here from error_format import error_format class SubroutineFinder(object): @staticmethod def process(tokenlist): # First we find all instances of the "sub" term and replace them and their name with a TYPE_SUBROUTINE. # We also do something similar to the "call" term. i = 0 while i < len(tokenlist.tokens): token = tokenlist.tokens[i] t = token.type v = token.value if t == TYPE_TERM : if v == "sub": # we look for a term following this. subname_token = None if i+1 < len(tokenlist.tokens): subname_token = tokenlist.tokens[i+1] if subname_token is None or subname_token.type != TYPE_TERM: error_format(token, "Sub is expected to be followed by the name of the subroutine.") # We remove the sub token. tokenlist.tokens.pop(i) decrement_gotos_pointing_after_here(tokenlist, i) # We then change the type of the second token to TYPE_SUBROUTINE. subname_token.type = TYPE_SUBROUTINE # We expect to find a block following this second token. blockstart_token = None if i + 1 < len(tokenlist.tokens): blockstart_token = tokenlist.tokens[i + 1] print blockstart_token if blockstart_token is None or blockstart_token.type != TYPE_BLOCK_START or blockstart_token.value != BLOCK_START_CHAR: error_format(token, "Sub is expected to be followed by the name of the subroutine and then the block to run.") # We hop to the end of the block and check if there is a return. # If there isn't, then we add one in. index = find_endblock_token_index(tokenlist.tokens, i + 1) last_token = tokenlist.tokens[ index - 1 ] if last_token.type != TYPE_TERM or last_token.value != "return": tokenlist.tokens.insert( index - 1, Token(TYPE_TERM, "return", None, None, 0)) increment_gotos_pointing_after_here(tokenlist, index) i += 1 # We also do something similar to the "call" term. i = 0 while i < len(tokenlist.tokens): token = tokenlist.tokens[i] t = token.type v = token.value if t == TYPE_TERM: if v == "call": # we look for a term following this. subname_token = None if i + 1 < len(tokenlist.tokens): subname_token = tokenlist.tokens[i + 1] if subname_token is None or subname_token.type != TYPE_TERM: error_format(token, "Call is expected to be followed by the name of the subroutine.") # We remove the call token. tokenlist.tokens.pop(i) decrement_gotos_pointing_after_here(tokenlist, i) i -= 1 # We then change the type of the second token to TYPE_GOSUB. subname_token.type = TYPE_GOSUB i += 1 # Next we generate a dictionary of locations for the subroutines. subroutine_locations = {} i = 0 while i < len(tokenlist.tokens): token = tokenlist.tokens[i] t = token.type v = token.value if t == TYPE_SUBROUTINE: subroutine_locations[v] = i+2 i += 1 # Finally we go through and change all of the TYPE_GOSUB values to their appropriate locations. i = 0 while i < len(tokenlist.tokens): token = tokenlist.tokens[i] if token.type == TYPE_GOSUB: if token.value in subroutine_locations: token.value = subroutine_locations[token.value] else: error_format(token, "Call points to a nonexistant subroutine.") i += 1 def process(tokenlist): SubroutineFinder.process(tokenlist)
95f1961772e9d4f09bf91100b0ca469d99fcf156
raubana/Pancake_Script_Tests
/V2/pancake/compiler/blocker.py
1,358
3.765625
4
""" The purpose of the blocker is to substitute TYPE_ENCLOSED tokens with their appropriate TYPE_BLOCK_START/TYPE_BLOCK_END pairs. It also checks that every block token is properly paired. """ from .. constants import * from .. error_format import error_format class Blocker(object): @staticmethod def process(tokenlist): index = 0 while index < len(tokenlist.tokens): token = tokenlist.tokens[index] if token.type == TYPE_ENCLOSED: i = ENCLOSING_CHARACTERS.index(token.value) if i % 2 == 0: # start token.type = TYPE_BLOCK_START else: # end token.type = TYPE_BLOCK_END index += 1 #we need to check that everything is properly paired. stack = [] for token in tokenlist.tokens: if token.type == TYPE_BLOCK_START: stack.append(token) elif token.type == TYPE_BLOCK_END: if len(stack) > 0: start = stack.pop() i = ENCLOSING_CHARACTERS.index(start.value) expected_char = ENCLOSING_CHARACTERS[i+1] if expected_char != token.value: error_format(token, "{val} is missing a starting pair.".format(val=token.value)) else: error_format(token, "{val} is missing a starting pair.".format(val=token.value)) if len(stack) > 0: error_format(stack[0], "{val} is missing an ending pair.".format(val=stack[0].value)) def process(tokenlist): return Blocker.process(tokenlist)
e67b78aa433f74d475e110d7633deeb3ea34afdc
raubana/Pancake_Script_Tests
/V2/pancake/compiler/line_blocker.py
879
3.734375
4
""" The purpose of the line blocker is to block off sections of code that are their own line. This prevents the shunter from reordering sections of code that must remain in a particular order. """ from tokenizer import Token from .. constants import * class LineBlocker(object): @staticmethod def process(tokenlist): start_index_stack = [0] x = 0 while x < len(tokenlist.tokens): token = tokenlist.tokens[x] t = token.type if t == TYPE_EOL or t == TYPE_SEPARATOR: tokenlist.tokens.insert(start_index_stack[-1], Token(TYPE_BLOCK_START,None,None,None)) x += 1 tokenlist.tokens[x] = Token(TYPE_BLOCK_END, None, None, None) start_index_stack[-1] = x + 1 elif t == TYPE_BLOCK_END: start_index_stack.pop() elif t == TYPE_BLOCK_START: start_index_stack.append( x + 1 ) x += 1 def process(tokenlist): LineBlocker.process(tokenlist)
878a3b806fb1efae157947753a116ea04ee76958
reynld/Sorting
/project/recursive_sorting.py
2,429
4.09375
4
### helper function def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements a = 0 b = 0 # since arrA and arrB already sorted, we only need to compare the first element of each when merging! for i in range( 0, elements ): if a >= len(arrA): # all elements in arrA have been merged merged_arr[i] = arrB[b] b += 1 elif b >= len(arrB): # all elements in arrB have been merged merged_arr[i] = arrA[a] a += 1 elif arrA[a] < arrB[b]: # next element in arrA smaller, so add to final array merged_arr[i] = arrA[a] a += 1 else: # else, next element in arrB must be smaller, so add it to final array merged_arr[i] = arrB[b] b += 1 return merged_arr ### recursive sorting function def merge_sort( arr ): if len( arr ) > 1: left = merge_sort( arr[ 0 : len( arr ) // 2 ] ) right = merge_sort( arr[ len( arr ) // 2 : ] ) arr = merge( left, right ) # merge() defined later return arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # TO-DO: implement the Quick Sort function below USING RECURSION def get_pivot(arr, low, high): mid = (high + low) // 2 pivot = high if arr[low] < arr[mid]: if arr[mid] < arr[high]: pivot = mid elif arr[low] < arr[high]: pivot = low return pivot def parition(arr, low, high): index = get_pivot(arr, low, high) value = arr[index] arr[index], arr[low] = arr[low], arr[index] border = low for i in range (low, high+1): if arr[i] < value: border += 1 arr[i], arr[border] = arr[border], arr[i] arr[low], arr[border] = arr[border], arr[low] return border def quick_sort( arr, low, high ): if low < high: pivot = parition(arr, low, high) quick_sort(arr, low, pivot-1) quick_sort(arr, pivot + 1, high) return arr # try it out arr = [2,5,9,7,4,1,3,8,6]; print(arr); arr = quick_sort(arr, 0, len(arr) - 1); print(arr); # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr
412e2228c42ecdd818ffc52c0ebad6ef7e5035ad
vid083/dsa
/Python_Youtube/type.py
241
4.1875
4
value = int(input('Input a value: ')) if type(value) == str: print(value, 'is a string') elif type(value) == int: print(value, 'is a integer') elif type(value) == list: print(value, 'is a list') else: print(value, 'is none')
867bf977490089e4db47ac7a29b7e45d03fd9e1e
vid083/dsa
/Python_Youtube/nested.py
105
3.734375
4
my_list = [[1,2,3], [4,5,6], [7,8,9]] for lists in my_list: for items in lists: print(items)
4423c0ea9eaf1e1b798a5dae8cac898b430f20b1
vid083/dsa
/Python_Youtube/basic_cal.py
248
4.03125
4
n1 = int(input('Enter first number: ')) n2 = int(input('Enter second number: ')) op = input('enter operation to perform: ') if op == '+': print(n1+n2) if op == '-': print(n1-n2) if op == '*': print(n1*n2) if op == '/': print(n1/n2)
a9752d243a82bb69b7a35132b80c53d3236b725b
vid083/dsa
/Greeks4greeks/Recursion/decimal_to_binary.py
117
4
4
# Decimal to binary conversion:- def fun(n): if n>0: fun(n//2) print(n%2) n=int(input()) fun(n)
1d204736ae60d0d946e4cd8bbbff364a7d491e21
Abreu-Ricardo/IC
/clivar.py
872
3.578125
4
# Programador: Ricardo Abreu # Inicio da clivagem de algoritmos from LCS import LCS arquivo = open("entrada.txt", "r") # Criando objetos pept1 = LCS() pept2 = LCS() resultado = None for aux in arquivo: try: if aux[0] == '>': continue else: pept1.string = aux if pept2.string == None: # Primeiro linha do arquivo pept2.string = pept1.string elif pept1.string != pept2.string: resultado = LCS.sub_seq(pept1, pept2) if len(pept2.string) < len(resultado): # Com '>' acha o menor em comum, com '<' o maior em comum pept2.string = resultado except EOFError: ### FIM DO ARQUIVO break resultado.reverse() #Inverter o vetor print(resultado) print("Tamanho da seq:", len(resultado)) print() arquivo.close()
6aa060874a60746319bc27f40fd0a00f9108fdbd
JonReinhold/FrenchLearningTool
/History/rebuild.py
1,210
3.640625
4
import random from fuzzywuzzy import fuzz frenchList = [['yes','oui',0],['no','non',0],['hello','bonjour',0],['not','pas',0],['you','vous',0],['in','dans',0],['dictionary', 'dictionnaire', 0]] orderedFrenchList = [] def wordFeed(): index = random.randint(0,len(frenchList)-1) global word word = frenchList[index] return word[1] linebreak = "*"*45 print(linebreak + "\n Test your knowledge! \n Type H for help or Q to quit. ") print(linebreak) while True: response = input("What is " + wordFeed() + " in English? \n" + "Previously you got this word " + str(word[2]) + "% correct. ") if response == word[0]: print("Correct!") word[2] = 100 elif response.upper() == "Q": print("Exiting tool...") break elif response.upper() == "H": print(linebreak + "\n " "Translate the French words and they will be sorted " "\n and asked again based on how well you know them. \n Press Q to exit.") print(linebreak) else: print("Wrong!") similarity = fuzz.ratio(response, word[0]) print("Your answer was " + str(100 - similarity) + "% off.") word[2] = similarity
839dea017945129886e7ba7b985bcd887cfc42d5
Leviosar/ufsc
/19.2/INE5404/exercicios/ex1/q25.py
205
3.796875
4
from math import sqrt def isPrime(n): for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True for i in range(100001): if isPrime(i): print(i)
5373b0122d3797c39579237ea0c5d4ef42abc5da
HerndonE/CST-311-Intro-to-Computer-Networks
/Homework/Week 9/Programming_Assignment_3_TCP_Client_Server_Team4/PA3_Server_Team4.py
4,132
4.25
4
# Ethan Herndon # Mustafa Memon # Maria Leftheriotis # Alvin Liang # Programming Assignment 3: TCP Client Server ''' -Explain why you need multithreading to solve this problem. Put this in a comment at the top of your server code- For this code you need to have a multithreaded server so you are be able to have two connections that are able to send data to the one server. The two parts are running simultaneously for data to be sent between the connections. The multithreaded server allows for the two connections to communicate with the one server. Each connection has its own thread and one connection does not need to wait for the other connection to end. ''' #TCPCapitalizationServer.py from socket import * import threading #Needed to initiate a multithreaded server import time #For time functions serverName = gethostname() #Computer's hostname, IP address serverPort = 12000 #Port number #Declarations of variables socket_X = -1 socket_Y = -1 message_X = -1 message_Y = -1 message_number = 1 clientFirst = [] # stores the clients in order of when they send a message messageFirst = [] # stores the messages in order of when sent connected_X = 'Client X connected' connected_Y = 'Client Y connected' #We have defined the function get_message to help with the multithreaded server def get_message(clientFrom, clientTo, socketFrom, socketTo): #Able to reach the below variables outside the function global message_number global clientFirst global messageFirst message = socketFrom.recv(1024).decode() clientFirst.append(clientFrom) #Counts up the clients of when they send the message messageFirst.append(message) #Counts up the messages of the order print("Client %s sent message %d: %s" % (clientFrom, message_number, message)) #Tells the order of which client sent what message first and second message_number = message_number + 1 #Counts the number of messages #Create a TCP socket serverSocket = socket(AF_INET, SOCK_STREAM) #Notice the use of SOCK_STREAM for TCP packets serverSocket.bind((serverName, serverPort)) #Assign IP address and port number to socket print ('The server is ready to receive 2 connections....\n') serverSocket.listen(2) #Listens for two connections while (socket_X == -1): #For First Connection socket_X, addr = serverSocket.accept() #Creating First Connection socket for server to accept print ('Accepted first connection, calling it client X') while (socket_Y == -1): #For Second Connection socket_Y, addr = serverSocket.accept() #Creating Second Connection socket for server to accept print ('Accepted second connection, calling it client Y') print ('\nWaiting to receive messages from client X and client Y....\n') #Lets the client know that the server is waiting for messages #Tells the client the connection is connected and lets the client know which connection is which socket_X.send(connected_X.encode()) socket_Y.send(connected_Y.encode()) #Here we create two threads for the connections to be able to run simultaneously thread_1 = threading.Thread(target=get_message,args=('X','Y',socket_X,socket_Y)) thread_2 = threading.Thread(target=get_message,args=('Y','X',socket_Y,socket_X)) #Starting the two threads thread_1.start() thread_2.start() #Let the threads be able to communicate to the server while running simultaneously and then lets the threads close thread_1.join() thread_2.join() #Here we have a format to tell us what client sent the first message #0 is the first connection that sent a message #1 is the second connection that sent a message sentence = "From Server: " sentence = sentence + clientFirst[0] + ": " sentence = sentence + messageFirst[0] + " received before " sentence = sentence + clientFirst[1] + ": " sentence = sentence + messageFirst[1] #Sends the message to the client to show the order of which the server recieved the messages socket_Y.send(sentence.encode()) socket_X.send(sentence.encode()) #Closing both sockets print ('\nWaiting a bit for clients to close their connections') time.sleep(1) #Timer socket_X.close(); #Closing socket_X socket_Y.close(); #Closing socket_Y print('Done.') #Acknowledegment that the sockets closed
e7fe2e55d6f9c213a05a4620b3150d227712d5d7
zhouyuhangnju/freshLeetcode
/Add Binary.py
1,080
3.59375
4
def addBinary(a, b): """ :type a: str :type b: str :rtype: str """ a = list(a)[::-1] b = list(b)[::-1] print a, b carry = '0' if len(a) > len(b): a, b = b, a minlen = len(a) res = [bb for bb in b] for i in range(minlen): if a[i] == '0' and b[i] == '0' and carry == '1': res[i] = '1' carry = '0' elif a[i] == '0' and b[i] == '1' and carry == '1': res[i] = '0' elif a[i] == '1' and b[i] == '0' and carry == '0': res[i] = '1' elif a[i] == '1' and b[i] == '1' and carry == '0': res[i] = '0' carry = '1' if carry == '1': for i in range(minlen, len(b)): if b[i] == '0' and carry == '1': res[i] = '1' carry = '0' break elif b[i] == '1' and carry == '1': res[i] = '0' if carry == '1': res.append('1') res = ''.join(res[::-1]) return res if __name__ == '__main__': print addBinary('11', '1')
bdfc13c8a720a1846ace858343959f44afd41f3a
zhouyuhangnju/freshLeetcode
/LetterCombinationsofaPhoneNumber.py
1,045
3.5
4
def letterCombinations(digits): """ :type digits: str :rtype: List[str] """ digitletterdict = {"0": "0", "1": "1", "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"} # strlist = [] # # for digit in digits: # letters = digitletterdict[digit] # # newstrlist = [] # for letter in letters: # if strlist: # for str in strlist: # newstrlist.append(str+letter) # else: # newstrlist.append(letter) # strlist = newstrlist # # return strlist def subLetterCombinations(currdigits): if len(currdigits) == 0: return [''] return [letters + poststr for letters in digitletterdict[currdigits[0]] for poststr in subLetterCombinations(currdigits[1:])] if len(digits) == 0: return [] return subLetterCombinations(digits) if __name__ == '__main__': print len(letterCombinations("234"))
050611de1ceb8e48c8ee2f79ca721147e5a4f0cb
zhouyuhangnju/freshLeetcode
/Sort Colors.py
1,153
4.21875
4
def sortColors(nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ def quicksort(nums): def subquicksort(nums, start, end): if start >= end: return p = nums[start] i, j, direction = start, end, -1 while i < j: if direction == -1: if nums[j] < p: nums[i] = nums[j] i += 1 direction = 1 else: j -= 1 elif direction == 1: if nums[i] > p: nums[j] = nums[i] j -= 1 direction = -1 else: i += 1 assert i == j nums[i] = p subquicksort(nums, start, i - 1) subquicksort(nums, i + 1, end) subquicksort(nums, 0, len(nums)-1) quicksort(nums) if __name__ == '__main__': colors = [2,1,2,3,1,1] sortColors(colors) print colors