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 |
|---|---|---|---|---|---|---|
76e362a58e0658d88a410711a0b711a5756bf00f | weipanchang/project | /any_base_convert.py | 1,403 | 3.78125 | 4 | #!/usr/bin/env python
import unittest
import math
def decimal_to_binary(n, base):
l = [int(math.pow(base, i)) for i in range(int(math.log(n, base)), -1, -1)]
def recursive(n, i):
if i == len(l)-1:
return str(n)
else:
#if n >= l[i]:
x = str(n // l[i... |
c32c240e044fea0f624d670bfecb7f405abbb860 | weipanchang/project | /Bulbsort.py | 378 | 3.71875 | 4 | l = [6,5,4,3,2,1]
# for i in range(len(l) -1):
# for j in range(len(l) - i -1):
# if l [j] > l [j + 1]:
# l[ j], l[j + 1] = l[j+1], l[j]
#
def quicksort(l):
if not l:
return []
else:
return quicksort([a for a in l if a < l[0] ]) + [l[0]] + quicksor... |
7cbd4f7ae9c546cfff41af13d8e116d0ff02e9c2 | SINAEEE/pystudy | /function/func_ex.py | 2,884 | 3.53125 | 4 | # Func_ex.py
# 함수에 관한 코드
def dummy(): #이런경우 pass가 없으면 파이썬이 내부블록을 찾지못함
pass
def print_hello():
print("Hello Python")
def times(a,b):
return a*b
def do_nothing():
return
# 함수의 호출
print()
dummy() #리턴 값이 없는 경우
print_hello()
print(times(10,10))
print(do_nothing())
#여러 개의 값을 반환
print()
def swap(a,b):
... |
50ef607d737aee60c281a650a0ed1433e66722eb | SINAEEE/pystudy | /data_type/set_ex.py | 1,613 | 3.625 | 4 | # 세트
# 순서 없고, 중복없는 객체의 집합
# {} 정의
# in, not in, len
# 세트 만들기
a={1,2,3}
print(a, type(a))
#포함 여부의 확인
print(2 in a)
print(3 in a)
print(2 not in a)
print(3 not in a)
# 객체를 추가 : add(x)
a.add(4)
print("add(4) : ",a)
a.add(4) #이미 있는 값에 추가
print("add(4) : ",a)
#객체를 제거해 봅시다. : remove(x), discard(x)
a.remove(4)
#a... |
0f2c31a02801deebe61cae9eb1902449bdf9ef15 | SINAEEE/pystudy | /exception/except_ex.py | 1,778 | 3.96875 | 4 |
def try_f1():
try:
lst = [1,3,5,7,9]
lst[5] # IndexError: list index out of range
except:
print("Error")
#try_f1()
def try_f2():
try:
value = int("10a") # ValueError: invalid literal for int() with base 10: '10a'
except ValueError as e: #특정상황의 error를 위쪽에서 처리하고
... |
1b1aa3742af628db1c257473f817ff7ef3b88706 | chuangbo/adventofcode-2020 | /day6/d6p1.py | 212 | 3.8125 | 4 | #!/usr/bin/env python3
filename = 'example.txt'
filename = 'input.txt'
count = 0
for group in open(filename).read().split('\n\n'):
s = set([c for c in group if c != '\n'])
count += len(s)
print(count)
|
8990f0091eac7324d5d464447d18afde1d6d1757 | kresimir-lukin/AdventOfCode2020 | /day01.py | 849 | 3.703125 | 4 | import sys
def two_pointer_sum(numbers, target_sum, left):
right = len(numbers) - 1
while left < right:
candidates = numbers[left], numbers[right]
if sum(candidates) == target_sum:
return candidates
if sum(candidates) > target_sum:
right -= 1
el... |
3f61f4435df65abe6c3b929d102674603f1d9778 | okey68/s-p500correlation | /correlapp.py | 586 | 3.734375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st
st.title('Stock Correlation App')
st.header('Enter two stock tickers to find their correlation')
stock1 = st.text_input("ticker", 'AAPL')
stock2 = st.text_input("ticker", 'KO')
# data as of 12/2020. will need to update
df = pd.read_csv('sp50... |
150707575b841cdf6be557362cb5b4c599cc9b4f | three3stones/ThoughtWork_Homework | /2.3 python面向对象基础/ParkingLot.py | 1,501 | 3.84375 | 4 | """
需求1:构造一个停车场,停车场可以停车和取车,停车成功后得到停车票。 用户取车的时候也需要提供停车票,停车票有效,才可以成功取到车。
"""
from Car import Car
import uuid
class ParkingLot:
def __init__(self, capacity):
# todo: 构造停车场所需的字段
self.capacity = capacity
self.cars = [] # 存储汽车
self.tickets = [] # 存储车票
def park_car(se... |
cc7d0b2ca2cee0a1d8f0cf65ed48e94a3209c8e2 | SimranKucheria/Snake-Game | /sg2.py | 2,916 | 3.53125 | 4 | import pygame
import random
import time
pygame.init()
def game(op):
if op == 1:
black=(0,0,0)
white = (255, 255, 255)
if op == 2:
white=(0,0,0)
black = (255, 255, 255)
up=1
down=2
left=3
right=4
blue=(0,0,255)
red=(255,0,0)
yellow = (255, 255, 102)
green = (0, 255, 0)
display=pygame.display.set_mode... |
26d14c6b1786baf307400f126ca9c81f183d0aa3 | AndrewBatty/Selections | /Selection_development_exercise_2.py | 368 | 4.125 | 4 | # Andrew Batty
# Selection exercise:
# Development Exercise 2:
# 06/102014
temperature = int(input("Please enter the temperature of water in a container in degrees centigrade: "))
if temperature <= 0:
print("The water is frozen.")
elif temperature >=100:
print("The water is boiling.")
else:
pr... |
88bba9fd15153a76c8b04b95160ae8c195453eec | Alan-luo1991/PythonTest | /LeetCode/Case_20.py | 2,879 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def isValid(self, s: str)... |
e10ee61baf3d57c049f24dd3299d27788391dc4e | raqii1997/Exercise-17 | /Exercise 17.4.py | 897 | 3.953125 | 4 | class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self): # __str__ function returns the representation of the object
return '(' + str(self.x) + ', ' + str(self.y) + ')'
def __add__(self, self_1): ... |
2ac62c3cf01d88c62085b6e5187906824dcdea33 | cwoolnough-ops/DataStructuresInPython | /Linked_list.py | 2,266 | 3.828125 | 4 | from node import Node
class LinkedList:
def __init__(self, value):
self.head_node = Node(value)
self.list_length = 0
if value != None:
self.list_length += 1
def get_head_node(self):
return self.head_node
def add_new_head(self, value):
new_head = Node(v... |
9e6bf011f38322f1eac4b950579881165d6e7812 | Rickard-Martensson/hashcode_2021_practice_problem | /main.py | 2,963 | 3.5625 | 4 | # Author: Rickard Mårtensson <rmarte@kth.se>
INPUT_FILE_NAME = "in"
OUTPUT_FILE_NAME = "out"
"""
Calculates the number of points for the google hashcode preparation problem 2021
Usage:
1. choose INPUT_FILE_NAME to be the input data from the problem description
2. Either choose OUTPUT_FILE_NAME (on row 20) ... |
7e9c099201526f12a4e4e2d647714a22b8d08e2d | jtirila/simple-file-etl | /simple_file_etl/file_readers/csv_reader.py | 725 | 3.546875 | 4 | import pandas as pd
def read_file(path, delimiter, header=None):
"""Read a CSV file. TODO: We are enforcing a little bit stricter syntax for delimiter,
and a bit looser for header, than Pandas does. Consider these requirements. Also consider stuff
like receiving a DataFrame index as a parameter etc.
... |
ea6766d0973dc81e8e2c4188c5155e97c8462996 | pratik-pednekar/NewFranchiseLocator | /apps/summary.py | 790 | 3.640625 | 4 | import streamlit as st
import numpy as np
import pandas as pd
#from data.create_data import create_table
def app():
st.write("Summary")
#st.title('WHERE DO YOU OPEN A NEW FRANCHISE?')
st.markdown("## The advantages of using this app are:")
st.markdown("* It can be generalized to other cities")
st.... |
b25046f848a3d33f240d6caf1bf61fc7e4882c99 | henokalem/US-Names | /pyparse.py | 913 | 3.671875 | 4 | import pandas
import matplotlib.pyplot as plt
fileNames = open('inputFile.txt', 'r')
for fileName in fileNames:
data = pandas.read_csv(fileName[:-1], sep=",", header = None)
data.columns = ["First Name", "Gender", "Count"]
data['Count'] = data['Count'].apply(pandas.to_numeric)
popularNames = data.sort_val... |
cca1670de9cdc7dc6856513d2d81302962e597bc | whp5924/Python | /class03.py | 942 | 4 | 4 | #
class person:
def __init__(self, name, age, height, weight, money): # 构造函数;
# 定义属性
self.name = name
self.age = age
self.__height = height
self.weight = weight
self.__money = money
def say(self):
print("hello! my name is %s,\ni am %d years old,\nI am he... |
c224d08507b99b58f1deee67a61a110567c28169 | whp5924/Python | /fig09_03.py | 860 | 4.21875 | 4 | #
# 基类 派生类
import math
class Point:
def __init__(self,xValue=0,yValue=0):
self.x=xValue
self.y=yValue
class Circle(Point):
def __init__(self,x=0,y=0,radiusValue=0):
Point.__init__(self,x,y)
self.radius=float(radiusValue)
def area(self):
return math.pi * self.radius **... |
403274fcc44f478915f82d96a42c4088968ac9db | whp5924/Python | /import1.py | 833 | 3.859375 | 4 | #import
# import 模块名1 [as 别名字】,模块名2 [as 别名2],......会导入指定的模块所有成员(包括变量、函数、类) 当使用时 用模块名作前缀.成员名
# from 模块名1 import 成员名1 [as 别名1],成员名2 [as 别名2],..... 导入的是模块中指定的成员,不是全体成员。当使用时,不用加前缀,直接使用成员名
# 直接直接
# *****module
# recursive call 或recursion step递归 return
import math,random
global summ11
def recursive1(number):
sum1=1
... |
3e1be987a5ab63d5a519861c5d5c229508ae2a9c | whp5924/Python | /fig09_08.py | 569 | 3.6875 | 4 | #
# Fig 9.6: fig09_08.py
#
class Point:
name="*******"
def __init__(self,xValue,yValue):
self.x=xValue
self.y=yValue
def __str__(self):
return "%d,%d" % (self.x,self.y)
if __name__=="__main__":
# 给类对象赋值,必须是类名赋值,用类对象赋值,只会实例化新类
point=Point(75,115)
print("x的坐标点:",point.x)
... |
2e46a48f1c93d103bdafae95e21cbe6a094154d4 | ryan-shnitman/Dijkstra | /Dijkstra.py | 1,921 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 13:56:42 2020
CS330
PA 2 -- Implement Dijkstra's Algorithm
"""
import sys
import heapq
""" global variables """
infinity = 10**4
shortest_path = {} #{node:[shortest distance, parent]}
adj_list = {} #{node:[child, edge weight]}
queue = ... |
93e7cb963f045429828b4a7b25a460e85136d758 | FH-Potsdam/hello-processing-py-cv-world | /find_lines/find_lines.pyde | 2,092 | 3.53125 | 4 | """
Simple sketch that looks for lines in a video
"""
# add the needed libs
add_library('video')
add_library('opencv_processing')
# declare the global variables we need
video = None
opencv = None
font = None
# setup is run once
def setup():
# make sure processing knows we are
# using the global objects
g... |
3b4608f02475a5cb37397511b3fa5bad4c4007e2 | earth25559/Swift-Dynamic-Test | /Number_3.py | 530 | 4.1875 | 4 | test_array = [-2, -3, 4, -6, 1, 2, 1, 10, 3, 5, 6, 4]
def get_index(max_val):
for index, value in enumerate(test_array):
if(value == max_val):
return index
def find_index_in_array(arr):
max_value = arr[0]
for value in arr:
if value > max_value:
max_value = value
... |
654aed523c6f2e360681ea7dd7192a1d321e97b3 | miniyk2012/bitcoin_gui | /checkbutton.py | 852 | 3.671875 | 4 | import tkinter as tk
window = tk.Tk()
window.title("radio button")
var = tk.StringVar()
l = tk.Label(window, bg='red', width=20, text='empty')
l.pack()
var1 = tk.IntVar()
var2 = tk.IntVar()
def print_selection():
if var1.get() == 1 and var2.get() == 1:
l.config(text="I love both")
elif var1.get()... |
77d19d85d6a71296a71de9b78cb367a6b783fc64 | itaditya/Python | /GUI/memo2.py | 1,255 | 3.875 | 4 | #!/usr/bin/env python3.4
import datetime
import tkinter
def getTime():
now = datetime.datetime.now()
return (now.strftime("%d-%m-%Y %H:%M"))
def addContent(file):
tag=input("Add a memo tag\n")
tag+="\n"
file.write(tag)
file.write(getTime()+"\n")
note=input("Input a note \n")
note+="\n\n"
file.write... |
e4ad61b609bed028b402265b224db05ceef7e2de | itaditya/Python | /Maths/toPostfixConv.py | 937 | 4.125 | 4 | from stack import Stack
def prec(operator):
if(operator == '^'):
return 3
elif(operator == '*' or operator == '/'):
return 2
elif(operator == '+' or operator == '-'):
return 1
else:
return -1
# print("Not a valid operator")
def postfixConv():
s = Stack()
e... |
fff80f653c78d1e1c1c14ff94dbe22f2b6e9248c | itaditya/Python | /GUI/dict.py | 941 | 3.8125 | 4 | #!/usr/bin/env python3.4
import tkinter
top=tkinter.Tk()
diction={
"python":"python is a snake which bites" ,
"window":"window is something which is transparent"
}
def initiategui():
quit=tkinter.Button(top,text='Close Me',command=top.quit)
quit.pack()
label=tkinter.Label(top,text="Copy text to view it's meaning... |
995aedff1269fffeb188c7d9150a7365a8b86680 | itaditya/Python | /GUI/Gui.py | 506 | 3.640625 | 4 | #!/usr/bin/env python3
import tkinter
top=tkinter.Tk()
quit=tkinter.Button(top,text='Close Me',command=top.quit)
quit.pack()
label=tkinter.Label(top,text='Hello World!')
label.pack()
# r =tkinter.Tk()
# r.withdraw()
# r.clipboard_clear()
# r.clipboard_append('Aditya is copied to clipboard')
# r.update()
# r.destroy()... |
fe9610a0463e784197fb704ce50ecb4d0b403d8e | itaditya/Python | /Practise/time.py | 244 | 3.96875 | 4 | #!/usr/bin/env python3.4
import datetime
now = datetime.datetime.now()
print ("Current Date using str\t",str(now))
print ("Current year %d \t" %now.year)
print ("Current strftime")
print (now.strftime("%Y-%m %H:%M"))
print (now.isoformat())
|
0cb9311c1a018a0a149e8707f6d33728120c263b | Yu-python/python3-algorithms | /5. LeetCode/145.binary-tree-postorder-traversal/[√] 1.py | 1,573 | 3.984375 | 4 | """
方法一: 深度优先搜索(DFS) - 递归
https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefb4e/
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/tu-jie-er-cha-shu-de-si-chong-bian-li-by-z1m/
解题思路:
什么是二叉树的后序遍历:按照访问「左子树、右子树、根节点」的方式遍历这棵树,
而在访问左子树或者右子树的时候,我们按照同样的方式遍历,直到遍历完整棵树。
因此整个遍历过程天然具有递归的性质,... |
40652596e623398b0f9e7b404dcbeebd4a3f2542 | Yu-python/python3-algorithms | /5. LeetCode/146.lru-cache/[√] 1.py | 2,242 | 3.890625 | 4 | """
方法一:标准库 collections.OrderedDict
解题思路:
在 Python 语言中,有一种结合了哈希表与双向链表的数据结构 OrderedDict
在 Java 语言中,同样有类似的数据结构 LinkedHashMap
复杂度分析:
时间复杂度:对于 put 和 get 都是 O(1)。
空间复杂度:O(capacity),因为哈希表和双向链表最多存储 capacity 个元素
"""
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.od ... |
56e9ead65e1b1eea967b3f3a2f54634db55a61b0 | Yu-python/python3-algorithms | /5. LeetCode/104.maximum-depth-of-binary-tree/3.py | 1,764 | 4.1875 | 4 | """
方法三: 广度优先搜索(BFS)
https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefb4e/
解题思路:
首先我们引入一个队列,这是把递归程序改写成迭代程序的常用方法。
1. 队列中只存放「某一层的所有节点」
2. 先记录这一层的节点数 size (队列中元素个数)
3. 迭代 size 次,每次出队一个元素,获取它的左右子节点再入队
4. 迭代完 size 次后,队列中就是下一层的所有节点。将最终结果 ans 值加 1
5. 重复步骤 1 - 4。二叉树的最大深度即为 ans
时间复杂度:O(n),其中 n 为二叉树节点的个数。每个... |
be0174ba49e03fce1f11555373d086756ee2e26d | Yu-python/python3-algorithms | /5. LeetCode/88.merge-sorted-array/[√] 3.py | 2,111 | 3.84375 | 4 | """
方法三:双指针(i与j),从后往前
解题思路:
nums1 有 m + n 的空间大小,可以用于储存最终的合并后的结果
从方法二借鉴下思路,我们可以依次比较 nums1 和 nums2 的较大者,保存到 nums1 的末尾即可
1. 使用 i 和 j 分别指向 nums1 和 nums2 的末尾元素(因为它们本来就是升序排列的)
2. 比较 nums1[i] 和 nums2[j] 的大小,将较大值存入结果数组 nums1 的末尾
3. 依次类推。直到 nums1 前半段(下标为 0 至 m-1) 或 nums2 其中一个序列为空时:
(1) 如果 nums2 先为空,因为原始 nums1 就是有序的,所以剩余的下... |
f86b48c39959f2f54884ddc7a0343dc7feaa8ffd | Yu-python/python3-algorithms | /5. LeetCode/21.merge-two-sorted-lists/2.py | 2,141 | 3.921875 | 4 | """
方法二:递归
https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/yi-kan-jiu-hui-yi-xie-jiu-fei-xiang-jie-di-gui-by-/ (看图更直观)
解题思路:
假设有序链表 l1 的长度是 n,有序链表 l2 的长度是 m
1. 判断 l1 和 l2 第一个节点哪个更小,然后较小节点的 next 指针指向「其余节点的合并结果(递归调用)」
2. 终止条件:当两个链表都为空时,表示我们对链表已合并完成
复杂度分析:
时间复杂度:O(n+m),其中 n 和 m 分别为两个链表的长度。
因为每次调用递归都会去掉... |
45c49b4e0b37dfc1b2bde7c1cd8899d30d9ed408 | Yu-python/python3-algorithms | /6. 剑指Offer/40.最小的K个数/[√] 2.py | 2,376 | 3.875 | 4 | """
方法二:堆
解题思路:
我们用一个大顶堆实时维护数组的前 k 小值。
1. 首先将前 k 个数插入大顶堆中
2. 随后从第 k+1 个数开始遍历:
如果当前遍历到的数比大顶堆的堆顶的数要大,则跳过它继续遍历(肯定不是前 k 小值,因为它比大顶堆最大的值还大)
如果当前遍历到的数比大顶堆的堆顶的数要小,就把堆顶的数弹出,再插入当前遍历到的数。
3. 最后将大顶堆里的数存入数组返回即可。
注意:Python 语言中的 heapq 模块创建的是小顶堆,因此我们要对数组中所有的数取负数,使用小顶堆找到前 k 大值,再将小顶堆里的数全部取反即可。
1. 首先将前 k 个数取反,再插入小顶堆中
2. 随后从第 k+1... |
39dd327631e503fb1e8f04000822baeb70e7e8ef | Yu-python/python3-algorithms | /5. LeetCode/232.implement-queue-using-stacks/[√] 1.py | 4,549 | 3.609375 | 4 | """
解题思路:
队列是一种「先进先出(first in - first out, FIFO)」的数据结构,队列中的元素都从后端(rear)入队(push),从前端(front)出队(pop)。
实现队列的三种方法:
- 数组(顺序队列)
- 链表(链式队列)
- 两个栈
栈是一种「后进先出(last in - first out, LIFO)」的数据结构,栈中元素从栈顶(top)压入(push),也从栈顶弹出(pop)。
为了满足队列的 FIFO 的特性,我们需要用到两个栈,用它们其中一个来反转元素的入队顺序,用另一个来存储元素的最终顺序。
要点:
1. 入队 push()
任何情况下,都只需要直接压入栈1即可
2. 出... |
c87251f72690a7929d946e6fc3195125ac77e040 | Yu-python/python3-algorithms | /5. LeetCode/145.binary-tree-postorder-traversal/[x] 5.py | 942 | 3.828125 | 4 | """
方法五: Morris 遍历
https://leetcode-cn.com/problems/binary-tree-postorder-traversal/solution/er-cha-shu-de-hou-xu-bian-li-by-leetcode-solution/
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/leetcodesuan-fa-xiu-lian-dong-hua-yan-shi-xbian-2/
解题思路:
利用二叉树中大量指向 None 的指针,可以将空间复杂度降为 O(1)
时间复杂度:O... |
f4993ce37db82d0f3642bb2adfad551b549bcae1 | Yu-python/python3-algorithms | /5. LeetCode/104.maximum-depth-of-binary-tree/4.py | 1,488 | 3.90625 | 4 | """
方法四: 深度优先搜索(DFS)
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/di-gui-bfsdfsde-3chong-jie-jue-fang-shi-by-sdwwld/
解题思路:
1. 将节点和它对应的深度一起压栈
2. 节点出栈后,更新树的最大深度为 ans 和节点深度中的最大值
3. 节点的左右子节点的深度为节点深度加 1
4. 右子节点先入栈、左子节点后入栈。类似于「前序遍历」
时间复杂度:O(n),其中 n 为二叉树节点的个数。每个节点只会被遍历一次。
空间复杂度:取决于栈中存储的最大元素个数,其在最坏... |
9c869c62b55990a57361432f84f425571f056993 | yohman/21W-UP206A | /Weeks/Week07/command1.py | 176 | 3.828125 | 4 | ########################################
# Hello!
########################################
name = input("Hello. What is your name?")
print ("Nice to meet you " + name)
|
6a893c43b41ab815a515aac7f2f662720e37fcc8 | doitduri/algorithm_py | /1181.py | 196 | 3.5625 | 4 | words = {}
n = int(input())
for i in range(n) :
w = str(input())
words[w] = len(w)
words = dict(sorted(words.items(), key=lambda t: (t[1], t[0])))
for i in words.keys():
print(i) |
08d82c08934ec253d1d7cda9463b0ca703163e08 | robbysingh23/python1 | /celsius_conversion.py | 173 | 3.96875 | 4 | celsius = int(input('Please enter a Celsius temperature: '))
fahrenheit = (celsius * 9/5) + 32
print('The temperature in C is %s' % (celsius))
print(str(fahrenheit) + ' F') |
183822cb41cd13058b01fb033604a4e2bcc778e7 | jtonyortiz/PyTorch-Tutorials | /pyTorchBlitz.py | 1,044 | 3.5625 | 4 | from __future__ import print_function
import torch
#Print an uninitialized 5x3 matrix:
x = torch.empty(5,3)
print(x)
#Construct a randomly initialized matrix:
x = torch.rand(5,3)
print(x)
#Consturct a matric filled with zeros and of dtype long:
x = torch.zeros(5,3, dtype=torch.long)
#Construct a tensor directly f... |
29dc0056edb2aaeeafb44cce012915c93ac881b6 | victorgardini/TCP_server | /TCPServer.py | 2,328 | 3.65625 | 4 | from socket import *
def contar_vogais(frase):
"""
--> Esta função, recebe ums string e conta o número de ocorrências das vogais na mesma.
"""
cont_a = frase.count('a')
cont_e = frase.count('e')
cont_i = frase.count('i')
cont_o = frase.count('o')
cont_u = frase.count('u')
return f'... |
275fe7b79c7c091237ce170cb043b4983a1fc1b2 | SweLinHtun15/GitFinalTest | /Sets&Dictionaries.py | 1,520 | 4.1875 | 4 | #Sets
#include a data type for sets
#Curly braces on the set() function can be used create sets.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
#Demonstrates set operations on unique letters from two words
a = set('abracadabra')
b = set('alacazm')
a # unique letter in a
a - b ... |
11112a412fe774fd409082097729276881a281c8 | SweLinHtun15/GitFinalTest | /FileInputOutput/open.py | 665 | 3.671875 | 4 | # "r" - Read
# "a" - Append
# "w" - Write
# "x" - Create
# "t" - Text
# "b" - Binary
#open & Read file
f = open('test.txt', 'r') # R - Read
print(f.name)
f.close()
with open('test1.txt', 'a') as g:
g.write('This is line number 6'+"\n")
print(g,end='')
with open('test.txt', 'r') as f:
f_text = f.readli... |
4b37c615f7a0f44b918a7cd870e7306de7ee70db | pranay-anchan/Algorithms-and-Data-Structures-in-Python | /duplicates.py | 237 | 3.828125 | 4 | def duplicates(nums):
for num in nums:
if nums[abs(num)] >=0:
nums[abs(num)] = -nums[abs(num)]
else:
print("Repetition found: ", abs(num))
if __name__ == "__main__":
nums = [2,6,5,1,4,3,2,3]
duplicates(nums) |
344135a82efc6850461f37c9630d9d66d43fddfc | zetica97/Calculadora | /Calcu.py | 875 | 3.984375 | 4 |
def Suma(x, y):
return x + y
def Resta(x, y):
return x - y
def Multiplicar(x, y):
return x * y
def Dividir(x, y):
return x / y
salir = False
while not salir:
print("Que desea hacer:")
print("1.Suma")
print("2.Resta")
print("3.Multiplicar")
print("4.D... |
e6504d78073d7d914cb00031f9b418f4c52f3339 | hackclubcoet/Batch-4 | /Aswain.py | 676 | 4.09375 | 4 | import random
# Aswain-4-Number Guessing
number = random.randrange(1,10)
# returns a randomly selected element from the range created by start,stop and step argumemts
guess = int(input("Guess a number between 1 and 10 :"))
#stores the guessed number
while guess!= number: #checks whether guess not to equal to number
... |
75d2edf7a9993df774ab3733d76f477567cc6d0e | Akashtyagi/DataStructure | /Data-Structures/Greedy_Problems/Hauffman_Encoding/haufman_encoding.py | 7,514 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 23:42:35 2020
@author: AkashTyagi
"""
from collections import Counter
from queue import PriorityQueue
class HauffmanNode:
def __init__(self, char, frequency=0, left=None, right=None):
self.char = char
self.frequency = freque... |
e74b2157aaeb871f26ccd355940dd06bd1a195fe | Akashtyagi/DataStructure | /Problems/non_recursive_merge_sort/sort_linkedList_using_mergeSort.py | 3,415 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 18:57:18 2020
@author: AkashTyagi
"""
# =============================================================================
# Non-recursive merge sort
# =============================================================================
'''
In this, we sor... |
72c6b11a9c59c967b8d96ba3cf0385dcce9385b1 | Akashtyagi/DataStructure | /Data-Structures/sorting_algos/radix-sort.py | 2,800 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 20:50:10 2020
@author: Akash Tyagi
"""
'''
Explanation: https://www.youtube.com/watch?v=JMlYkE8hGJM
Fastest sorting algo in term of time complexity.
* Redix sort maintains Locality of reference i.e If 3 occurs twice, then the 3 which occured f... |
aef61344b4ca92c43e83387dbed6bf6b461f5b7a | Akashtyagi/DataStructure | /Problems/majority_element/majority_element.py | 1,203 | 3.921875 | 4 | class Solution:
def majorityElement(self, nums: List[int]) -> int:
# =============================================================================
# Moore Voting Algorithm
# =============================================================================
'''
*** WORKS ONLY if we... |
f0182bd69afe96e831eccd0066d12cd295452b38 | Akashtyagi/DataStructure | /Problems/majority_element_array/majority_element.py | 1,322 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 12:37:15 2020
@author: Akash Tyagi
"""
#Question: https://leetcode.com/problems/majority-element/solution/#fnref1
#nums = [1,1,1,2,2,2,4,5] # Doesn't work for this. (No majority elem)
nums = [2,1,2,2,5,2,4]
#nums = [2,3,3]
l = len(nums)
#... |
48c93bf81a99429bd43744cd1170790743cdbcc7 | Akashtyagi/DataStructure | /Problems/Tower_Of_Hanoi/tower_of_hanoi.py | 1,651 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 22 17:40:40 2020
@author: AkashTyagi
"""
# =============================================================================
# Tower of Hanoi
# =============================================================================
'''
| | |
| | ... |
11194c78a1f269eb2e376fd31ecdbbda73476b98 | PaulTeco/feynmanim | /FeynManim.py | 15,649 | 3.890625 | 4 | from manim import *
class FeynManim:
"""
A class to construct parts (curves) of Feynman Diagrams with Manim
Main Attributes
----------
geometry : lambda function
parametrizes the geometry of the curve (default is a straight line)
line_style : lambda function
parametrizes the... |
0d7c7ed5f2ace216376ebac6469581500b8e755b | wggy/python3.7-lesson | /lesson14/use_fileio.py | 838 | 3.578125 | 4 | # _*_ coding: UTF-8 _*_
# created by ping on 2020/1/14 23:45
# 文件操作
# file = open(filename, mode, buffering)
# filename: 文件名称
# mode: 打开文件模式
# buffering: 是否开启缓存,0:不开启,1:开启,大于1:缓冲区大小,默认开启缓存
# file = open('test.txt', 'a+', encoding='utf-8')
# file.write("黑发不知读书早,白首方知读书迟")
# file.close()
# 读取全部
with open('test.txt', 'r... |
27c36c2b903a2d5ee1c9e1adf6978bf9fd3f9483 | wggy/python3.7-lesson | /lesson03/input.py | 618 | 3.78125 | 4 | # _*_ coding: UTF-8 _*_
# created by ping on 2020/1/2 22:45
import datetime
username = input('请输入姓名:')
# python3.7中input输入的信息都是字符类型
bornyear = int(input('请输入出生年份:'))
print('姓名:', username, ',出生:', bornyear)
nowyear = datetime.datetime.now().year
age = nowyear - bornyear
if age > 65:
print(username, '你是老年人了,辛苦... |
97bc5e1d52cd2a5a9cccfb277a351b3c801a211f | NULLCT/sl_sazae | /scraper/formatter.py | 691 | 3.734375 | 4 | #!/usr/bin/env python3
import codecs
def formatLine(line) -> str:
#remove "第"
line = line[1:]
#放送中止
if not line[0].isdigit():
return "ERROR"
#remove "回"
line = line[0:line.find("回")] + line[line.find("回")+1:]
cnt = 0
for i in range(len(line)):
if line[i] == " ":
cnt+=1
if cnt == ... |
f61efcd0cb07e68a3ee8ad580d6d6daea163b60e | hyekyeong123/programmers-coding | /programmersOne/2020-07-13/완주하지못한선수.py | 1,190 | 3.53125 | 4 | # 처음 풀이 -> 틀림
def solution(participant, completion):
participant.sort()
completion.sort()
for i in range(0, len(completion)):
if participant[i] != completion[i]:
return participant[i]
return participant[-1]
# 처음에 remove를 사용해서 삭제했는데 아무리 해도 틀린 값이 나왔다.
# 두번째 풀이
participant = ['marina'... |
4f05e2864e527d66046bce49b60cf422f9801803 | hyekyeong123/programmers-coding | /programmersOne/2020-07-17/이상한 문자 만들기-.py | 707 | 3.578125 | 4 | def solution(s):
newStr = ''
sArray = s.split(" ")
for i, v in enumerate(sArray):
# 3번 반복
vArray = list(v) # 각 문자열을 리스트로 만들기
for ii, vv in enumerate(vArray):
if ii == 0:
newStr += vv.upper()
elif ii % 2 == 0:
# 짝수라면
... |
b43013c3a32da2d0fbaa752339ae0963f41939b6 | hyekyeong123/programmers-coding | /programmersOne/2020-07-24/핸드폰 번호 가리기-.py | 773 | 3.609375 | 4 | # 파이썬에서 문자열은 부분적으로 수정이 불가능하다. 따라서 문자열 내용에 수정이 필요하다고 한다면 새롭게 문자열을 생성하는 수 밖에 없다.
# 나의풀이
def solution(phone_number):
answer = ''
length = len(phone_number)
result = phone_number[-4:] # -4인덱스에서 끝까지
for i in range(length - 4):
answer += '*'
answer = answer+result
return answer
# 다른 사람의... |
d96d47d9728448cb33ae3165d243e030e71be4ac | NateByers/programming_for_life_sciences | /assignment2a.py | 2,467 | 4 | 4 | # Below I define a recursive function to make a list of all possible nucleotide
# combinations for an arbitrary length. (c.f. chapter 2 in Advanced Python For
# Biologists by Martin Jones (2014)).
def make_nucleotide_combos(length):
if length == 1:
return ['A', 'T', 'G', 'C']
else:
combos = []
... |
a08731ab7d14189b502210784451bff4f46b0b61 | satyammutha/PythonPrograms | /minMax.py | 426 | 3.890625 | 4 | def minMaxCheck(arrIn):
minValue = arrIn[0]
maxValue = arrIn[0]
for eachNumber in arrIn:
if(eachNumber < minValue):
minValue = eachNumber
if(eachNumber > maxValue):
maxValue = eachNumber
return minValue, maxValue;
n = int(input())
arrIn = []
for index in range(n)... |
14ad549e99a814bf75c83e8ef6aa301d980319cd | smadabushi123/excecise2 | /excercise2_1.py | 757 | 3.953125 | 4 | #Author:Sri Harsha Madabushi
#Date : 21/05/2019
"""Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3"""
# Asking user to input a string
stri... |
313d516c677a09c69b158b1bd195ea0b2ff2fbc9 | tylors1/Leetcode | /Problems/recurseObject.py | 366 | 3.890625 | 4 |
def getIn(obj, arr):
def traverse(obj, arr, i):
if i == len(arr) - 1:
return obj[arr[i]]
if not obj:
return None
return traverse(obj[arr[i]], arr, i + 1)
return traverse(obj, arr, 0)
obj = {"username": "sally", "profile": {"name": "Sally Clojurian", "address": {"city": "Austin", "state": "TX"}}}
arr... |
6e4823e36c5c7d85c66fb61a9ed04ce66d312f00 | tylors1/Leetcode | /Problems/stringSplosion.py | 188 | 3.75 | 4 | # http://codingbat.com/prob/p117334
def string_splosion(s):
res = []
for i in range(len(s)):
res.append(s[:i+1])
return "".join(res)
s = "abc"
s = "Code"
print string_splosion(s) |
71eee7a87f03cd592a5d2caf4a00628d20c4abff | tylors1/Leetcode | /Problems/dailyTemperatures.py | 461 | 3.5 | 4 |
def dailyTemperatures(temperatures):
res = [0] * len(temperatures)
stack = []
for i in range(0, len(temperatures)):
while stack and stack[-1][0] < temperatures[i]:
temp = stack.pop()
res[temp[1]] = i - temp[1]
if i != len(temperatures)-1 and temperatures[i+1] > temperatures[i]:
res[i] = 1
else:
... |
9e3b3eab52351f1623476a42057c226dbbff485b | tylors1/Leetcode | /Problems/treeLCA.py | 717 | 3.5625 | 4 | from binarytree import Node
def LCA(root, n1, n2):
print root
arr1 = []
arr2 = []
def getPath(root, path, n):
if not root:
return False
path.append(root.value)
if root.value == n:
return True
if (root.left != None and getPath(root.left, path, n)) or (root.right != None and getPath(root.right, path,... |
6db52f6f535188182deceb48cdaf203f5deb416f | tylors1/Leetcode | /Problems/fib.py | 144 | 3.578125 | 4 |
cache = {}
def fib(n):
if n <= 1:
return 1
else:
if n not in cache:
cache[n] = fib(n-2) + fib(n-1)
return cache[n]
print fib(200) |
46a8871ca59f348f8ed1771786e0e517c82a6450 | tylors1/Leetcode | /Problems/increasingTriplet.py | 253 | 3.6875 | 4 | def increasingTriplet(nums):
low = mid = float('inf')
for num in nums:
if num < low:
low = num
if low < num < mid:
mid = num
if num > mid:
return True
return False
nums = [6,7,1,2]
# nums = [6,7,1,2,8]
print increasingTriplet(nums) |
7889b08683e25156d2513d9852eed1512c73a4ad | tylors1/Leetcode | /Problems/plusOne.py | 241 | 3.640625 | 4 | def plusOne(digits):
for i in range(len(digits))[::-1]:
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
digits[0] = 1
digits.append(0)
return digits
digits = [1,2,3,9]
# digits = [1,2,3,4]
print plusOne(digits) |
cd71e74d8cbc6ad4a8594250abe57668fe0e57c4 | tylors1/Leetcode | /Problems/topKElements.py | 264 | 3.546875 | 4 | import heapq
def topKElements(nums, k):
counts = {}
for num in nums:
if num not in counts:
counts[num] = 1
else:
counts[num] += 1
print counts
return heapq.nlargest(k, counts, key=counts.get)
nums = [1,1,1,2,2,3]
k = 2
print topKElements(nums, k) |
06f212d4174a614107c282791996452ea4103f44 | tylors1/Leetcode | /Problems/tictactoe.py | 1,256 | 3.921875 | 4 | # terminal tic tac toe game
import sys
board = [[None, None, None],
[None, None, None],
[None, None, None]]
count = 0
def get_play():
row = raw_input("Enter row: ")
col = raw_input("Enter col: ")
if row.isdigit() and col.isdigit():
row, col = int(row), int(col)
if row < 3 and col < 3 and board[row][col] ==... |
38f1a362e3adc4f816c57980606498d5ab1b56b3 | tylors1/Leetcode | /Problems/longestSubarray.py | 681 | 4.125 | 4 | # subarray sum - find the longest subarray sequence
# that adds up to a target
# FOLLOW UPS:
# 1. How would we modify this if we're looking for min subarray sequence?
# 2. How would we modify this if we're looking for min subarray sequence equal to OR greater than target?
def longestSubarray... |
0438ab17c66f541186a58aa2cddcaf92ce62ff22 | tylors1/Leetcode | /Problems/longestSubstring.py | 536 | 3.734375 | 4 | def longestSubstring(s, k):
if k == 0 or s == None or len(s) == 0:
return 0
if len(s) < k:
return s
store = {}
max_len = k
left = 0
right = 0
for i in range(len(s)):
if s[i] in store:
store[s[i]] += 1
else:
store[s[i]] = 1
print store
if len(store) > k:
max_len = max(max_len, i-left)
w... |
d08349fb012d87a67c436dbb22c436761c29078b | DmitriBelan/Python_2021 | /Tests/Test_1_21092021/Task_3.py | 243 | 4.09375 | 4 | while True:
a = float(input('Please enter side "a": '))
b = float(input('Please enter side "b": '))
c = float(input('Please enter side "c": '))
if a ** 2 + b ** 2 == c ** 2:
print('Ok')
else:
print('Not OK') |
89687db198b4df9815e1dc85dda80c1ae078f464 | sunilmummadi/cmpe255-spring19-lab1 | /friends.py | 1,236 | 3.703125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
users =[
{ "id":0, "name": "Hero" },
{ "id":1, "name": "Dunn" },
{ "id":2, "name": "Sue" },
{ "id":3, "name": "Chi" },
{ "id":4, "name": "Thor" },
{ "id":5, "name": "Clive" },
{ "id":6, "name": "Hicks" },
{ "id":7, "name": "Devin" },
... |
758f6edb9e9a50b1336ad5f9fb4ca20c9e529745 | vithalw/Marvellous_Assignment3 | /frequency3_4.py | 542 | 4 | 4 | def getFrequency(arr,number):
count=int(0);
for i in range(0,len(arr),1):
if(arr[i]==number):
count=count+1;
return count;
def main():
size=int(input("Enter size of List: "))
arr=[];
print("Enter elements: ")
element=int(0);
for i in range(0,s... |
91547fa5469d2dd8156d8ddaeb0689029f9a4e83 | nusoff01/CLS_192 | /wiki/locations_by_year.py | 437 | 3.5 | 4 | # The purpose of this script is to take in a band list (i.e. location
# and town founded in) and extract the locations after a given date
import csv
sourceData = "csvs/"
cutoff_year = 2016
with open(sourceData + 'House.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',', skipinitialspace=True)
... |
59a66f5d61e433919603d5fb3baae1c079ce7d36 | MuthuNarayanan10/Guvi | /ZenClass/Day7/prgm7.py | 97 | 3.75 | 4 | string=input("enter the string")
string1=string.swapcase()
print("After toggling case",string1) |
d269f473c5856c3ea63039294a073b28af27fd4e | fjcarpen/glowing-octo-ironman | /test.py | 50 | 3.5 | 4 | a=[2,3,1]
a.sort()
a.reverse()
print a
raw_input() |
eee553d6d0bfdd463cd8deb6a5e9a3ae80a10a5b | wangxinghust/pyhello | /pyhello/test_survey.py | 984 | 3.6875 | 4 | import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def setUp(self):
"""
创建一个调查对象和一组答案,供使用的测试方法使用
"""
question="what language did you first learn to speak?"
self.my_survey=AnonymousSurvey(question)... |
b28cc9b225183cf220709a8dc09ee64a58cc0123 | wangxinghust/pyhello | /pyhello/hello.py | 418 | 3.546875 | 4 | message="测试一波"
print(message)
msg="hello world! python!"
print(msg)
print("为什么没有pylint?")
message="第二次测试一波"
print(message)
print(message)
print("\tPython")
print("Languages:\n\tPython\n\tC\n\tjava")
msg=" python "
print(msg.rstrip()) # 删除字符串右边的空格,删除左边用lstrip(),全部删除用strip()
age=23
message="Happy "+ str(age)+"rd Bir... |
1fad0145e4dc586d2c02e3dd8adc1874ac655284 | wangxinghust/pyhello | /pydata/scatter.squares.py | 635 | 3.65625 | 4 | """
散点图
"""
import matplotlib.pyplot as plt
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, edgecolor='none',
s=40, c=y_values, cmap=plt.cm.Blues)
# 设置图表标题并给坐标轴加上标签
plt.title("Squares Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("S... |
2c66e5f8239a095868af69cc7f0b92843d795e5f | acslater00/amazeing | /dotgraph.py | 6,479 | 3.703125 | 4 | from collections import defaultdict
"""
Idea here; every "white" dot is a node, with an id
1) every pixel is a node
2) condense pixels to make the search graph a bit smaller (3x3 instead of 1x1)
3) run dijsktra from start to end and see how long it takes?
"""
# must be a square...
class Node(object):
def __ini... |
492c73ee6942bc4dc280466b321083b1b0da3b67 | Candy-Robot/python | /python编程从入门到实践课后习题/第八章、函数/fun3.py | 774 | 3.6875 | 4 | """
def show_magicians(charmer):
for magician in charmer:
print(magician)
def make_great(charmer):
length = len(charmer)
for a in range(0,length):
charmer[a] = 'the Great ' + charmer[a]
magicians = ['zhangfei','guanyu','yangguo','xiaozhao']
show_magicians(magicians)
make_great(magicians)
... |
885d43c1619d5ddd8166a60492eb74f026778c5f | Candy-Robot/python | /python编程从入门到实践课后习题/第七章、用户输入与循环/while.py | 1,683 | 4.15625 | 4 | """
prompt = "\nwhat Pizza ingredients do you want: "
prompt += "\n(Enter 'quit' when you are finished) "
while True:
order = input(prompt)
if order == 'quit':
break
print("we will add this "+order+" for you")
prompt = "\nwhat Pizza ingredients do you want: "
prompt += "\n(Enter 'quit' when you ... |
fd561479f49ea7752569353c25e2c7ac2de627eb | Candy-Robot/python | /python编程从入门到实践课后习题/第六章/pet.py | 804 | 3.75 | 4 | """
cat = {
'pet_type':'cat',
'owner':'mike',
}
dog = {
'pet_type':'dog',
'owner':'liming',
}
pig = {
'pet_type':'pig',
'owner':'wangwu',
}
pets = [cat,dog,pig]
for pet in pets:
print(pet)
favorite_place = {
'mike' : ['hangzhou','shanghai','guangzhou'],
'jack':['nanjing'... |
3121b06cef5a09d78baafed33201a320930c38ba | ybgirgin3/hackerrank-solutions | /python_/namedtuple.py | 427 | 3.53125 | 4 | from collections import namedtuple
# ID, marks, class and name
# order of these is not important
# calc average of the class
ead input from STDIN. Print output to STDOUT
from collections import *
N,students= input(), namedtuple('students',raw_input().split())
stud= [students(*raw_input().split()) for i in range(N)] ... |
455c17245302c8f20073c1c7688d96a8e82c97bc | ybgirgin3/hackerrank-solutions | /python_/regex_subtitution.py | 313 | 3.984375 | 4 | # && ve || leri değiştir
# &&& ve ||| olanları değiştirme
# yorum satırında olanları da değiştirme
import re
def change(match):
if match.group(1) == '&&':
return 'and'
else:
return 'or'
for _ in range(int(input())):
print(re.sub(r"(?<= )(\|\||&&)(?= )", change, input()))
|
8f34e47f9e01b0e8ad7a3afb10c6232c452a46d7 | ybgirgin3/hackerrank-solutions | /Algorithm_w_Python/plusminus/asd.py | 708 | 3.609375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
nList = []
pList = []
zList = []
def divider(z, n, p, h):
pos = p / h
neg = n / h
zer = z / h
# return ('%.6f\n%.6f\n%.6f' % (pos, neg, zer))
print('%.6f\n%.6f\n%.6f' % (pos, neg, zer... |
dc9de3a40fc29f6292da80a96b55a70254e87eb4 | ybgirgin3/hackerrank-solutions | /python_/calendar_module.py | 242 | 3.734375 | 4 | # mm dd yyyy verilecek onun hangi güne denk geldiğini bul
import calendar
# input
mm, dd, yyyy = map(int, input().split())
#print(mm, dd, yyyy)
target = calendar.weekday(yyyy, mm, dd)
ret = calendar.day_name[target].upper()
print(ret)
|
24d7e0a7a7a0d6a68b1954f2f096f9e7bb31440d | squallcloud/Sample_forPython | /EasySample/test.py | 165 | 3.671875 | 4 | l = [[1,2,3], [7,8,9]]
for x, y, z in l:
print("{1} {0}".format(x, y))
ll = ["index:{}".format(x) for x in range(10)]
print(ll)
lll = range(10)
print(lll) |
33b0975ef87813ffefa1460a7d3cf4348121689c | abvarun226/coding-challenges | /leetcode/Problem19.py | 780 | 3.640625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
listLen = 0
d = ListNode(0)
d.next = head
curr = head
while curr is not None:
listLen += 1
curr = curr.next
listLen -= n
curr ... |
c15c747ebdeeeaeab56594c4bc2e76a40d49cd8d | abvarun226/coding-challenges | /hackerrank/find-the-merge-point-of-two-joined-linked-lists.py | 1,364 | 3.984375 | 4 | """
https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem
"""
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
def findMergeNode(head1, head2):
''' Optimal Solution - O(n) '''
p1, p2 = head1, head2
l1, l2 = 0, 0
# Get the length of first ... |
93df6c2d95afd7e1c479d7254e3cfcc8d361d5f9 | samyhkim/algorithms | /206 - reverse linked list.py | 558 | 3.96875 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
def reverseList(head):
new = None
curr = head
while curr:
next = curr.next # saves curr's next position
curr.next = new # assign's curr's position to new
new = curr # new takes curr's old sp... |
c60b078ada7cf7a9aeeaea63ac9e1b4c6b5c8bf0 | samyhkim/algorithms | /67 - add binary.py | 447 | 4.0625 | 4 | def add_binary(a, b):
sum = ""
a = list(a)
b = list(b)
carry = 0
while a or b or carry:
# convert to int
if a:
carry += int(a.pop())
if b:
carry += int(b.pop())
# convert back to str
sum += str(carry % 2) # ones digit
carry /... |
fb6c3d9170ac0280ca45fea3a857b828e6c50e49 | samyhkim/algorithms | /124 - binary tree maximum path sum.py | 895 | 3.515625 | 4 | def max_path_sum(root):
max_path = float("-inf") # placeholder to be updated
def get_max_gain(node):
nonlocal max_path # This tells that max_path is not a local variable
if node is None:
return 0
# Read the part important observations
gain_on_left = max(get_max_ga... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.