blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
c5b59c7ae576ddd7d7ff8da8fc22415a05c084e8
vidyasagarr7/DataStructures-Algos
/Karumanchi/Sorting/RepeatedElement.py
809
3.78125
4
def check_repeated(input_list): """ O(n^2) solution :param input_list: :return: """ for i in range(len(input_list)): for j in range(i+1,len(input_list)): if input_list[i]==input_list[j]: return True return False def check_repeated_sort(input_list): ...
ee861e0efdb6e5515dd24ad97b15d2fecefde994
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/LinkedList/NthElement.py
877
4.125
4
from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList,Node """ Write a function to get Nth node in a Linked List Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2 Output:...
c71547e58e1d6c3c5d5caade6d1091312a3d6f71
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/PrintDistinctPermutations.py
1,065
4.125
4
""" Print all distinct permutations of a given string with duplicates Given a string that may contain duplicates, write a function to print all permutations of given string such that no permutation is repeated in output. Examples: Input: str[] = "AB" Output: AB BA Input: str[] = "AA" Output: AA Input: str[] = "...
7170a0bff9b961be58ee3253209d6634db808ffd
vidyasagarr7/DataStructures-Algos
/SortingPrac/test.py
165
3.65625
4
def dictTest(d, aVal): for k in d: if d[k] == aVal: return k return None lengths = {'one':3, 0:1, 'two':3} print(dictTest(lengths, 3))
b5b4d136247ccd07ddc1da1a665775f36c1713a4
vidyasagarr7/DataStructures-Algos
/Trees/SearchElement.py
1,191
4.21875
4
from Karumanchi.Trees import BinaryTree from Karumanchi.Queue import Queue def search_element(node,element): """ Algorithm for searching an element Recursively :param node: :param element: :return: """ if not node: return False else: if node.data == element: ...
18858b1ec937e1850ab9ae06c83dc35d15d36c85
vidyasagarr7/DataStructures-Algos
/609-Algos/Lab-2/BubbleSort.py
513
4.28125
4
def bubble_sort(input_list): """ Bubble Sort algorithm to sort an unordered list of numbers :param input_list: unsorted list of numbers :return: sorted list """ for i in range(len(input_list)): for j in range(len(input_list)-1-i): if input_list[j]>input_list[j+1]: ...
a5293bd0704f0e36463e120c1ba40083c9a96876
vidyasagarr7/DataStructures-Algos
/Karumanchi/Trees/MaxSumLevel.py
1,204
3.78125
4
import sys from Karumanchi.Queue import Queue from Karumanchi.Trees import BinaryTree def find_height(root): if not root: return 0 else: return max(find_height(root.get_left()),find_height(root.get_right()))+1 def level_sum(root,level): if not root: return 0 else : que...
2f45a066f0b461b0992094cb8f515ce3f4dd2269
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/ReverseWords.py
420
4.4375
4
""" Reverse words in a given string Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i” """ def reverse_words(string): words_list = string.split(' ') words_list.reverse() return ' '.join(words_list) if __name__=='__m...
e557d262604f55668b4a9ed773d46f8b4fcac3a7
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/Interleavings.py
1,017
3.953125
4
""" Print all interleavings of given two strings Given two strings str1 and str2, write a function that prints all interleavings of the given two strings. You may assume that all characters in both strings are different Example: Input: str1 = "AB", str2 = "CD" Output: ABCD ACBD ACDB CABD CADB ...
84dc81a8e778315e719bb44cff5af69f5906c2a6
vidyasagarr7/DataStructures-Algos
/Karumanchi/PriorityQueueAndHeaps/Heap.py
941
3.75
4
class Heap: def __init__(self): self.heaplist = [] self.size = 0 def parent(self,index): """ returns parent index of a specified index element :param index: :return: """ return index//2 def left_child(self,index): """ returns...
722a8d7641727c407dbbcd1af3a28bb27dcbac6c
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Hash/ReducedForm.py
1,937
4.0625
4
import copy """ Convert an array to reduced form Given an array with n distinct elements, convert the given array to a form where all elements are in range from 0 to n-1. The order of elements is same, i.e., 0 is placed in place of smallest element, 1 is placed for second smallest element, … n-1 is placed for largest...
b132c0b8098f699c574460d19315bc583a53d34a
vidyasagarr7/DataStructures-Algos
/Karumanchi/Sorting/MergeSort2.py
1,199
3.90625
4
def merge(input_list,start,mid,end): """ :param input_list: :param start: :param mid: :param end: :return: """ first=mid-start+1 second=end-mid left = [0]*first right = [0]*second for i in range(first): left[i]=input_list[start+i] for j in range(second): ...
e20c9d2168f9e5c23ef638185ae2e00adbb90dfa
vidyasagarr7/DataStructures-Algos
/Karumanchi/Searching/CheckDuplicates.py
1,726
4.28125
4
from Karumanchi.Sorting import MergeSort from Karumanchi.Sorting import CountingSort def check_duplicates(input_list): """ O(n^2) algorithm to check for duplicates :param input_list: :return: """ for i in range(len(input_list)): for j in range(i+1,len(input_list)): if input...
2ef19d4886644d077c1f53c97f7de400c7019540
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/Rearrange.py
1,096
4.1875
4
""" Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space Given an array arr[] of size n where every element is in range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space. Examples: Input: arr[] = {3, 2, 0, 1} Output: arr[]...
4b1793f6d8c391ad17ecdfabc74702886aa02ebc
vidyasagarr7/DataStructures-Algos
/Karumanchi/Selection/KthSmallest.py
1,531
4.40625
4
from Karumanchi.Sorting import QuickSort def partition(list,start,end): """ Partition Algorithm to partition a list - selecting the end element as the pivot. :param list: :param start: :param end: :return: """ i=start-1 pivot = list[end] for j in range(start,end): if lis...
1b6ade2689898bdecc2d02279703977c7068c6a4
vidyasagarr7/DataStructures-Algos
/Karumanchi/Searching/MissingNumInRange.py
509
3.59375
4
import sys """ Find the missing number in an array containing n numbers in range of X to Y. """ def find_number(input_list,x,y): """ O(n) time :return: """ n = len(input_list) temp = [-sys.maxsize]*(n+1) for i in range(len(input_list)): temp[input_list[i]-x] = input_list[i] f...
6ed24c5a3f16b50e818d455763294de329c94bd1
vidyasagarr7/DataStructures-Algos
/Karumanchi/Sorting/BucketSort.py
822
3.828125
4
def insertion_sort(input_list): for i in range(1,len(input_list)): key = i j=i-1 while j >=0 and key<input_list[j]: input_list[j+1]=input_list[j] j-=1 input_list[j+1]=key return input_list def bucket_sort(input_list,DEFAULT_NUMBER_0F_BUCKETS): bucke...
36ee18af252051ed5f3a6a54f56d63b3ff38c39f
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/ChangeCase.py
474
4.03125
4
""" Change case """ def changecase(input_string): if not input_string : return else : for i in range(len(input_string)): if ord(input_string[i]) & (1<<5): input_string[i] = chr(ord(input_string[i]) & ~(1<<5)) else : input_string[i] = chr(...
faa5f5f0a6ea5b9a642c0941170ee0683a084d91
vidyasagarr7/DataStructures-Algos
/Karumanchi/Searching/Separate01-DNF.py
1,311
4
4
""" Dutch National Flag algorithm - separate 0's and 1's in an array Algo : - start with left = 0 and right - (n-1) - increment till left index untill it is 1 - decrement till right index untill it is 0 - if left < right : swap(left,right) """ def seperate_two_kind(input_list): """ separate 0'...
5d62aac0796d5d45b5d35c8547eff596e67dcc0b
vidyasagarr7/DataStructures-Algos
/Karumanchi/Queue/ReverseFirstK.py
569
3.640625
4
from Karumanchi.Queue import Queue from Karumanchi.Stack import Stack def reverse_first_k(input_que,k): stack = Stack.Stack() count = 0 while count<k: stack.push(input_que.dequeue()) count +=1 while not stack.is_empty(): input_que.enqueue(stack.pop()) for i in range(input_q...
feed79eee2caa02d26e11a26f70715b6395bdf9b
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/DivideNequalParts.py
497
3.921875
4
""" Divide a string in N equal parts Question: Write a program to print N equal parts of a given string. """ def print_n_parts(input_str,n): if not input_str : return else : _list = list(input_str) part = len(input_str)/n for i in range(len(input_str)): if i>0 ...
48b8860303e3be9af88d49c6326a6727a6d42816
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/MaxxIdxDiff.py
1,459
3.609375
4
""" Given an array arr[], find the maximum j – i such that arr[j] > arr[i] Examples: Input: {34, 8, 10, 3, 2, 80, 30, 33, 1} Output: 6 (j = 7, i = 1) Input: {9, 2, 3, 4, 5, 6, 7, 8, 18, 0} Output: 8 ( j = 8, i = 0) Input: {1, 2, 3, 4, 5, 6} Output: 5 (j = 5, i = 0) Input: {6, 5, 4, 3, 2, 1} O...
9e9c4c48985810d5825ad4661b2882a93ce137e8
katie-ring/hacktoberfest-2021-accepted
/Games/numberguessing.py
476
4.03125
4
import random number = random.randint(0, 10000) tries = 0 found = False print("The number is between 0 - 10000") while not found: guess = int(input("Guess: ")) tries += 1 if guess == number: found = True print(f"You found the number {number} after {tries} tries!") elif guess > number:...
1886d22bb2a430d5b63c079944ad4ba1a46a3c5e
katie-ring/hacktoberfest-2021-accepted
/DSA in python/DoWhile.py
233
4.0625
4
# prints all letters except 'a' and 's' i = 0 str1 = 'chetnaganesh' while i < len(str1): if str1[i] == 'a' or str1[i] == 't': i += 1 continue print('Current Letter :', a[i]) i += 1
da943d7606018b2e124129f784c78ba6218e6410
serpent-project/serpent
/src/arkanlor/boulder/generators/utils.py
828
3.9375
4
# -*- coding: utf-8 -*- import numpy def select_tile(tile_list, f): """ selects a tile from tile_list * 2 to make placement more even. however this method would destroy linear order in your tile_list. """ tile_list = tile_list + tile_list l = len(tile_list) # total number of tiles. ...
2cc99073e2f9b4bf49f27a308398384212bd61a8
erija952/project-euler
/python/p9/p9.py
296
3.6875
4
#!/usr/bin/python #Find a + b + c = 1000. for a in range(1,1000): for b in range(1,1000): for c in range(1,1000): if a+b+c == 1000: if a**2 + b**2 == c**2: print "Found " + str(a) + " " + str(b) + " " + str(c) + "a*b*c=" + str(a*b*c)
b3e494f80811909d0b9876514fcee49bde927d2f
erija952/project-euler
/python/p10/p10.py
795
3.546875
4
#!/usr/bin/python import math def get_primes(n): a = [[i, True] for i in range(2,n+1)] sqrtN = int(round(math.sqrt(n))) for i in range(2,sqrtN+1): if a[i-2][1] == True: b= [x*i for x in range(0,n)] c= [x + i**2 for x in b] c[:] = [x for x in c if x<=n] # Remove to large elements for j in ...
d7f32f9626f66394f459babf3b22b0ad229a0203
chenliang15405/python-learning
/study_day01-基础/11_切片.py
553
4.21875
4
""" 切片: 语法: 序列[开始位置下标:结束位置下标:步长] 注意: 不包含结束位置的下标数据 步长是选取间隔,默认步长为1,步长是可选参数 """ str = '0123456789' print(str[2:]) # 如果不写结束,表示到结尾 print(str[:3]) # 如果不写开始,表示从头开始 print(str[:]) # 开始和结尾都不写,表示选取所有 print(str[-3:-1]) # 负数表示从后向前,-3 表示最后一个数 # 如果选取的方向和步长的方法冲突,那么无法选择数据
4ddc2187b4ba8c7bdfa2cc0acb2396acd517ee6d
chenliang15405/python-learning
/study_day06-web服务器/正则表达式/01_正则表达式模块的使用.py
1,415
3.703125
4
""" 正则表达式模块 re match 匹配的是字符串的开头,只要符合即可,并不管后面如何 re.match(正则表达式, 需要处理的字符串) . 匹配任意字符,除了\n \D 匹配非数字,不是数字 \s 匹配空白,空格、tab \S 匹配非空白 \w 匹配单词字符,a-z A-Z 0-9 _ \W 匹配非单词字符 [] 用来匹配或的关系 a[bcd]e abe ace ade | 也可以用来匹配或的关系 abc|ace|bce abc 表示匹配到任意一个即可 .+ 表示匹配任意字符1次到无数次 .+? 表示匹配到任意字...
de78157337b2849f1bde3dceda7ce00ff7325e79
chenliang15405/python-learning
/study_day07-python高级语法/06_创建property其他属性的方式.py
1,154
4.21875
4
""" 在对象中,可以通过定义property的三种方式,来触发属性的更新等情况并进行计算: 1。 获取数据: 必须返回一个值,并且没有参数,可以通过计算返回一个值 @property def price(self): return 100 2. setter: 通过@<propertyname>.setter的定义形式,当给property装饰的变量赋值的时候触发此方法 @price.setter def price(self, value): # 传递的参数是赋值时的参数 ...
cda7536a53659b57fc85f2399b764f7e0e11fec6
chenliang15405/python-learning
/study_day03-面向对象/08_多继承.py
1,187
4
4
""" 多继承: 子类可以继承多个父类,并拥有所有父类的属性和方法 语法: class 子类名(父类名1,父类名2,...) pass 多继承出现的问题: 如果多个父类中有相同的方法或者属性,那么应该避免使用多继承 虽然不报错,但是会根据方法的调用顺序来调用一个父类中的方法和属性 Python中的mro ---- 方法搜索顺序 __mro__ 可以查看方法的搜索顺序,在多继承时,可以查看,方法和属性的搜索顺序 该方法是类的方法 新式类和旧式类: 新式类: 创建的类以Object类为父类的类,dir()函数查看该类的对象,会提供一些...
c7e45ee0ceb6dcb6edd694ef58b8eaf10cfcac41
chenliang15405/python-learning
/study_day03-面向对象/文件/01_文件的基本操作.py
2,059
4.40625
4
""" python中操作文件的函数/方法: 1. open 函数: 打开文件,并返回文件操作对象 2. read 方法: 将文件内容读取到内存, 在同一个打开的文件中,读取一次,文件的指针会指向文件末尾,再次读取就读取不到数据 3. wirte 方法: 将制定内容写入到文件 4. close 方法: 关闭文件 打开文件的方式: 1. open() 函数: 默认的是以只读方式打开文件,只读不可写 2. open("文件名", "打开方式") 以指定的方式打开文件 打开方式: r : 默认模式,以只读方式打开 w: 只...
c1bb9c1df341e944056dddce9476b99ef680feff
chenliang15405/python-learning
/study_day04-网络编程/02_绑定端口接收udp数据.py
1,083
3.890625
4
""" 指定Ip和端口,接收socket的发送数据 udp在客户端和服务端都是需要绑定端口和Ip tcp经过了3次握手和4次挥手,所以客户端不需要绑定端口和ip,服务端需要绑定 tcp是面向链接的通信,udp是面向无连接的通信 """ import socket def main(): # 创建socket udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 绑定本地信息, 这里相当于注册时自己的信息到本地 local_addr = ("", 8080) udp_socket.bind(local_addr...
a08410de67f1cec8795f3a9dd38c749e80b8d541
chenliang15405/python-learning
/study_day04-网络编程/03_udp聊天器.py
821
3.765625
4
""" 使用socket实现udp聊天器 udp 协议相对来说会丢包,所以不是非常安全 """ import socket def send_msg(udp_socket): """发送消息""" dest_ip = input("请输入发送的IP:") dest_port = int(input("请输入发送的Port:")) input_data = input("请输入发送的消息:") udp_socket.sendto(input_data.encode("UTF-8"), (dest_ip, dest_port)) def receive_msg(udp_soc...
8a427daf720cf366865379780eed6da7d529f3c4
chenliang15405/python-learning
/study_day02-基础进阶/03_局部变量和全局变量.py
990
4.03125
4
""" 1、定义 局部变量: 在函数内部定义的变量,只能在函数内部使用 全局变量: 函数外部定义的变量,所有函数内部都可以使用全局变量, 应该讲全局变量定义在所有函数上方 2、生命周期: 局部变量: 函数执行时创建,函数执行完毕,局部变量会被系统回收 全局变量: 3、注意: 在函数内部不能直接修改全局变量的值,如果使用赋值语句,那么相当于在函数中定义了一个局部变量 4、在函数内部修改全局变量的值: global 关键字 global 变量 变量 = value 5、全局变量的命名: 增加前缀: g_ 或者 gl_ """ num = 10 def test1(): ...
ec13eb25e346e8eb3bfb9f4d83717cc522c77ad7
chenliang15405/python-learning
/study_day05-多任务/线程/04_多线程共享全局变量.py
758
3.9375
4
""" 多线程共享全局变量, 只要有一个线程中修改了全局变量,那么其他线程是共享的 """ import threading import time g_num = 100 def test1(): global g_num g_num += 1 print("----test1------ %d" % g_num) def test2(temp): temp.append(33) print("----test2------ %d" % g_num) g_nums = [11, 22] def main(): thread1...
4f19a18a6f2e14db6ed754dc1df5d5293bf44483
chenliang15405/python-learning
/study_day05-多任务/进程/02_进程间通信Queue.py
851
3.796875
4
""" 进程是相互隔离的资源,所以通信的方式需要借助Queue队列完成 关于Queue的使用 """ import multiprocessing def download_from_web(q): data = [11, 22, 33] for temp in data: q.put(temp) print("下载器已经将数据下载完成") def analysis_data(q): waitting = list() # 从队列中取出数据 while True: if q.empty(): break ...
776dcedac5ed3d4be507b17cec2d716b1ff33ba0
chenliang15405/python-learning
/study_day06-web服务器/正则表达式/03_正则的匹配分组.py
1,064
3.6875
4
""" 匹配分组: 可以通过分组的方式获取到匹配正则的对应数据 | 匹配左右任意一个表达式 (ab) 将括号中的字符作为一个分组,可以通过正则匹配到的返回值 .group(num) 获取匹配到的括号中的数据,num是第几个括号中的数据 \num 引用分组 num 匹配到的字符串 (?P<name>) 分组起别名 (?P=name) 引用别名为name分组匹配到的字符串 """ import re ret = re.match(r"^([a-zA-Z0-9_]{4,20})@(163|126)\.com$", "laowang@126.com") # 获取匹配到的数据 print(re...
126c0c4c2f2fc5669f29240d59e4e2152b1dbf84
bomin0830/python
/CH9/9-7.py
203
3.796875
4
""" 30이하의 정수를 입력하면 입력한 정수보다 큰 수 부터 30까지의 모든 정수를 출력하는 프로그램 """ num=int(input('적어:')) for i in range(num,31): print(i)
214c8dde6f91932667c61575f4ab35a15869fa4d
bomin0830/python
/CH9/9-10.py
226
3.671875
4
""" 양의 정수들의 덧셈인데 0을 입력하면 종료인데 누를거 다더할거임 """ sum=0 while(True): n=int(input('아:')) sum=sum+n if n==0: print('총합은',sum,'입니당') break
006a52edd4e94d19499083b2747cc630d7ecf867
shoemakercha/CSE_My_PyFiles
/Hello_World.py
1,226
4.09375
4
from __future__ import print_function # The above line imports Python 3.0 printing - NEVER FORGET THE ABOVE LINE OF CODE! print("Hello World") print("2 + 3") print(2 + 3) print(Hello World) print("Your new score is", 1030 + 10) print("Your new score is", "1030 + 10") print("Your new score is," 1030 + 10) print("Your ne...
87ca726839b27ff9acfcc97f5d89f81693dc051d
songsonggithub/nesting
/analysis_tools/rotate_polygon_test.py
1,615
3.625
4
def get_polygon_bounds(polygon): """ :param polygon: [{'x':, 'y': }, {'x':, 'y':}, {'x':, 'y':}, {'x':, 'y':}] :return: 返回左下角的点(x, y),以及长度和宽度(length, width) """ if polygon is None or len(polygon) < 3: return None x_max = polygon[0]['x'] x_min = polygon[0]['x'] y_max = polygon[...
dcc3341ffa7ab38eeda46991dcb4c7214e80f827
marcosf63/introTele
/gera_sinal.py
1,387
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Trabablho da Disciplina Introdução as Telecomunicações Aluno: Marcos Antonio Fernandes de Oliveira Professor: Anderson B Rodrigues """ from random import randint import matplotlib.pyplot as plt def gera_sinal(n): """ função que recebe um numero inteiro como en...
60ad481728628d5d11debb5a2073f49bed4df247
buxuele/algo_snippet
/没意思/1450.py
379
3.515625
4
# -*- coding: utf-8 -*- # author: fanchuang # DateTime:2021/2/18 0018 13:26 # contact: fanchuangwater@gmail.com # about: def solution(): startTime = [1, 2, 3] endTime = [3, 2, 7] queryTime = 4 ret = 0 for i, j in zip(startTime, endTime): # print(i, j) if queryTime >= i and queryT...
0ddcaafb1e23497c4b7dc89375ab42b82f255c97
buxuele/algo_snippet
/基本数据结构/zip_star.py
553
3.953125
4
### python3 zip()的用法 # 1. 基本操作。按照顺序对多个可迭代对象打包。 a = [1, 2, 3] b = [4, 5, 6] T = list(zip(a, b)) print(T) # [(1, 4), (2, 5), (3, 6)] # 2. zip(*),是解压。 g = zip(*T) print(list(g)) # [(1, 2, 3), (4, 5, 6)] # 3. 下面是一个很好的写法 def better_group(nums, n): iters = [iter(nums)] * n # 这里的 n 个迭代器,实际上指向的是同一个地址! ret = zi...
a60d81d7b3e9363b61b912d36080e6eec982f705
buxuele/algo_snippet
/junk/127_word_dragon.py
313
3.84375
4
# author: fanchuangwater@gmail.com # date: 2020/4/12 下午9:59 # 目的: # beginWord = "hit" # wordList = ["hot","dot","dog","lot","log","cog"] # nums = [1,1,1,1, 1, 2, 2, 2, 2,2,3] i = 0 while i < len(nums) - 1: if nums[i] == nums[i+1]: nums.pop(i) print(nums) i += 1 print("in the end :", nums) ...
111ffbc2948be7dc771b53c2bb6e38b7578d9a3c
buxuele/algo_snippet
/基本数据结构/Queue.py
558
3.71875
4
import queue # queue 单向队列,先进先出 """ 1. 注意是包的导入, import queue 2. q = queue.Queue(2), 初始化可以指定队列的大小 3. empty(), 判空 4. full(), 是否满了 5. put(), 添加一个元素 6. get(), 获取一个元素 7. qsize(),获取元素的个数 """ q = queue.Queue(2) q.put([1, 2]) a = q.get() q.put([3, 4]) b = q.get() print(a) print(b) print(q.qsize()) c = q.get() print(c) ...
c16e4c17e76817138b26119b56c6b51eb886fcfa
buxuele/algo_snippet
/junk/78_sub_list.py
267
3.75
4
# author: fanchuangwater@gmail.com # date: 2020/5/3 下午2:13 # 目的: 一个列表的所有子集 import itertools nums = [1, 2, 3] ret = [] for i in range(len(nums)+1): temp = itertools.combinations(nums, i) for t in temp: ret.append(list(t)) print(ret)
93f908131aa241445317e5b131b7a1b948608719
buxuele/algo_snippet
/基本数据结构/Linked_List.py
2,433
3.96875
4
# 链表的实现及其基本操作方法 class Node: def __init__(self, item=None, next=None): self._item = item self.next = next def ___repr__(self): return str(self._item) class LinkedList: def __init__(self): self.head = None self.length = 1 def isEmpty(self): return self...
83faa60b95e81cac0d674ec1653d109fa1129b5c
buxuele/algo_snippet
/junk/5362.py
310
3.5625
4
# author: fanchuangwater@gmail.com # date: 2020/4/4 下午11:12 # 目的: s = "annabelle" k = 2 def real(w): t = len(w) // 2 if t == 1: return True else: return w[:t] == w[-t:][::-1] # 分成3部分或者是4部分怎么做呢 for i in range(1, len(s)): if real(s[:i]): k -= 1
6ab9f4fc4c47cccd475e0ae6ee5d472133103020
buxuele/algo_snippet
/没意思/561.py
201
3.765625
4
nums = [6,2,6,5,1,2] # nums = [1,4,3,2] # 没意思的。 nums.sort() # print(nums) # # ret = 0 # for i, j in enumerate(nums): # if i % 2 == 0: # ret += j # # # print(ret) print()
c99e277540f92a5f2ab3e4172daa25301bbca3cd
buxuele/algo_snippet
/junk/42_catch_rain.py
280
3.5
4
# author: fanchuangwater@gmail.com # date: 2020/4/4 下午2:55 # 目的: 大名鼎鼎的接雨水问题。 height = [0,1,0,2,1,0,1,3,2,1,2,1] # 根据提示的思路。先找到最高点,然后往2侧搜索。 left = 0 right = len(height) - 1 mx = height.index(max(height)) print(mx)
6cf395eb1b2f4c95da7954b100e6ffe873e368c5
buxuele/algo_snippet
/279.py
495
3.5625
4
# -*- coding: utf-8 -*- # date: 2021/2/17 0017 # author: fanchuang # contact: fanchuangwater@gmail.com # about: # 这道题其实是很有意思的。只是我现在不能去多花时间去做。 # 感觉像是 DP 或是 回溯算法 n = 12 def solution(): # 还是需要用到动态规划。 ret = 0 status_value = [] # for i in range(1, n+1): # pass # [0, 1, 4, 9, 16, 25, 36, 49...
1ca186d2fc82295c69dd5ab88c767024412a147d
buxuele/algo_snippet
/junk/209_02_binary.py
1,310
3.5
4
# author: fanchuangwater@gmail.com # date: 2020/4/4 上午1:57 # 目的: 尝试使用二分法来做。 # https://leetcode-cn.com/problems/minimum-size-subarray-sum/comments/ # 需要再看看。 s = 5 nums = [2,3,1,2,4,3] left, right, res = 0, len(nums), 0 # 这个函数才是关键,它是用来判断是否可以缩小当前这个窗口的大小的。 def helper(size): sum_size = 0 for i in range(len(nums))...
706d32805925b2d80a4c9c1be436dd3f19bd8d11
buxuele/algo_snippet
/二叉树/sub_tree.py
1,955
4.28125
4
# python3 实现二叉树 # 最好是参考这篇再看一遍: # https://www.cnblogs.com/maxiaonong/p/10060086.html class Node: def __init__(self, element, lchild=None, rchild=None): self.element = element self.lchild = lchild self.rchild = rchild class Tree: def __init__(self, root=None): self.root = root ...
1731435e09548a8025f3218f9ee8539f21458263
buxuele/algo_snippet
/junk/168_excel_name.py
504
3.546875
4
# author: fanchuangwater@gmail.com # date: 2020/5/28 上午11:11 # 目的: # # for i in range(1, 27): # print(chr(i+64)) # n = 780 # # a = s // 26 # b = s % 26 # print(a) # print(b) ret = "" while n > 26: # 这里需要检查一下是否能整除的情况。。。 if n % 26 == 0: # 那么就少进位1, 并且在结尾添加上Z ret += chr(26+64) n = n...
422ff37446f9785956ea3460dfd9c38cd3246292
cloeffler745/Database_source_code
/Venn_diagram_maker/Venn_Diagram_maker.py
5,331
3.5
4
# BOILER PLATE -------------------------------------------------------------------------------------------------------------------------- # FUNCTIONS ----------------------------------------------------------------------------------------------------------------------------- # This function takes a file, and a strin...
fb5a4841f45c632fc293f9652a21319864422dbb
DmitryMorozov0/MorozovDmitriy
/python/2.4.py
442
3.9375
4
# -- coding: utf-8 -- a=int(input("Расстояние между рядами: ")) b=int(input("Расстояние между дырочками в ряду: ")) l=int(input("Длина свободного конца шнурка: ")) n=int(input("Количество дырочек в каждом ряду: ")) def s(a,b,l,n): return (n-1)*b*2 + (n*2)*a + l*2 print("Искомая длина шнурка: ", s(a,b,l,n))
07a547ca252eeff5a330ddf6aea395109e97429f
DmitryMorozov0/MorozovDmitriy
/октябрь/6.py
201
4.09375
4
# - - кодировка: utf-8 - - n = int(input()) def find_factorial(n): f=1 for t in range(1, n+1): f = t*f return (f'{n}! = {f}') f = find_factorial(n) print(f)
4c6969b8ea809a9b59e4342a951ed0ee571f8ae4
DmitryMorozov0/MorozovDmitriy
/октябрь/4.py
141
3.671875
4
# - - кодировка: utf-8 - - N = int(input()) s = 0 # сумма for t in range(N): s += int(input()) print(s)
a944c5964f0338dc052beeac7549881a2bbe75e2
Dellking98/Python
/Coin_Tosses.py
1,412
3.75
4
def coing_tosses(Tosses): head = 0 tails = 0 for attempt in range(1,Tosses): import random random_number = random.random() if random_number < 0.5: head += 1 print "Attemp #" ,str(attempt)+": Throwing a coin.. It's a head!...Got" , str(head), "head(s) so far a...
2ac4a3e8b3dcc83e054ac688374d548b16fdb326
educa2ucv/Material-Apoyo-Python-Basico
/Codigos/4-Ciclos/Ejercicio2.py
452
4.03125
4
""" Ejercicio 2: Escribir un programa en el que se pregunte al usuario por una frase y una letra, y muestre por pantalla el número de veces que aparece la letra en la frase. """ frase = input("Ingrese una frase, por favor: ") letra = input("Ingrese una letra a contar: ") cont = 0 for elemento in frase: ...
638c098b21f50c29ddbb8136459117a099677acc
educa2ucv/Material-Apoyo-Python-Basico
/Codigos/2-TiposDeDatos/Logico.py
579
4.375
4
""" En Python tenemos las siguientes operaciones logicas y operandos logicos: Mayor estricto (>) Mayor o igual (>=) Menor estricto (<) Menor o igual (<=) Igualdad (==) Diferente (!=) Y lógico (and) O lógico (or) Negación lógico (not) """ """e...
2211bc642f1ec265eb394dc611dc1e1173e2714c
KevinZWong/Kevin_PythonClasses
/Assignment5/Assignment5a.py
475
4.03125
4
import math print("5.18") def primeFactors(n): list1 = [] while n % 2 == 0: list1.append(2) n = n / 2 for i in range(3, int(math.sqrt(n))+1, 2): while n % i == 0: list1.append(i) n = n / i if n > 2: list1.append(n) return l...
f339deb9e0f5b88435be89c7177266dc08fd80bb
KevinZWong/Kevin_PythonClasses
/ExtraCredit/AssignmentExtra.py
378
3.671875
4
total = float(input()) dollars = total//1 quarters = total//0.25 dimes = total//0.10 nickels = total//0.05 pennies = total/0.01 print("The maximum amount of dollars", dollars) print("The maximum amount of quarters", quarters) print("The maximum amount of dimes", dimes) print("The maximum amount of nickel",...
c70ed9bf923eb405993b8aa9bc2ba56eb5b8324a
KevinZWong/Kevin_PythonClasses
/Assignment3/Assignment3b.py
124
3.90625
4
print("3.6") print("Enter a ASCII code") ASCII_Num = int(input()) ASCII = chr(ASCII_Num) print("The character is",ASCII)
4cd3c5a0c073e92719a05c242975cd29896a3f4e
KevinZWong/Kevin_PythonClasses
/Assignment6/Assignment6b.py
1,837
3.78125
4
# Return true if point (x2, y2) is on the left side of the # directed line from (x0, y0) to (x1, y1) def leftOfTheLine(x0, y0, x1, y1, x2, y2): result = (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0) if result > 0: return True else: return False def leftOfTheLine2(x0, y0, x1, y1, x2, y2...
f536e710f4bc7c81085b7d19cc88a2b459a4c80e
KevinZWong/Kevin_PythonClasses
/Midterm/KQ3.py
525
4.0625
4
sides = input("Enter a point: x1,y1: ") list1 = [] list1 = sides.split(",") list1[0] = float(list1[0]) list1[1] = float(list1[1]) if list1[0] > -5 and list1[0] < 5 or list1[0] == -5 or list1[0] == 5: xinside = "Yes" else: xinside = "No" if list1[1] > -2.5 and list1[1] < 2.5 or list1[1] == -2.5 or li...
2e38e7bcee96a0c966e8ef6ff3cacdfb1091c326
george-mammen/IEEE-Bootcamp.py-Hackerrank
/N Odd Number.py
214
4.03125
4
""" Qs:Read N from input and print the first N odd numbers Sample Input 0 3 Sample Output 0 1 3 5 """ Code : num=int(input("")) for i in range(1,num+num,2): if((i % 2) ==1): print("{0}".format(i))
1cf1bd7ff718d01fe7a29ffe9fbddace4bbe750c
jinhussein96/fill-missing-data-in-a-dataset
/number of total vaccinations.py
786
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 25 00:09:44 2021 @author: JIN_HUSSEIN """ import datetime import pandas as pd ''' using the dataset that i produced from the 4th question ''' data = pd.read_csv("country_vaccination_stats1.csv") data = data[["country", "date", "daily_vaccinations", "vaccines...
270b0e19adea8d97c788ff31305616b65c516f76
shenzekun/leetcode
/Sqrt_x.py
844
4.15625
4
""" 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。 思路: 由于 x^2是单调递增,因此使用二分法 """ class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ ...
3cb424eca754352fc95b7c5ff2d1e9d708108908
shenzekun/leetcode
/Valid_Parentheses.py
900
3.859375
4
""" 20. 题目:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true 解题思路: 利用栈去实现。 """ class Solution(object): def isValid(sel...
4003a33f106082b016ee16537a7ad9558e82c2a2
shenzekun/leetcode
/Binary_Tree_Level_Order_Traversal_II.py
1,120
3.90625
4
""" 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其自底向上的层次遍历为: [ [15,7], [9,20], [3] ] 思路: 还是使用 dfs """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # ...
c9f7a46f6d2c1ea02c9c541606b4d92485beca5a
ceon97/Leetcode
/TwoSum.py
522
3.625
4
#Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. #You may assume that each input would have exactly one solution, and you may not use the same element twice. #You can return the answer in any order class Solution(object): def twoSum(sel...
28f10788c5b87969eaf7796a0528d3191f4a7dc4
UngTDavid/cssi-labs
/python/labs/shopping-list-app/loopPlayground.py
233
4.0625
4
print("Hello World") characterNum = 1 myString = raw_input("Give me a string loop though: ") for character in myString: print("This is letter number %s" % (characterNum)) characterNum = characterNum + 1 print(character)
5bba3528fd27cc78e03241aaffa4a4a7670e3b6d
gyogeshchandra/design_pattern
/singleton.py
571
3.703125
4
class Singleton: __instance = None @staticmethod def get_instance(): if Singleton.__instance == None: Singleton() else: return Singleton.__instance def __new__(cls): if Singleton.__instance != None: raise Exception("This class is singleton") ...
6a8d13af249934bc53f11e23592352a9b6a5e15c
jrodriguezballester/inicioPython2
/ejercicio1.py
471
4.09375
4
'''ejercicio 1 escribir una función max_in_list() que tome una lista de números y devuelva el más grande.''' # idea: que tome el primero y compare con el siguiente def max_in_list(numeros): mas_grande = numeros[0] for numero in numeros: if mas_grande <= numero: mas_grande = numero re...
17cf37f48ece134f96eb6d6f0fdcd68091415a3c
EricUcla16/Selenium-Python
/Demo Test Scripts/Basics - python capabilities.py
3,063
4.125
4
#this is how you write a comment print("Hello World") y = "hello " x = "world" print(y + x) x = 5 y = 10 print(y + x) if 10 > 5: print("10 is greater than 5") def summation(a, b): print(a+b) print("this sum was printed from a function") summation(x,y) x = 5 y = 2.5 z = 4j print() print() prin...
5b56503b5a4f18d259d6be8bbe1cb4e0695ed1bc
imran9891/Python
/Lambda.py
370
3.578125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # One line functions print(list(map(lambda x:x**2, [1,2,3]))) print(list(map(lambda x:x**2, (10,2,3)))) print(list(filter(lambda x:x % 20 == 0, [10,20,30,40,50]))) print(reduce(lambda acc,item : acc + item, [1,2,3], 0)) # List Sorting via index 2 a = [(0,2),(4,-3),(9,9...
32de35bdddabc49a95d580f5d746e3db5d384813
imran9891/Python
/Booleans.py
787
3.796875
4
#!/usr/bin/env python # coding: utf-8 # <h3 align="center">Booleans # </h3> # In[ ]: is_cool = True is_cool = False print(bool(-0)) # F print(bool(0)) # F print(bool(1)) # T print(bool(0.5)) # T print(bool('0')) # T print(bool('True')) # T print(bool('False')) # T print(bool(False)) # F print(bool('any random thing...
0f1edc71a026eac62eb4b641c0bd9ede2a98bbee
imran9891/Python
/PyFunctionReturns.py
882
4.125
4
#!/usr/bin/env python # coding: utf-8 # <h3 align="center">Function Return</h3> # In[ ]: def sum1(num1, num2): def another_func(n1,n2): return n1 + n2 return another_func def sum2(num1, num2): def another_func2(n1,n2): return n1 + n2 return another_func2(num1, num2) print(sum1(10,...
0675b277f60ac259976daaa00f77e5f5113c6c02
imran9891/Python
/String Slicing.py
640
4.03125
4
#!/usr/bin/env python # coding: utf-8 # <h3 align="center">String Slicing</h3> # In[3]: name = "0123456789" # we can do the exact same thing on list and tuple # name = (0,1,2,3,4,5,6,7,8,9) # name = [0,1,2,3,4,5,6,7,8,9] # [start:stop:stepover] print(name[1]) print(name[-0]) print(name[-1]) print(name[2:]) print(...
209e2e6a109321547f040c3be12894972248536b
imran9891/Python
/Decorators.py
344
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: def hello(): print("hello!") greet = hello del hello # here the function is not deleted, just the keyword, because greet is still pointing to the # function memory and python has not deleted it # hello() # this will give error, because it has been delete...
6c0229bd77b8f4eed173d625dcc5cfddd834038d
imran9891/Python
/MapFilterZipReduce2.py
764
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: from functools import reduce # 1. Capitalize all of the pet names and print the list my_pets = ['sisi','bibi','titi','carla'] print(list(map(lambda x: x.upper(), my_pets))) # 2. Zip the 2 lists into a list of tuples, but sort the numbers from lowest ot highest my_stri...
51cab64c0699e862fbf02d43e1893d4dc0ebdda5
imran9891/Python
/Class Single Inheritance.py
439
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Single Inheritance Example Date is parent class and Time is Child Class: class Date(): def get_date(self): return '2020-07-10' class Time(Date): def get_time(self): return '18:11:20' dt = Date() print(dt.get_date()) # print(dt.get_tim...
dcdbe1f39ae3fb2eeaf8fff877feada6343bcf06
imran9891/Python
/Highest Even.py
266
3.96875
4
#!/usr/bin/env python # coding: utf-8 # <h3 align="center">Highest Even</h3> # In[ ]: def highest_even(li): evens = [] for item in li: if item % 2 == 0: evens.append(item) return max(evens) print(highest_even([10,2,3,14,88,11]))
dad81396f5268946ef390dc3138f7d8968d3b5c6
Angeliquesiu/coding_challenges
/oddNum.py
1,125
4.0625
4
# ODD NUMBERS # count the odd numbers in a range # range is low, high (inclusive) def countOdds(low, high): return (high + 1) // 2 - low // 2 # return minimum number of operations needed for n to become 1 # if n is even, replace with n / 2 # if n is odd, replace with n + 1 or n - 1 # input: n = 65535 # output: 17...
8ddeb964ee3dc77bdd7154ca5a250de627317824
utsavraj/COMP3234
/A1/TCP/FTserver.py
1,600
3.703125
4
#!/usr/bin/python import socket import sys def main(argv): # set port number # default is 32341 if no input argument port_number = 32341 if len(sys.argv) == 2: port_number = int(sys.argv[1]) # create socket and bind sockfd = socket.socket() try: sockfd.bind(("", port_number)) except socket.error as err: ...
102ab4bd5d931b41d69b614e4d27a44987f2c6c6
julissaf/Python-Code-Samples-2
/module 5 (2b).py
192
4.15625
4
# Julissa Franco # February 14, 2019 # The purpose is to wirte a loop that lists numbers and its squares numbers= [12,10,32,3,66,17,42,99,20] for x in numbers: print (x) print (x**2)
3c7561a37b7ce2d08da28fbeef2ad4e7a3fcd8eb
giTomas/python3_learning
/time/ex1.py
456
3.71875
4
#!/usr/bin/python from datetime import datetime from time import sleep def l_cycle(per, int): period = per time_start = datetime.now() time_diff = 0 while time_diff != period: time_now = datetime.now() time_diff = (time_now - time_start).seconds print('lopp is running {}secs'.f...
74bd64ff672b3a10a20dff764c6696a1006c9f84
nafeesdipta/MachineLearningWork-
/Udemy Based ML Works/multiple_linear_regression.py
2,356
3.984375
4
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('/home/nafees/PycharmProjects/Test/Udemy Based ML Works/DataSet/Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # En...
0dceaea7576c2082d8bdb5eed0833fafd702b68c
kadintt/arithmetic
/arithmetic.py
2,108
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import numpy as np def binary_search(list, item): low = 0 high = len(list) - 1 while low <= high: mid = int((low + high)/2) guess = list[mid] if guess == item: return mid if guess > item: hi...
b2c3ae600699c3daa55e1dd57a2e7cecc78029bd
pierrecamilleri/advent_of_code_2020
/day7/solution_day7.py
2,229
3.671875
4
import re def parse_rule(rule): """ Parse a rule based on word order and number of digits found in the rule. Returns a dictionary `{containing color: {contained color 1: #, ...}}` """ digits = [int(d) for d in re.findall("\d", rule)] n_bag_types = len(digits) rule_splitted = str.split(r...
e0d4bc82e115d5dc2c96f8c58dd384310046f21d
khangvtran/Spotify-Fellowship-Assessment
/problem3.py
2,875
3.78125
4
''' Khang Vinh Tran 06/12/2018 Python 3 Question 3 -- changePossibilities(amount,amount): Your quirky boss collects rare, old coins. They found out you're a programmer and asked you to solve something they've been wondering for a long time. Write a function that, given an amount of money and an array of coin denomin...
267206223e2701c82b30ed05943dbaca1f04011c
RogerLei710/COMP-576-A0
/string_to_num.py
176
4.0625
4
while True: strInput = input("Enter a string\n") if strInput == "-1": break for c in strInput: print(ord(c) - ord('A'), end=' ') print("\n")
0eb8d63d6979c6c3ccf5a334dd4e2190d2211af5
saini-dhiraj/Algorithms
/Warmup/lcm.py
342
3.609375
4
# python3 a, b = map(int,input().split()) def gcd(a, b): assert 0 <= a <= 2 * 10 ** 9 and 0 <= b <= 2 * 10 ** 9 if b == 0 : return a c = a % b return gcd(b, c) def lcm(a,b): l=0 if a> b: l = gcd(a,b) else: l = gcd(b,a) q=a*b return q...
80f7654b2b8c6234dc730bdf8618b86229797175
cs-capstone/yerevan-transportation
/queue.py
437
3.765625
4
class Queue: def __init__(self): self.__size = 0 self.__data = [] def __len__(self): return self.__size def enqueue(self, item): self.__data.append(item) self.__size += 1 def dequeue(self): item = self.__data.pop(0) self.__size -= 1 retu...
d7c4c21563a09c85d82d652626eb7f5230b9254d
khairooo/Learn-linear-regression-the-simplest-way
/linear regression.py
1,829
4.4375
4
# necessary packages import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error,r2_score # generate random data-set np.random.seed(0) # generate 100 random numbers with 1d array x = np.random.ran...
b8f4c8ce7be89a1b3e227974d8030f63c10a54cd
EricSchles/DataScienceBootCamp
/pandas_tutorial.py
2,455
3.765625
4
import pandas as pd import pandas.io.sql as psql import sqlite3 import numpy as np #this could be a guide: http://pandas.pydata.org/pandas-docs/stable/indexing.html #time series: http://pandas.pydata.org/pandas-docs/stable/computation.html #missing data: http://pandas.pydata.org/pandas-docs/stable/missing_data.html #gr...
5c41e69ab0405fcb7b288899c9a66fda0e5bbc42
negeend/acorn-runner
/e2e tests/run.py
3,093
3.78125
4
""" Author: Negeen Daudi Date: 20 May 2020 Purpose: This file is the entry point of the program. """ from game import Game from player import Player import game_parser from grid import grid_to_string import os import sys try: filename = sys.argv[1] except IndexError: ## Chec...