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
fe69319fd23b34bcfc3f8e5534a7d81158f2cc74
victorparra96/Dictionaries-in-Python-
/exercise6.py
744
4.0625
4
""" Escribir un programa que cree un diccionario vacío y lo vaya llenado con información sobre una persona (por ejemplo nombre, edad, sexo, teléfono, correo electrónico, etc.) que se le pida al usuario. Cada vez que se añada un nuevo dato debe imprimirse el contenido del diccionario. """ new_dict = {} def cre...
25b050106a89f63ea2133a42edc2fb2359379ee2
victorparra96/Dictionaries-in-Python-
/exercise9.py
2,093
4.25
4
""" Escribir un programa que gestione las facturas pendientes de cobro de una empresa. Las facturas se almacenarán en un diccionario donde la clave de cada factura será el número de factura y el valor el coste de la factura. El programa debe preguntar al usuario si quiere añadir una nueva factura, pagar una existent...
8755045010b78fa186c0f8dc7a005e7a34f4cabb
hoodielive/computerscience
/python/linked_lists/singly_linked_list.py
1,079
3.796875
4
class Node: def __init__(self, value): self.info = value self.link = None class SingleLinkedList: def __init__(self): self.start = None def display_list(self): if self.start is None: print("List is empty.") return else: print("L...
5a909adc2afee84b66d5b2b234ba71e55da4e5a3
A-creater/turtle_exemple
/event_button.py
2,384
4.28125
4
import turtle class Point: def __init__(self, x, y): self.x = x self.y = y class Button(turtle.Turtle): point1: Point point2: Point title: str def __init__(self, point1: Point, point2: Point, title: str): super(Button, self).__init__() self.point1 = point1 ...
ac8d2e3b16ea184e848d5a98f7e237f259917311
adimehta03/Emotional-Virtual-Assistant-with-COVID-informatics
/EVA/__init__.py
337
3.671875
4
''' Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. ''' num=[1,2,3,4,1,2,3] d={} for i in num: d[i]=num.count(i) print(d.items()) print(sorted(d.items(), key= ...
ab4816011c4f66a1a78af074d130b6d104c69a65
Technoconfig/BMICalculator.exe-Python-GUI-
/BMI-Calculator.py
2,062
3.71875
4
# Imports all from Tkinter GUI Package from tkinter import * # Initialization app = Tk() ma = IntVar(None) he = IntVar(None) b = IntVar(None) # Calculates Body Mass Index (BMI) with user inputs, then put the user in one of four categories # Also check if the values entered are not zero def calculate_bm...
521fc9ebe9ece1368a26345f826b3efc2e57b20a
DavidLeBa-VN/FCTC_AP
/PY4E/List/Exercise_6.py
161
3.6875
4
a = [] while True: s = input('Enter a number: ') if s == 'done': break a.append(int(s)) print('Maximum:', max(a)) print('Minimun:', min(a))
fabc2d50efa94a266facaf1127fd1fef4b39a016
DavidLeBa-VN/FCTC_AP
/CS50/Unit_1_Python_Basic/Problem_3.py
248
3.53125
4
s = input() + "0" sta, end = 0, 0 sn = 0 for a in range(len(s)): if a == 0 or s[a] < s[a - 1]: if (sta == end and end == 0) or (a - sn > end - sta + 1): sta = sn end = a - 1 sn = a print(s[sta : end + 1])
9d7e8ff8ab40845f98546ece5d3026296c4d0ea8
lucasantarella/njit_cs100_hw
/HW10_LucaSantarella.py
1,061
3.78125
4
""" Luca Santarella CS 100 2018S Section 009 HW 08, November 1, 2019 """ horton = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say'] """ Exercise 1: """ def initialLetterCount(wordList): result = dict() for word in wordList: if word[0] in result: result[word[0]] += ...
554e1ac6391e6f8582fcf1e48f3d724e4d992c42
Romeo2393/First-Code
/Comparison Operator.py
220
4.21875
4
temperature = 30 temperature = int(input("What's the temperature outside? ")) if temperature > 30: print("It's a hot day") elif temperature < 10: print("Its a cold day") else: print("Enjoy your day")
2212ee424a9f6e92024b069625f95c09291b7ba0
mgorenstein/algorithmic-art
/linear_knots/linear_knots.pyde
592
3.859375
4
''' This algorithm generates a stochastic system of connected lines. The System class draws a specified number of initial lines and then draws a specified number of random lines that form a vertex with one or two of the previously drawn lines. ''' from system import System from datetime import datetime def setup(): ...
3eebb69e178befbda33ea9fe8289474751af63b8
Reyloso/Test_Ingenieria_datos
/fibonacci.py
2,958
4.1875
4
from math import log10, sqrt """ Serie Fibonacci La secuencia de Fibonacci es una secuencia de números con la relación: 𝐹𝑛=𝐹𝑛-1𝐹𝑛-2, donde 𝐹1=1 y 𝐹2=1 Resulta que 𝐹541 contiene 113 dígitos y es el primer número de Fibonacci donde los últimos 9 dígitos son una secuencia pan-digital (que contiene todos los núm...
c3be3e8656cd4bdf11c6f84def02bbb148d947da
knight-byte/Codewars
/7_Kyu/Reverser/Reverser.py
132
4.0625
4
def reverse(n): """Returns n with all digits reversed. Assume positive n.""" return int(''.join([i for i in str(n)])[::-1])
0dc370163b9d59e9dbfea70ebea4579afbef4834
knight-byte/Codewars
/7_Kyu/Simple remove duplicates/Simple_remove_duplicates.py
145
3.546875
4
def solve(arr): arr.reverse() re = [] for i in arr: if i not in re: re.append(i) re.reverse() return re
6642aaa9975a7b6b25bbb958e35dd1583aa12c9c
scottshull/Sales-Tax
/Sales Tax.py
657
4.0625
4
cost = 1 totalCost = 0 print("List the prices of each item and then enter 0 when you are done. ") while cost != 0: strCost = raw_input("Enter the cost of the item: ") cost = float(strCost) totalCost += cost else: print ("The total is $" + str(totalCost)) strTax = raw_input("How much is th...
2b436c2a6da7c7ac397964332008153b5ec2d7ae
thegraycoder/programming-for-fun
/python/easy/longest-common-prefix.py
2,423
3.75
4
# Write a function to find the longest common prefix string amongst an array of strings # If there is no common prefix, return an empty string "". # Runtime: 28 ms # Approach 1: Length LCP cannot be greater than that of smallest string # Calculate min length O(n) # While len(LCP) < minlen build prefix and return if c...
257d98aab923cde7604b08aa3cba3040c988fc14
AlbandeCrevoisier/is
/cs/alban.py
3,433
3.8125
4
"""Internship offline test: cluster detection in a binary image. Convention: the origin of (x, y) coordinates is the top left corner of the image, with x increasing towards the right and y increasing towards the bottom. Assumption: in PART 1: Simple Clustering, it is said that '2 pixels of ones are in the same cluste...
2c65ac439e4980da2ccbd21af4918b095a6247bb
AzimAstnoor/Function
/newt/main.py
797
3.84375
4
def addition(add1, add2): add3 = add1 + add2 return add3 def subtraction(sub1, sub2): sub3 = sub1 - sub2 return sub3 def multiplication(mul1, mul2): mul3 = mul1 * mul2 return mul3 def division(div1, div2): div3 = div1 / div2 return div3 def modulus(mod1, mod2): mod3 = mod1 % mod2 ...
bade7f1f21186629b07d0c32e07430dec5d44966
bitrost/exercism
/python/isogram/isogram.py
295
3.953125
4
def is_isogram(words): characterList = [] words = words.lower() words = words.replace(" ","").replace("-","") for character in words: if (character not in characterList): characterList.append(character) else: return False return True
84e23d7bb5df3549b754b9785c6c4a906f504a97
zacniewski/Decorators_intro
/05_decorators_demystified.py
1,460
4.1875
4
"""The previous example, using the decorator syntax: @my_shiny_new_decorator def another_stand_alone_function(): print "Leave me alone" another_stand_alone_function() #outputs: #Before the function runs #Leave me alone #After the function runs Yes, that's all, it's that simple. @decorator is just a shortcut to: ...
f6d25b2241de30314fd7c6a322b8be18d1936ba6
DiogoM14/Python-Exercicios
/Curso/ex018.py
322
3.96875
4
from math import tan, sin, cos, radians an = float(input('Qual o ângulo que pretende saber? ')) t = tan(radians(an)) s = sin(radians(an)) c = cos(radians(an)) print('O ângulo de {} tem a tangente de {:.2f}. \nO ângulo de {} tem o seno de {:.2f}. \nO ângulo de {} tem o cosseno de {:.2f}.'.format(an, t, an, s, an, c))
cf231e55c68e90e0cf6334ab13286bd140164514
DiogoM14/Python-Exercicios
/Curso/ex039.py
302
3.875
4
idade = int(input('Qual é a tua idade? ')) if idade == '18': print('Está na hora de ires à inspeção!') elif idade < 18: n = 18 - idade print('Faltam {} anos para ires para a inspeção!'.format(n)) else: n2 = idade - 18 print('Já foste à inspeção há {} anos!'.format(n2))
43c7d21b47a9ac1ab62c21fd56cc2c70108681d6
DiogoM14/Python-Exercicios
/Curso/ex003.py
153
3.84375
4
n1 = int(input('Digite o número: ')) n2 = int(input('Digite outro núemro: ')) s = n1+n2 print('O a soma do número {} e {} é de {}'.format(n1,n2,s))
2e9328c7edd2ae04354c253b69e66901c01aa33e
DiogoM14/Python-Exercicios
/Curso/ex043.py
659
3.703125
4
peso = float(input('Qual é o teu peso em KG? ')) altura = float(input('Qual é a tua altura? ')) imc = peso / (altura * altura) if imc < 18.5: print('O teu IMC é de {:.2f}, estás a \033[31mbaixo\033[m do peso!'.format(imc)) elif 18.5 <= imc < 25: print('O teu IMC é de {:.2f}, estás com o peso \033[38mideal\033[m...
415610dd65f08b57b0f52fb07c41077c468ef39e
DiogoM14/Python-Exercicios
/Curso/ex004.py
352
3.75
4
n = input('Digite algo: ') print('O tipo primitivo desse valor é',type(n)) print('É alfanumérico?',n.isalnum()) print('É número?',n.isnumeric()) print('É alfabético?',n.isalnum()) print('Tem espaços?',n.isspace()) print('Está em maúsculas?',n.isupper()) print('Está em minúsculas?',n.islower()) print('EStá capitalizada?...
f170a6023f6c27d8c4e1b77ff865275fa33dd551
david-ryan-alviola/winter-break-practice
/hackerRankPython.py
1,977
4.40625
4
# 26-DEC-2020 # Print Hello, World! to stdout. print("Hello, World!") # Given an integer, , perform the following conditional actions: # If is odd, print Weird # If is even and in the inclusive range of 2 to 5, print Not Weird # If is even and in the inclusive range of 6 to 20, print Weird # If is even and grea...
ef91805f7126ffcc763322a620fab29c6ba2dbab
Osama-Abdul-Ghafoor/Coding-Practice
/MakingItPalindrome.py
879
3.765625
4
def countMin(str): Check=0 Counter=0 midpoint=0 SoFarLength=0 for iterator in range(len(str)): if iterator>1 and Check==0: if str[iterator]==str[iterator-2]: Check=1 Counter+=1 SoFarLength=iterator-2 midpoint=iterat...
34f4397a7ead727bcd3dfe759fe87c3575b3ea2a
Lebhoryi/Leetcode123
/59. 螺旋矩阵 II.py
530
3.609375
4
# coding=utf-8 ''' @ Summary: @ Update: github.com/cy69855522/Shortest-LeetCode-Python-Solutions @ file: 59. 螺旋矩阵 II.py @ version: 1.0.0 @ Author: Lebhoryi@gmail.com @ Date: 2/19/20 10:39 PM ''' def generateMatrix(n: int) -> [[int]]: res, n = [[n ** 2]], n ** 2 while n > 1: # 逆向思考,从中心散发一点到最外圈...
803c7f03efcb6fbce8e8a685206f95140a86e3bc
Lebhoryi/Leetcode123
/旋转数组的最小数字.py
951
4
4
# coding=utf-8 """ https://blog.csdn.net/u010005281/article/details/79823154 @ Summary: 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减排序的数组的一个旋转,输出旋转数组的 最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。NOTE:给出的所有元素都大于0,若数组大小为0, 请返回0。 @ Update: @ file: 旋转数组的最小数字.py @ version: 1.0.0 @ Author: Lebhoryi@gmail.com @ Date:...
f7db488e67bd2a78669aa66d8bb5534366ef450f
Lebhoryi/Leetcode123
/70. 爬楼梯.py
618
3.546875
4
# coding=utf-8 ''' @ Summary: DP, dp[i] = dp[i-1] + dp[i-2]; 斐波那契 @ Update: @ file: 70. 爬楼梯.py @ version: 1.0.0 @ Author: Lebhoryi@gmail.com @ Date: 2/23/20 10:10 PM ''' def climbStairs(n: int) -> int: # 超时 # if n <= 2: return n # return climbStairs(n-1) + climbStairs(n-2) # 时间复杂度 O(n) 空间复杂...
200b5f33f14ed164c217aa6434581884cc9339c7
Lebhoryi/Leetcode123
/75. 颜色分类.py
1,118
4
4
# coding=utf-8 ''' @ Summary: @ Update: @ file: 75. 颜色分类.py @ version: 1.0.0 @ Author: Lebhoryi@gmail.com @ Date: 2/25/20 12:19 AM ''' def sortColors(nums: [int]) -> None: """ Do not return anything, modify nums in-place instead. """ # 简单版快排,使用了额外的空间,不符合题意,做升级版 # if not nums or len(num...
dd9590f4194a1b901f642413425ee7a44df07fbe
Lebhoryi/Leetcode123
/74. 搜索二维矩阵.py
661
3.625
4
# coding=utf-8 ''' @ Summary: 先获取首列,然后二分类找到这个数所在的行,然后进行判断 @ Update: @ file: 74. 搜索二维矩阵.py @ version: 1.0.0 @ Author: Lebhoryi@gmail.com @ Date: 2/24/20 9:59 PM ''' import bisect def searchMatrix(matrix: [[int]], target: int) -> bool: if not matrix or not matrix[0]: return False col = list(list(zip(*...
bed97d63401f758a0a626e03e24e8d601539fe19
kokkondaspandana/sample_project
/Hackerrank/date_time/calender_module.py
183
3.859375
4
from calendar import weekday,day_name MM,DD,YYYY=[int(i) for i in raw_input().split()] print day_name[weekday(YYYY,MM,DD)].upper() Sample Input 08 05 2015 Sample Output WEDNESDAY
400b46282bfa228f86d6e51be7e8c320e960c852
CarlosFdez/SpueBox
/plugins/musicplayer/songrequestlist.py
2,414
3.609375
4
import collections import random class SongRequestList: "Represents a queue of songs that can be manipulated" def __init__(self): self.shuffle = False self.loop = False # Contain the list of songs and upcoming songs. # The original list is kept to support looping (aka reloadin...
1586e65d5151b3ab53623c01912590ae5ee1bdf6
louisryann/leetcode
/28. 实现strStr().py
650
3.875
4
''' 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 ''' class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ #解法1 #return haystack.find(needle) #...
dff5bbfadaba8d026ab8f50060fd6449f2a2bc9d
arturfil/data-structures-and-algorithms
/trees/binary_search_tree.py
5,796
4.03125
4
class Node: def __init__(self, value=None): self.value = value self.left_child=None self.right_child=None self.parent=None class BinarySearchTree: def __init__(self): self.root=None def insert(self,value): if self.root==None: self.root = Node...
10eadac8c43d0dab3039732e0fa8b497a875c3b7
arturfil/data-structures-and-algorithms
/sort/insertion_sort.py
453
4.21875
4
def insertion_sort(arr): # traverse through index 0 to len(arr) for i in range(1, len(arr)): current_value = arr[i] position = i while position > 0 and arr[position - 1]>current_value: arr[position] = arr[position-1] position = position - 1 arr[position] = current_value # testing al...
7ec78a69356e9c9c7fc7225d906f98a847d17df7
arturfil/data-structures-and-algorithms
/trees/tree.py
923
3.859375
4
# simple implementation of a tree: List of Lists aka [[1,2,4],[2,4,5],[2,3,4]]. This could also be refered as a matrix # I don't particularly like this way of making a binary tree, I prefer using a close with Root LeftNode & RightNode def BinaryTree(r): return [r,[],[]] def insertLeft(root, newBranch): t = root.p...
f4d36bdea706ff1a4794cfb8d0bd7ffb198ef834
Aasiefkhan/protothon01
/problem 3.py
225
3.78125
4
list=[1] for i in range (10): print(list) appender = [] appender.append(list[0]) for i in range (len(list)-1): appender.append(list[i]+list[i+1]) appender.append(list[-1]) list=appender
701c8ac9df8e1544c22b63d94e2894fbf20ab04c
PaulGG-Code/Security_Python
/Simple_File_Character_Calculator.py
242
4.1875
4
#open file in read mode file = open("D:\data.txt", "r") #read the content of file data = file.read() #get the length of the data number_of_characters = len(data) print('Number of characters in text file :', number_of_characters)
5905267e4d06d8f0ffa4cce5a6215422a7a592a3
Chinwonoble/python-tutorials
/variable.py
394
3.984375
4
x = 1 y = 2.5 name = 'John' is_cool = True fav_colors = ['white', 'grey', 'black'] # assignment give 5 examples of variable names and assign values to tehm of different types a = 4 g = 5.5 name = 'noble' is__sunny = False footballers = ['ronaldo', 'messi', 'pulisic'] ''' this is a python class where we will be learn...
590a7dc3834e2936ac5a292e68e60dff1707f37e
mububoki/nested-dataclasses
/sample/main.py
266
3.546875
4
from dataclasses import dataclass from nesteddataclasses import nested_dataclass @dataclass class A: aa: int ab: str @nested_dataclass class B: bb: str ba: A data = {'bb': 'str_bb', 'ba': {'aa': 1, 'ab': 'str_ab'}} b = B(**data) print('b:', b)
835f358f71f3a8e6361c2c5fa0a8ed765e58386b
jakupierblina/learning-python
/tutorial/set.py
1,059
4.1875
4
x = set('abcde') y = set('bdxyz') print('e' in x) # membership print(x-y) #difference print(x | y) #union print(x & y) #intersection print(x ^ y) #symmetric difference print(x > y, x < y) #superset, subset z = x.intersection(y) #find the same elements z.add('SPAM') print(z) z.update(set(['X', 'Y'])) #update the se...
0f79919381ad193f554ff0179856ed30832fa54e
stephenchenxj/myLeetCode
/isBipartite.py
3,210
3.75
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 23 20:33:44 2019 @author: stephen.chen 785. Is Graph Bipartite? Medium Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge i...
aa567964702607f6d3e2069bd372120294293969
stephenchenxj/myLeetCode
/mergeTwoLists.py
2,016
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 5 10:53:58 2019 @author: dev """ #Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ ...
24be92623597fdc0a483010dbdfa30a68a4c1d23
stephenchenxj/myLeetCode
/1071_greatestCommonDivisorOfStrings.py
1,392
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 23 15:55:27 2020 @author: stephenchen 1071. Greatest Common Divisor of Strings Easy 320 86 Add to List Share For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times) Return the larg...
18fb6fcca47e2afe459ed4a2f8c2cbcd85bd0877
stephenchenxj/myLeetCode
/getSum.py
1,319
3.75
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 7 03:20:55 2019 @author: stephen.chen Sum of Two Integers Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = -2, b = 3 Output: 1 """ class Solution(object...
7d31f46b56ff240017a5b267c61da3edeeb7832d
stephenchenxj/myLeetCode
/intersect.py
2,088
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 20 20:48:25 2019 @author: dev 350. Intersection of Two Arrays II Easy Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 =...
2283bc44b0cd38401b9c7b0c237515be359f2bf8
stephenchenxj/myLeetCode
/countAndSay.py
1,568
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 20:14:28 2019 @author: stephen.chen The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off...
d21a0f2c4e745a0ca8e332694a1c0c93d516110f
stephenchenxj/myLeetCode
/dailyTemperatures.py
1,572
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 2 21:06:45 2019 @author: dev """ class Solution(object): def dailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """ num = len(T) days = [0]*num biggersIndex = [...
6681e1889c4408a8740bf7ca0abbb1b8dd60ce67
stephenchenxj/myLeetCode
/694_Number of Distinct Islands.py
2,247
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 28 12:05:14 2020 @author: chen 694. Number of Distinct Islands Medium 676 43 Add to List Share Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) Y...
169351b90fdc1ce2b4356b877fc59afd5562f9a3
stephenchenxj/myLeetCode
/deleteNode.py
1,893
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 6 02:14:38 2019 @author: stephen.chen Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which looks like following: 4 -> 5 -> 1 -> 9 Example 1: Input: head = [4,5,1,...
0a4cf1075711c3b98b5d6dfd88b0065aec99c044
stephenchenxj/myLeetCode
/findDiagonalOrder.py
1,512
4.15625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. 498. Diagonal Traverse Medium Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1...
254a6146ad1725a9d4852d911ebba4a37b7063c3
stephenchenxj/myLeetCode
/topKFrequent.py
1,042
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 3 15:16:13 2019 @author: dev """ from collections import defaultdict class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if k ==...
1bfdabd0cec2c25f14bf4b00ad447586de4c9130
stephenchenxj/myLeetCode
/rotate.py
733
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 3 15:29:50 2019 @author: dev """ 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. """ r...
f8ff8c47fe3b6f6532182ec3474a1405f8293638
stephenchenxj/myLeetCode
/reverseInteger.py
1,146
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 00:44:11 2019 @author: stephen.chen """ ''' Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer r...
3a17bc4469643bab67b0f5f2e21d67b37010a32c
stephenchenxj/myLeetCode
/python_cheat_sheet.py
2,476
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 13 15:19:48 2020 @author: chen """ strList = ['1', '2', '3', '4', 'a', 'b', '.', 'z'] string = ':'.join(strList) print(string) string = ''.join(strList) print(string) print(type(strList)) def convert(lst): return ' '.join(lst).split() ...
2b25b8e15b8e2f5d49cb1d008031dc0f14b6b4e1
stephenchenxj/myLeetCode
/canVisitAllRooms.py
903
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 23 21:51:33 2019 @author: dev """ class Solution(object): def canVisitAllRooms(self, rooms): """ :type rooms: List[List[int]] :rtype: bool """ visitedRoom = set() visitedRoom.add(0) ...
da0019078824aa244442fbf23e20fb33814c05af
stephenchenxj/myLeetCode
/shuffle.py
1,386
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 11 20:26:42 2019 @author: stephen.chen Shuffle an Array Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any...
0bfdcb57aea18a8af3f02282a10792ad120ea7a0
stephenchenxj/myLeetCode
/twoSum_2.py
1,007
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 2 16:43:01 2019 @author: dev """ class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ ''' for i in range(len(num...
89da494a7cae93de6c64d9220ff8a598c14499e0
stephenchenxj/myLeetCode
/python_search_dict_by_value.py
220
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 13 15:06:15 2020 @author: chen """ mydict = {1:'a', 2:'b', 3:'a'} value = 'a' keys = [ key for key,val in mydict.items() if val==value ] print(keys)
05d521405c6ffe03a658e474386e5863a4c93434
goutham470/UVa-Online-Judge
/Volume100/10035 - Primary Arithmetic.py
523
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 27 23:28:53 2019 @author: gouth """ def carries(a,b): carry=0 count=0 while a!=0 or b!=0: if a%10+b%10+carry >=10: count+=1 carry=1 elif a%10+b%10+carry <10: carry=0 print(a,b) a,b=int(a/...
7f0aeba4c78b966786583c61f3601ef496cd5d45
elledriver/Programming_Languages
/Python/1.Learning_Basics/level_2.py
2,728
4.0625
4
from collections import deque #Library for queues """ Tuples, sets, dictionary, stack, queues, format """ #Tuple (inmutable, does not support item assignment) t = ("Elle", "Manuel", 10, [1,2,3], -80) t[3] print(len(t)) print (len(t[3])) t.index("Manuel") #find position t.count(10) #number times value in tuple. #Se...
b9b8aa7db9bbcd6f58389b86e73fd1d90cdbe443
ArtemArtemenko1/labor
/lab2/lr2.2.py
943
4.03125
4
#Організація циклу за допомогою оператора while #Дано ціле число, що складається з різних цифр. Визначити, яка з цифр заданого числа більше, тобто знайти найбільшу цифру числа. import re def check_input(user_input): pattern = r"^-?\d+(.\d+)?$" user_input=input() while not re.match(pattern,user_input):...
b02d9b540e459fb6f9f3aeb584c5fbeccc308916
LukasNickel/aoc
/dummy/solution.py
399
3.5
4
def part1(puzzle): return -1 def part2(puzzle): return -1 def main(): with open('input') as f: puzzle = f.readlines() with open('example') as f: example = f.readlines() assert part1(example) == 0 print('Solution Part 1:', part2(puzzle)) assert part2(example) == 0 pr...
1b2ea5e343cc25264f4de24b27cee54ba6485715
AntonioHazboun/ML-Methods-from-Scratch
/Decision Trees and Prior Probability/code/metrics.py
2,964
4.03125
4
import numpy as np def confusion_matrix(actual, predictions): """ returns 2*2 confusion matrix assuing binary data values as per [ [true_negatives, false_positives], [false_negatives, true_positives] ] Args: actual (np.array): actual labels of length N ...
e53c7a19546d5f27f630fe4e559607134dcbc43e
AntonioHazboun/ML-Methods-from-Scratch
/K-Means Clustering and Gaussian Mixture Models/code/kmeans.py
3,198
3.734375
4
import numpy as np def euclidean(a,b): return np.linalg.norm(a-b) class KMeans(): def __init__(self, n_clusters): """ Implements traditional KMeans algorithm with hard assignments using two steps 1. Update assignments 2. Update the means Args:...
fad5072101686f87f97f9d014e30b6d3c66f68f7
tim-mccabe/python-challenge
/PyBank/main.py
2,350
3.875
4
# First we'll import the os module import os # Module for reading CSV files import csv csvpath = ("budget_data.csv") with open(csvpath) as csvfile: # Split the data on commas csvreader = csv.reader(csvfile) #read the header row header = next(csvreader) #set variables to use as counters Months = 0...
b0ba8f4f5411931d0d106a1e4ff75c15deb4a32c
christian-alexis/edd_1310_2021
/colas.py
2,818
4.15625
4
#PRUEBAS DE LAS COLAS class Queue: def __init__(self): self.__data = list() def is_empty (self): return len(self.__data)==0 def length(self): return len(self.__data) def enqueue(self,elem): self.__data.append(elem) def dequeue (self): i...
c20080aa0a84d7f9fb4b33091a966fafe2d76db8
vsviroje/assignment8
/Assignment8_4.py
925
3.546875
4
from threading import * def small(n): sum=0 for i in range(len(n)): if n[i] >= 'a' and n[i] <= 'z': sum = sum + 1 print("s", sum) print(current_thread().ident) def big(n): sum=0 for i in range(len(n)): if n[i]>='A'and n[i]<='Z': sum=sum+1 print("b",su...
8bd21e8f1cdc740b1dd7667ec8debd73299eb998
navinkumar-choudhary/TestPythonProject
/ClassDemoOne.py
571
3.8125
4
# Data Encapsulation Concept class Calculator: name = "" price = 0 def Details(self): print(self.name+'\'s'+ " Price is "+str(self.price)) def SetDetails(self, name1, price1): self.name = name1 self.price = price1 camel = Calculator() camel.name = "Camel" cam...
c884324d506e9ea5d5853ed8849c7ae81c3ad976
navinkumar-choudhary/TestPythonProject
/WHILELoopDemo.py
90
3.578125
4
# while condition/expression # stmts n=10 while n>0: print(n) n-=1
7a5d566ef0aa2b419b5f6fc6c7974a0d44d053b2
navinkumar-choudhary/TestPythonProject
/OverLoading.py
211
3.90625
4
# OverLoading def Add(n1, n2, n3=0): return(n1+n2+n3) # Add(5,5) # function with Return keyword this won't work we need use the Call as Below # Add(5,4,10) print(Add(5, 6, 5)) print(Add(5, 10))
2a665b0de325a2752cca744fd571faadc0708970
navinkumar-choudhary/TestPythonProject
/ExceptionHandling.py
777
3.625
4
import sys num1 = 10 num2 = 5 arr = [10, 20, 30] result = 0 try: result = num1/num2 except ZeroDivisionError: print("Error: ", sys.exc_info()[1]) finally: print("Finally Executed....... for 1st try") try: print(arr[5]) except IndexError: print("Error: :", sys.exc_info()[1]) # ...
0fd7c11542e95bd3522dd6ffaf44f186991c4476
navinkumar-choudhary/TestPythonProject
/mainDemo.py
334
3.625
4
name = "Navin" def fun(x): print("value from fun one: ",name) print("X value before modification in Fun1: ", x) x = 100 print("X value after modification in Fun1: ", x) def main(): print("Hi") print("Value from main: ",name) x=20 fun(x) print("Value of x in main method: ...
13be0771d68534e54b7022de0f57bfcae01d769b
navinkumar-choudhary/TestPythonProject
/Inheritance2.py
494
3.796875
4
class Vehicle: def __init__(self,c,p): self.color = c self.price = p class Car(Vehicle): def __init__(self, c, p, t): super().__init__(c ,p) self.numberOfTyres = t class Bike(Vehicle): def __init__(self, c, p, t): super().__init__(c ,p) self.numberO...
0ffe4afc95e64efe667b76c42dbae97687b2160d
mendozatori/python_beginner_proj
/rainfall_report/rainfall_report.py
1,305
4.3125
4
# Average Rainfall Application # CONSTANTS NUM_MONTHS = 12 # initialize total_inches = 0.0 # input years = int(input("How many years are we calculating for? ")) while years < 0: print("Please enter a valid number of years!") years = int(input("How many years are we calculating for? ")) ...
3b811ee60b5aee105510e413af107661e2127836
tenzin1308/PythonBasic
/Class/TypesOfMethods.py
711
4.125
4
""" We have 3 types of Methods: a) Instances/Object Methods b) Class Methods c) Static Methods """ class Student: # Class/Static Variable school = "ABC School" def __init__(self, m1, m2, m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 # Instances/Object M...
4f14448ae61f18ddf0470f8f284491f4e82da2d4
qeqar/advent-of-code
/2019/day06.py
766
3.59375
4
#!/usr/bin/env python import networkx import matplotlib.pyplot as plt graph = networkx.Graph() with open('inputs/day06.txt') as f: orbits = f.readlines() #orbits = ["COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", "E)J", "J)K", "K)L"] #orbits = ["COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", ...
460cc50a969285738d149478f0e258374f2182aa
acardilini/intro-to-programming-nanodegree
/stage3/rename_files.py
606
3.796875
4
import os import string def rename_files(): files = os.listdir("/Users/jess/adam/ipnd-starter-code-master/stage_3/lesson_3.2_using_functions/secret_message/prank") saved_path = os.getcwd() print("Current Working Directory is "+saved_path) os.chdir("/Users/jess/adam/ipnd-starter-code-master/stage_3/less...
0b40e747cde5f8ce90430d354cae360451f9216e
bufan77/InterviewQuestion
/5.py
11,451
3.875
4
# 26 Python的is # is是对比地址,==是对比值 # 27 read,readline和readlines # read 读取整个文件 # readline 读取下一行,使用生成器方法 # readlines 读取整个文件到一个迭代器以供我们遍历 # 28 Python2和3的区别 # 推荐:Python 2.7.x 与 Python 3.x 的主要差异 # 29 super init # super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes...
259a74c2e2274ddbd9fd517af07f3694abca0451
NiltonGMJunior/codeforces-problem-set
/935A/fafa_and_his_company.py
371
3.578125
4
# Codeforces # #935A - Fafa and his Company # http://codeforces.com/problemset/problem/935/A # 12/01/2019 # Nilton G. M. Junior if __name__ == '__main__': num_employees = int(input()) possible_ways = 0 for num_leaders in range(1, num_employees // 2 + 1): if num_employees % num_leader...
a26dd1a838cdd1e027421286d2acb7897193f069
Sumitsahu896/My_LeetCode_Solutions
/product-of-array-except-self/product-of-array-except-self.py
858
3.578125
4
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: # The length of the input array length = len(nums) # The left and the right array with the answer answer = [0]*length # The left array holds the product of all the elements t...
97c6266634ee0fb49f378a3471924132d3f67d18
gcruzrios/master-python
/19-bases-datos/sqlite.py
1,350
3.765625
4
import sqlite3 #Conexion conexion = sqlite3.connect('./19-bases-datos/pruebas.db') #crear cursor cursor = conexion.cursor() #crear tabla cursor.execute("CREATE TABLE IF NOT EXISTS productos (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "titulo varchar(255),"+ "descripcion text,"+ "precio int(255)"+ ")") conex...
aef61021b9dec0d217df5df42c8ce560669422e1
gcruzrios/master-python
/16-POO-clases/main.py
1,240
4.09375
4
# OOP Programación orientada a Objetos # Definir una clase # Carro / coche class Coche: #atributos o propiedades color = "Rojo" marca = "Ferrari" modelo ="Aventador" velocidad=300 caballaje=500 plazas=2 #metodos o funciones def setColor(self,color): self.color = color ...
97fb485940a3e6fe71aaef90e77c4bd01a472f2a
gcruzrios/master-python
/07-ejercicios/ejercicio8.py
270
3.890625
4
# porcentaje de un número numero = int(input("introduce el un número: ")) porcentaje = int(input(f"introduce el porcentaje del número: {numero} que quieres obtener: ")) operacion = (numero * (porcentaje/100)) print(f"El {porcentaje} % de {numero} es: {operacion}")
761f70bb1e80cf2a27e33c05fa1cc85e9c92c036
SolangeUG/nltk-book
/06-learning-to-classify-text/exercises.py
1,821
3.578125
4
import nltk import random from nltk.corpus import movie_reviews # List of documents, labeled with the appropriate categories, # chosen from the Movie Reviews Corpus, which categories each review as positive or negative documents = [ (list(movie_reviews.words(fileid)), category) for category in movie_reviews.ca...
9d315b603d6388f35fd3a1468be06fffbfc9d313
pc2459/learnpy
/partial_pdf.py
995
3.65625
4
""" Programme that extracts pages from a PDF within a given range using GUI elements """ from easygui import * from pyPdf import PdfFileWriter, PdfFileReader #let user choose file using fileopenbox input_filename = fileopenbox("","Select a PDF to extract from...","*.pdf") # choose beginning page using enterbox st...
23f386c4f97055645a6724a76dc49f3b7a93c93b
pc2459/learnpy
/csv_parse.py
2,455
4.15625
4
""" Write a script that will take three required command line arguments - input_file, output_file, and the row_limit. From those arguments, split the input CSV into multiple files based on the row_limit argument. Arguments: 1. -i: input file name 2. -o: output file name 3. -r: row limit to split Default settings: 1. ...
da75fe91a98fc2861ee2fbf266e5223eeac0c9b4
austincunningham/python_exercises
/5_Miles_to_Feet.py
275
4.21875
4
#!/usr/bin/python3 def Miles_to_Feet(Miles): feet = (Miles * 5280) print ("%1.0f feet in %1.0f miles" %(feet,Miles)) def main(): print("Enter number of miles to convert to feet") mile = input(">") Miles_to_Feet(mile) if __name__=='__main__': main()
1dcef0331a46fdd68ad0d8c524b523dc4470186a
NoviceNi/Python-practices
/practice021.py
164
3.65625
4
#!/usr/bin/python def cal(x): if (x - (x / 2 + 1)) == 1: print x else: cal(x - (x / 2 + 1)) total = 1 for i in range(10): total = total
0118c258e960b17d058cdf3dddcd64483044aa97
webclinic017/Onepiece
/python/leetcode/two_sum.py
844
3.625
4
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ result = [] tempList = [] for index, value in enumerate(nums): if (len(tempList) == 0): tempList.appe...
2acdb967655d4dfabbad0f9b2d0aab3ed2f6837b
webclinic017/Onepiece
/python/spider/hkstockspider.py
2,069
3.59375
4
import pandas_datareader as data import pandas as pd from datetime import datetime # We would like all available data from 01/01/2000 until 12/31/2016. start_date = '2018-08-01' end_date = '2018-08-31' stock_code = '2800.HK' start = datetime(2018, 8, 22) end = datetime(2018, 9, 22) # User pandas_reader.data.DataRead...
302dc30c30b7b891ab7507edf7a4be4ee440f6a2
webclinic017/Onepiece
/python/pandas/pandasLesson8.py
1,733
3.5
4
import random import string import pandas as pd import numpy as np np.random.seed(0) # This is the total number of groups to be created NumberOfGroups = 50000 # Create a lot of groups (random strings of 4 letters) Group1 = [''.join(random.choice(string.ascii_uppercase) for _ in range(4)) for x in range(int(Number...
4f551231e782ab7cdd6df733355d84b61589a0a9
guiaugusto/university_annotations
/Quinto_Semestre/UVA/SuperSale/teste.py
221
3.546875
4
fat = [] def fator(n): if n == 0: fat.append(0); elif n == 1: fat.append(1); else: fat.append(n*fat[n-1]) n = int(input()) i = 0 while i <= n: fator(i) i += 1 print(fat[n])
6870aeb00b2b139ebd8e5e9b935e17ac4b4075f8
evgranato/Python-Course-Code
/Dictionaries/dictionary_methods.py
4,218
3.75
4
# ***Dictionary Methods*** # Clear # instructor.clear() # this will erase everything # instructor = { # "name" : "Colt", # "owns_dog" : True, # "num_courses" : 4, # "favorite_language" : "Python", # "is_hilarious" : False, # 44: "my favorite number!" # } # Copy # c = instructor.copy() # now c ha...
e69777826368a7c672e29bb26d0532911054bbf4
evgranato/Python-Course-Code
/Functions/functions_part2.py
6,651
4.59375
5
# ****FUNCTIONS PART 2**** # ***OBJECTVIES*** # use the * and ** operator as parameters to a function and outside of a function # leverage dictionary and tuple unpacking to create more flexible functions # *args # a special operator we can pass to functions # gathers remaining arguments as a tuple # this is just a par...
ad281de1757d8b1aae62e4f01f8b22269a53a75d
evgranato/Python-Course-Code
/Review Files/tic_tac_toe.py
1,424
3.953125
4
import random def draw_board(board): print(" | |") print('' + board[7] + '|' + board[8] + '|' + board[9]) print(' | |') print('----------') print(' | |') print('' + board[4] + '|' + board[5] + '|' + board[6]) print(' | |') print('----------') print(' | |') print('' + board[1] + ...
8822fa3af685612b84b0f0e149b81411520b6ae7
evgranato/Python-Course-Code
/CSV and Pickling/csv_pickling.py
8,551
4.53125
5
# **READING CSV FILES** # - CSV files are common for tabulated data # - We can read CSV files just like text files # - Python has a built-in CSV module to read/write CSVs more easily # **CSV MODULE** # - reader - lets you iterate over rows of the CSV as lists # - DictReader - lets you iterate over rows of the CSV as O...
2e677c69608aa439fccb69258ab7b6f8512d4c32
evgranato/Python-Course-Code
/HTTP/http.py
4,166
4.1875
4
# ***HTTP INTRODUCTION*** # write python code that talks to websites (API requests etc) # OBJECTIVES: # - describe what happens when you type a URL in the URL bar # - describe the request/response cycle # - explain what a request or response header is, and give examples # - explain the different categories of response ...