blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7674728f41057eb267f26c67c79d8bdb69f105ec | mihirjain97/practice | /listComprehension.py | 663 | 3.796875 | 4 | names = ['Joe', 'John', 'Sushant', 'Krisha', 'Tanvi']
l = []
for person in names:
l.append(person)
print(l)
print([person for person in names])
lst = []
for person in names:
lst.append(person + ' dumped me.')
print(lst)
print([person + ' buddies foreever.' for person in names])
lst = []
movies_and_ratings ... |
364a7860ce186c8fb2a203f2d12f100c3be49738 | mshubat/Data-Structures-Algorithms | /4 - Trees and Graphs/45-validate_bst.py | 1,530 | 4.25 | 4 | '''
Implement a function to check if a binary tree is a
binary search tree.
Method 1:
In order traversal of the tree, checking that each element
which is printed is larger than the element before it. If
the items are in order than the ordered property of the
tree is correct.
'''
from BST.binary_search_tree import ... |
2081f6f777cdd0d60d5890eea942cada79b5a723 | mshubat/Data-Structures-Algorithms | /10 - Sorting and Searching/Sorting Algorithms/MergeSort.py | 1,462 | 4.25 | 4 | '''
Merge Sort Description:
Merge sort divides the array in half and sorts each of
those halves, then merges them back together. Each half
has the same sorting algorithm applied to it until each
half contains only one number. The merge does the "heavy
lifting".
Time Complexity: O(n*logn)
Space Complexity: O(n) [Depen... |
39c47ac47b2999a062084cc31bf142ff04779193 | mshubat/Data-Structures-Algorithms | /4 - Trees and Graphs/42-minimal_tree.py | 1,029 | 4.09375 | 4 | '''
Given a sorted (increasing order) array with unique
integer elements, write an algorithm to create a binary
search tree with minimal height.
'''
from BST.binary_search_tree import binary_search_tree
def insert_middle(array, bst):
mid = len(array)//2 # find midpoint
bst.insert(array[mid])
if len(... |
c0137261ec9a03ff436e4fa12a8376e7c29064a1 | kamvir/Python_Tutorials | /Arithmetic_Operators/arithmetic_operators.py | 1,359 | 4.0625 | 4 | title = '==================================== Arithmetic Operators in Python ===================================='
print(title)
note = 'Note :: Please refer code for better understanding.'
print(10 + 3) # Outputs :: 13 >> Addition
print(10 - 3) # Outputs :: 7 >> Subtraction
print(10 * 3) # Outputs :: ... |
ebae57eef0554423636373bbcf3f7011d104b7e7 | kamvir/Python_Tutorials | /Lists/list_methods.py | 1,675 | 4.1875 | 4 | title = "=============== List methods ==============="
note = "Note :: Please refer code for better understanding"
print(title)
numbers = [5, 2, 1 , 7, 4]
numbers.append(20) # Adds list item.
print(numbers) # Outputs: [5, 2, 1, 7, 4, 20]
numbers.insert(0, 10) # Inserting list item on a particular i... |
f7399644c83eefd97e53c9aa15e19d908c80fe0c | kamvir/Python_Tutorials | /Strings_in_python/strings_in_python.py | 1,256 | 4.375 | 4 | title = '============================= Strings in Python ============================='
print(title)
note = 'Please refer code for better understanding'
course = 'Python for Beginners'
print(course)
course = "Python's Course for Beginners"
print(course)
course = 'Python for "Beginners"'
print(co... |
0b82ddb280f8a0290a76b8098a310be092345ceb | pytommaso/Appunti | /13 - Generators_0.py | 891 | 4.3125 | 4 |
# generators:
# doesnt return and exit, like functions
# they automatically suspend and resume in the last point
# of value generation
# with giant list in memory
def create_cubes(n):
result = []
for x in range(n):
result.append(x**3)
return result
create_cubes(10) # ---> giv... |
dd3d91e1a9fa5c560fa22317e32d8212b80a51d9 | pytommaso/Appunti | /Tools/5 - Tools_Built in function.py | 983 | 3.734375 | 4 |
# builtinfunction
__import__() help() min() tuple()
abs() id() next() type()
ascii() input() open() zip()
bool() int() print()
dict() iter() range()
dir() len() reversed()
enumerate() ... |
9038dc3729cfa89009e6e3ee41ef6038884320f3 | pytommaso/Appunti | /13 - Generators_1_Fibonacci.py | 333 | 3.578125 | 4 |
def gen_fibon(n):
a = 1
b = 1
for i in range(n):
yield b
#a = b
#b = a + b
a,b = b,a+b
# # ATTENZIONE:
# a = b
# b = a + b
# # E' DIVERSO DA: perchè nel primo l'espressione iniziale
# #variando varia la seconda
# a,b = b,a+b
for n in gen_fibon(10):
... |
bc232cb81353a81d082fcd04c7dd851e43bbffa6 | jogubaba/PythonScripts | /4example.py | 165 | 4.15625 | 4 | Price = input("Enter price for the retail items you have taken one after the other ")
Cost = int(Price)
total = 0
for list in Cost:
total += list
print(list) |
cbfb4c0e9d8efffe4e7db17f75a34d0b3668d50f | jogubaba/PythonScripts | /5Variables.py | 157 | 3.5 | 4 | price = 20
Quantity = 10
Rating = 2.5
Place = 'Hyderabad'
print(Place)
#print ("This item will cost you" /price)
print(price)
print(Quantity)
print(Rating)
|
01429aefdf4ee48da8cd9e451a08d20f7848ca43 | jogubaba/PythonScripts | /20ifelse.py | 341 | 4 | 4 | is_hot = True
#is_cold = False
if is_hot:
print("It's a very hot day")
print("Stay inside your home and drink plenty of water")
#elif is_cold:
#print("It is very cold outside, stay in, keep yourself warm and do your home work")
else:
print("Just go around the town and shop for your birthday")
print("Ha... |
635e7fb013185aa53b44b6e8d16d63b91b97e858 | jogubaba/PythonScripts | /22sed.py | 594 | 3.6875 | 4 | file = open('/home/jogubaba/Downloads/My List', 'r')
f_contents = file.readlines()
sn = open('/home/jogubaba/Downloads/servervmname', 'r')
contents = sn.readlines()
for f_contents in contents:
print(contents)
else:
print("Not in List")
#another
keywords = input("Please Enter keywords path as c:/example/ \n... |
fa509e354fdb30329fc7fc4588dd1754423d5502 | elenatheresa/CSCI-242 | /Fall 2019/Homework/HW7-CorpusE/HW7Q4B-CorpusE.py | 1,667 | 3.6875 | 4 | import heapq
from collections import defaultdict
def encode(frequency):
heap = [[weight, [symbol, '']] for symbol, weight in frequency.items()]
heapq.heapify(heap)
while len(heap) > 1:
lo = heapq.heappop(heap)
hi = heapq.heappop(heap)
for pair in lo[1:]:
pair[1] = '0' +... |
e469ab51c338c9804e2e5399b10640b2457d7e4e | elenatheresa/CSCI-242 | /Fall 2019/Homework/HW2 - CorpusE/HW2-Q2.py | 4,061 | 3.765625 | 4 | #Elena Corpus
#CSCI 242 - HW 2
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert( node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
... |
398dede051dfdcd9a524dd522dc677a8da565b84 | AloriumTechnology/AloriumTech_CircuitPython_EvoM51 | /examples/neo_blue.py | 530 | 3.546875 | 4 | """
`neo_blue`
========================================================
Copyright 2020 Alorium Technology
Contact: info@aloriumtech.com
Description:
This is a very simple CircuitPython program that turns the
Evo M51 NeoPixel blue.
"""
from aloriumtech import board, digitalio, neopixel
neo = neopixel.NeoPixel(board... |
8335e214a4436f526f7a1a02fb476566302b9796 | gabrielpaixaom/pythonProject | /ex004-Dissecando Var.py | 415 | 3.984375 | 4 | # Dissecando uma variavel
msg = input("Digite algo: ")
print("O tipo primitivo desse valor é ", type(msg))
print("Só tem espaços? ", msg.isspace())
print("É um número? ", msg.isnumeric())
print("É alfabético? ", msg.isalpha())
print("É alfanumérico? ", msg.isalnum())
print("Esta em maiúsculas? ", msg.isupper())
print(... |
587ba363c01aa2af336ff6dd9c96d608932ad04d | CsacsoBacsi/VS2019 | /Python/PythonTutorial/PythonTutorial/Recursion.py | 596 | 3.59375 | 4 | # --------------------------------------------------------------------
import os
# --------------------------------------------------------------------
def tri_recursion (k): # tri_recursion (def_param = 10) -> Sets the default parameter if none given
if k > 0:
result = k + tri_recursion (k - 1) # (1 + 0... |
d90e467507f304e966646858ce79584be3c0ce85 | CsacsoBacsi/VS2019 | /Python/PythonTutorial/PythonTutorial/RegExp.py | 10,324 | 4.03125 | 4 | # --------------------------------------------------------------------
import re
import os
# *** Matching chars ***
""" MetaCharacters: . ^ $ * + ? { } [ ] \ | ( )
Class [] or set of characters
[abc] or [a-c]
[abc$] $ is not special here!
[^5] complement. Any char but 5. [5^] has no meaning
[a-zA-Z0-9_] = \w
\d Matc... |
e022411992be5e03389f9048a90e3d59ee4f88ae | maheshg81/PyEX | /Analysis/addition.py | 444 | 3.65625 | 4 | import sys
from datetime import datetime
"""This is an example for NumPy"""
import numpy as np
def pythonsum(n):
a = range(n)
b = range(n)
c=[]
for i in range(len(a)):
a[i] = i ** 2
b[i] = i ** 3
c.append(a[i]+b[i])
return c
c = pythonsum(10)
print c
de... |
cd6c932c5bf760c8a9bceac95fdb8371c1c0dacb | maheshg81/PyEX | /DataTypes/Set.py | 244 | 3.734375 | 4 | __author__ = 'ugunipati'
# set : to remove the duplicate elements in lists or tuples
#Lists
name=(1,2,2,3)
print name
example = set(name)
print example
#Tuples
name1=[1,2,2,3]
print name1
example1= set(name1)
print example1 |
b3e84757a4c2f1dc1a93193db58a5ad8b1d011a3 | dfernandez33/CS7650_NLP | /HW3/hw3_skeleton_word.py | 9,300 | 4.0625 | 4 | import math, random
from typing import List, Tuple
################################################################################
# Part 0: Utility Functions
################################################################################
def start_pad(n):
''' Returns a padding string of length n to append to ... |
fdc15fac7634495b4f9f61cf09b279c0bb518932 | danvk/advent2019 | /day14.py | 3,446 | 3.609375 | 4 | #!/usr/bin/env python
import fileinput
import itertools
import math
import re
def parse_component(comp):
"""Parse "10 ORE" -> (10, 'ORE')."""
m = re.match(r'(\d+) ([A-Z]+)$', comp)
assert m, comp
amt, what = m.groups()
return int(amt), what
def read_reactions(inp):
"""Returns map from produ... |
db0c3c6d11b212a33e4261eae5351b699ed06d33 | danvk/advent2019 | /day5.py | 2,246 | 3.5625 | 4 | #!/usr/bin/env python
import fileinput
ADD = 1
MULTIPLY = 2
INPUT = 3
OUTPUT = 4
JUMP_IF_TRUE = 5
JUMP_IF_FALSE = 6
LESS_THAN = 7
EQUALS = 8
STOP = 99
NUM_PARAMS = {
ADD: 3,
MULTIPLY: 3,
INPUT: 1,
OUTPUT: 1,
JUMP_IF_TRUE: 2,
JUMP_IF_FALSE: 2,
LESS_THAN: 3,
EQUALS: 3,
STOP: 0
}
... |
dcfad322afd26b744b22ddfc9cec994b2f6ffb50 | Kasden45/AI-mancala-game-gui | /Components.py | 805 | 3.625 | 4 | from typing import List
# from Player import Player
class Stone:
def __init__(self, color):
self.color = color
def __str__(self):
return str(self.color)
class Hole:
def __init__(self, number, stones, player):
self.stones: List[Stone] = stones
self.number: int = number
... |
25d84109e9fd1478210d158f3f68b2509423310d | HomegrownWookie/QuadraticCalculator | /PA2.py | 513 | 3.984375 | 4 | import math
a = int(input("Enter A: "))
b = int(input("Enter B: "))
c = int(input("Enter C: "))
disc = (b * b) - 4 * a * c
if disc < 0:
print("Complex Number!")
exit()
if a == 0:
print("Not a quadratic function.")
exit()
x1 = (-b + int(math.sqrt(disc))) / (2 * a)
x2 = (-b - int(math.sqrt(disc))) / ... |
5dd4142fba9a8880d7fe4371fc62d742de072a53 | yevsel/C | /Tic Tak Toe/classs.py | 464 | 3.6875 | 4 | class Seperate:
def __init__(self,myArray=[]):
self.myArray=myArray
def even(self):
contain=[]
for i in range(len(self.myArray)):
if self.myArray[i]%2==0:
contain.append(self.myArray[i])
return contain
def odd(self):
container=[]
fo... |
4249579be7adde61d9095626ff9dd90a1d0e94e0 | finchy70/Treehouse | /teacher.py | 1,240 | 3.921875 | 4 | teachers = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
'Kenneth Love': ['Python Basics', 'Python Collections']}
def most_classes(teachers):
max_lessons = 0
max_teacher = ""
for item in teachers:
print(item)
print(len(teachers[item]))
... |
f9bea1b88a3d9ebd41e12e7622a9a6cd996c542e | alexmorenogc/RSADigitalSignature | /rsaAlex.py | 2,324 | 3.828125 | 4 | import random, sys, os
def main():
# Step 1: Ask to user for prime
p_str = raw_input('Write a prime, for example 389:')
p=int(p_str)
q_str = raw_input('Write another prime, for example 401:')
q=int(q_str)
n = p * q
phi = (p-1)*(q-1)
# We check the keySize, if phi > 1024 we limit the size
... |
8766fe9e7a1d46b5271bf6a6aa386cb5f52a4f96 | BigYiii/WY | /61题.py | 105 | 4 | 4 | list=[]
for i in range(3):
a=input("请输入一个数:")
list.append(a)
list.sort()
print(list)
|
6a1a4da887abb3ea7f6e730fc6c976f6fa71a458 | BigYiii/WY | /26题.py | 114 | 3.71875 | 4 | for i in range(3,0,-1):
print(" "*i+"*"*(7-2*i))
for i in range(0,4,1):
print(" " * i + "*" * (7 - 2 * i)) |
d80b97c60d2026b8ddfa6d0dfd29872078bef447 | BigYiii/WY | /42题.py | 161 | 3.65625 | 4 | n=[[1,3,5],[8,2,0],[9,2,1]]
sum=0
for i in range(0,3):
a=n[i]
for j in range(0,3):
b=a[j]
if i==j:
sum += b
print(sum)
|
9743ffaa6e72bc09f4dcb5270fffcbefa68a2282 | BigYiii/WY | /32题.py | 139 | 3.78125 | 4 | def f(x):
if x == -1:
return ''
else:
return string[x] + f(x-1)
string=input("请输入5个字符:")
print (f(4)) |
b01882dbecb4d620dc86bda49052eb892677183d | whoisapig/PythonBase | /Dict和Set类型/Code.py | 1,916 | 3.953125 | 4 | #!/usr/bin/python
#coding:utf-8
# 根据如下dict:
#
# d = {
# 'Adam': 95,
# 'Lisa': 85,
# 'Bart': 59
# }
# 请打印出:
#
# Adam: 95
# Lisa: 85
# Bart: 59
d = {
'Adam':95,
'Lisa':85,
'Bart':59
}
for (key,value) in d.items():
print ("%s:%s" %(key,value))
# 请设计一个dict,可以根据分数来查找名字,已知成绩如下:
#
# Adam: 95,
... |
0ff79f2bc80d9eff5134da9f5f6a1ac9c044e2fa | JimChr-R4GN4R/CTFlearn-Writeups | /Crypto/Symbolic Decimals (80 points)/symbol_to_number.py | 303 | 3.609375 | 4 | text = "^&,*$,&),!@#,*#,!!^,(&,!!$,(%,$^,(%,*&,(&,!!$,!!%,(%,$^,(%,&),!!!,!!$,(%,$^,(%,&^,!)%,!)@,!)!,!@%"
text = text.replace('!','1').replace('@','2').replace('#','3').replace('$','4').replace('%','5').replace('^','6').replace('&','7').replace('*','8').replace('(','9').replace(')','0')
print(text)
|
94cdcd3b796ce29ed12937ed2ae0493d5c6b78cb | maciexu/Datacamp_Importing-Data-in-Python | /Importing _From_HDF5.py | 2,187 | 3.765625 | 4 | """
Using h5py to import HDF5 files
The file 'LIGO_data.hdf5' is already in your working directory. In this exercise, you'll import it using the h5py library. You'll also print out its datatype to confirm you have imported it correctly. You'll then study the structure of the file in order to see precisely what HDF gro... |
9d32a9da6c416aee1cbc061721e3afdaaf3ec80a | thaihaluong/HW3 | /3.3.star.py | 375 | 4.0625 | 4 | from turtle import *
def draw_star(x,y,z):
import turtle
turtle.goto(x,y)
turtle.left(108)
for i in range (0,5):
turtle.forward(z)
turtle.left(144)
speed(0)
color('blue')
for i in range(100):
import random
x = random.randint(-300, 300)
y = random.randint(-300, 300)
leng... |
4e2b9f7de6498b1f3686ac68088396ae6197bbe8 | pzwickl/PZ-Thesis | /VNQ/vod/configuration.py | 7,091 | 3.5 | 4 | __author__ = 'patrick'
import numpy as np
pound_to_euro = 1.2618898
dollar_to_euro = 1
def dollar(value):
return value*dollar_to_euro
def pound(value):
return value*pound_to_euro
def million(value):
return value * 1000 * 1000
def billion(value):
return 1000 * million(value)
######################... |
0ea9e858a10030b0c2aad1ee7ccb526f43df075e | KimSeungHyunOREO/MSE_Python | /Final Test/ex140.py | 370 | 3.546875 | 4 | print("-------")
print("-------")
print("-------")
print("-------")
# 아래 식과 결과가 같다.
# ------ 4번 출력을 할려면
# for문을 이용하여 4번 출력
a = [1, 2, 3, 4] # a 원소 개수만큼 출력시키기 위해서 4개의 원소를 가진 리스트를 만들었다.
for i in a: # a만큼
print("-------") # 출력한다.
# In[ ]:
|
c646e95a4b02e320985b2855e97b3a45eb2af235 | RJhean/Python-3 | /func_anidadas.py | 602 | 3.921875 | 4 | """
Funciones Anidadas
"""
def division(numero1, numero2):
def validacion():
return numero1 > 0 and numero2 > 0
if validacion():
return numero1/numero2
resultado= division(10,2)
print(resultado)
"""
Closures
es cuando una funcion retorna una funcion anidada
"""
def multiplicacion2(numero3,... |
d543292866db7b6e064be7f54246907afc9a231b | RJhean/Python-3 | /funciones_4.py | 523 | 3.921875 | 4 | """
pasar n cantidad de argumentos a una función
* -> n valores para función se traducen en tuplas
** -> n valores para la función, se traduce en diccionarios
"""
def suma(*args):
resultado = 0
for valor in args:
resultado= resultado+valor
return resultado
resultado = suma(10,20,30)
print(resulta... |
573a5d0156afb307b48b64ddd1e1115da54628f3 | RJhean/Python-3 | /ciclo_while.py | 395 | 4.1875 | 4 | """
Ciclo While
La utilizaos cuando no sabemos cuantos iteraciones queremos realizar.
Continue = nos permite que el ciclo continue su ejecución
Break = nos permite cortar el ciclo de forma abrupta
"""
contador = 0
while contador<=10:
print ("Hola", contador)
contador+=1
if contador==5:
continue
... |
f613cab79433a18de163b861a255475ca0022bf9 | RJhean/Python-3 | /variables.py | 718 | 3.984375 | 4 | """
Variables :
- a = "Cadenas"
- b = 9 # entero
- c = 9.6 # reales
- d = True # boleanos
"""
saludo = "Hola"
b = 4
print(saludo)
print(b)
"""
Números :
Enteros = 9
floats = 9.6
complex
boleanos = V o F
Operadores matemáticos:
+
-
*
/
//
**
"""
numero1 = 9
numero2 = 4
resultado = numero1 + numero2
print("Su... |
a3c6ccc80dfbebb84244096dd07cfd5334fce9f2 | Vincent-Seb-Wu/Data-Structures | /Homework/2/question2_largest_ten.py | 829 | 4.28125 | 4 | def largest_ten(list1):
"""
find the largest ten elements in list1. Assume list size greater than 10.
required runtime: O(len(list1))
:param list1: List -- list of integers
:return: List -- largest ten elements in list list1, as a new size 10 list. (Order doesn't matter.)
"""
ret_lst =... |
5448215a6d345722e5c79bfc17a05325ceb6149a | Timothy-Parker-jpg/Turtle | /spirograph.py | 446 | 3.875 | 4 | from turtle import Turtle, Screen
import random
def generate_color():
color = []
for i in range(3):
color.append(random.randint(0, 255))
return color
turt = Turtle()
turt.speed(100)
turt.shape("turtle")
turt.shapesize(1, 1)
screen = Screen()
screen.colormode(255)
for i in ... |
45b4bd38e56dca7691a6e079f7c1293d84046819 | Harry-Rogers/UsefulAlgos | /Algorithms/Graph search.py | 2,228 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 15 14:58:31 2020
@author: Harry
"""
from collections import defaultdict
class graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(s... |
ae9bdff7ad08f9f61517dc8cb0fe77192e06c4f7 | JunyiJ/find_political_donors_junyi | /src/test.py | 1,439 | 3.546875 | 4 | import unittest
from main_parse import get_median_sum,valid_date
class TestValidDate(unittest.TestCase):
def test_true_date(self):
self.assertTrue(valid_date("12312016"))
self.assertTrue(valid_date("01312016"))
self.assertTrue(valid_date("02292016"))
self.assertTrue(valid_date("02292016"))
self.assertTrue... |
612fd0c6f09c0271b636e0a7d11bc4276e78df11 | Vidhi23Chauhan/akademize_grofers_python | /50_Example 24_using_while_loop.py | 308 | 3.796875 | 4 | n = int(input("Enter n: "))
i = 1
while 1 <= i <= n:
print(i * i)
i = i + 1
"""
vidhichauhan@Admins-MacBook-Pro ~ % /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 "/Users/vidhichauhan/Documents/akademize-grofers-python/50_Example 24_using_while_loop.py"
Enter n: 5
1
4
9
16
25
""" |
7855d5621a607cdc1c536323ef2bc60c5ae2f0b5 | Vidhi23Chauhan/akademize_grofers_python | /25_first_n_even_numbers_n_iteration.py | 300 | 3.90625 | 4 | n = int(input("Enter n: "))
for i in range(1,n+1):
if i % 2 == 0:
print(i)
"""
vidhichauhan@Admins-MacBook-Pro ~ % /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 /Users/vidhichauhan/Documents/akademize-grofers-python/25_first_n_even_numbers.py
Enter n: 10
2
4
6
8
10
""" |
65523e9d72954ac3d8f1a7cf319a0055160a92f9 | Vidhi23Chauhan/akademize_grofers_python | /81_hello_names.py | 436 | 3.765625 | 4 | names = ["Sravan", "Arun", "Varun"]
wishes = ["Good morning","Good evening","Good night"]
def name(n):
for i in range(3):
print(f"{wishes[i]} {names[n]}")
i += 1
def main():
for n in range(3):
name(n)
n += 1
main()
"""
Good morning Sravan
Good evening Sravan
Good night Sr... |
b3b34613e84597069e24b810e249a526c16fe619 | Vidhi23Chauhan/akademize_grofers_python | /23_first_n_natural_numbers.py | 278 | 3.953125 | 4 | n = int(input("Enter n: "))
for i in range(1,n+1):
print(i)
"""
vidhichauhan@Admins-MacBook-Pro ~ % /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 /Users/vidhichauhan/Documents/akademize-grofers-python/23_first_n_natural_numbers.py
Enter n: 5
1
2
3
4
5
""" |
cc8eef20d79a6cc2e5bf98aef797bdbf708e67bd | Vidhi23Chauhan/akademize_grofers_python | /71_is_prime.py | 722 | 4.125 | 4 | def is_prime(n):
start = 2
stop = n-1
i = start
while(i <= stop):
if n % i == 0:
return False
i += 1 # same as i = i + 1
return True
def print_is_prime_status(n):
if is_prime(n):
print(f"{n} is a prime number")
else:
print(f"{n} is not a prime... |
90482f2a2902fde3b238e73824c59f9d9df0dc48 | vbrh-immalle/TheDynamicNatureOfPythonObjects | /normal.py | 1,083 | 4.21875 | 4 | class MyType: # [1]
useUppercase = False
def __init__(self):
self.str = "Hello! "
self.times = 3
def print_it(self):
if self.useUppercase:
print(self.str.upper() * self.times)
else:
print(self.str * self.times)
if __name__ ... |
6825e8941b4c17190b099c91b4ea0f06fca62cfe | BJV-git/amazon_6 | /amazon_6/longest_k_distnct.py | 1,659 | 3.625 | 4 | # Point: checking if a window is valid takes constant if used constant space map, i.e. to see if uniq are more than k, by that move the window
# can make it more efficient if we maintain a count of uniques
# Catch: use the window
# so we need to have a map to keep track of k distinct count, same as longest window subs... |
59303603eea6f8733bfe9c3983827954556f6b65 | BJV-git/amazon_6 | /amazon_6/zigzag_bin_tree.py | 497 | 3.703125 | 4 | # POINT: have one more variable with dir, and multiply each time
# its just that we need to append the reverse for even ones
# yes so maintain the direction flag and then append as normally
# Time: O(N)
# Space: O(N)
def zigzag_traversal(root):
if not root: return []
res,level, direc = [], [root], 1
whi... |
a2f3de428f92a8804ae38568b3fefcf724b01ff7 | BJV-git/amazon_6 | /amazon_6/word_break.py | 1,705 | 3.75 | 4 | # POINT: DP, verifies if its a valid start and then sees if there is any valid split word in the given map
# its a greedy too, but storing all the possibles starts so we cna know what split is optimal
# so when we divide a word we set the [] index to be true so that from that point we will check that if any
# time: O... |
2b66d9554f6fb529bccdc7f60f373fc6024757b4 | BJV-git/amazon_6 | /amazon_6/copy_list_random_pointer.py | 1,517 | 3.671875 | 4 | # POINT: insert dummy, set random conn, reset all connections
# use dictionary and then do but maintaining the memory is not effecient so better to create the node in run
# logic: put the new nodes in between while traversing firts
# Point: keep extra so that in middle the new are added, make the dummies point by ran... |
69b10213f33efa52160d6d27fa67a391a2496a82 | talescasalta/Coursera | /week9.ipynb | 5,338 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
import re
import string
# In[9]:
def le_assinatura():
'''A funcao le os valores dos tracos linguisticos do modelo e
devolve uma assinatura a ser comparada com os textos fornecidos'''
print("Bem-vindo ao detector automático de COH-PIAH.")
wal = float... |
95025ea541a47c103d8871ee62d15e50a949c547 | shobhit-nigam/Qualcomm | /killbill/day2/data_structs/1.py | 235 | 3.875 | 4 | #lists & tuple
avengers = ["thor", "hulk", "captain", "ironman"]
print(type(avengers))
avengers = ("thor", "hulk", "captain", "ironman")
print(type(avengers))
print("avengers[0] =", avengers[0])
print("avengers[1:3] =", avengers[1:3])
|
fc2032a8b22dbb73c62e06375c1658e8f2df9b77 | shobhit-nigam/Qualcomm | /killbill/day1/basics/2.py | 250 | 3.84375 | 4 | #int count = 20;
count = 20
#count = count+1
count += 1
print(count, type(count))
count = 45.67
print(count, type(count))
count = "hello world"
print(count, type(count))
count = 'h'
print(count, type(count))
print("print is of type =", type(print))
|
5c771c6e026958bcb3d265edc84a6a4fa7559391 | shobhit-nigam/Qualcomm | /killbill/day1/strings/7.py | 217 | 3.578125 | 4 | #strings indexing & slicing
game = "cricket"
player = "virat kohli"
reptile = 'cobra'
print(game[0:4])
print(game[4:6])
print(game[-6:-2])
# does not give "out of range" error
print(reptile[7:17])
print(reptile[-8:-1])
|
eb58dd5eceb1596ad920381929bfeee01bd7ec63 | shobhit-nigam/Qualcomm | /killbill/day1/lists/7.py | 403 | 4.09375 | 4 | #lists functions
tintin = ['tintin', 'haddock', 'calculus', 'snowy', 'marie-louis']
print("tintin =", tintin)
tintin.append("alcazar")
print("tintin =", tintin)
tintin.reverse()
print("tintin =", tintin)
tintin.remove("haddock")
print("tintin =", tintin)
tintin.pop(-2)
print("tintin =", tintin)
tintin.insert(3, "haddo... |
9191e4d5ef400ba1c11849f07e33f3a93ad6d9ff | ravivats/ds-algo-interview-cookbook | /platform-problems/leetcode/may-2020-leetcoding-challenge/10-LeetCode-findJudge.py | 1,858 | 3.890625 | 4 | '''
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You a... |
490e445b9778dd1f5fda3862bcfacfaae543f576 | penm284/weekly_problems | /rgb_hex.py | 608 | 3.640625 | 4 | def rgb(r, g, b):
if r < 0:
r = "00"
elif r > 255:
r = "FF"
elif r < 15:
r = "0" + str(hex(r).split("x")[1]).upper()
else:
r = str(hex(r).split("x")[1]).upper()
if g < 0:
g = "00"
elif g > 255:
g = "FF"
elif g < 15:
g = "0" + str(hex(g)... |
29b6d4f278ea76b4b43f0bf97cbe7332a682c77f | JiashengWu/Wikidata | /Wikidata.py | 1,995 | 3.578125 | 4 | import glob
import os
class Wikidata:
"""Wikidata class, which provide a function of find_property().
Attributes:
data (dict): Data stored as {path: example_set}.
"""
def __init__(self, relpath):
"""The constructor of Wikidata class.
Read the input files only once, and store ... |
0d6e3a9705394d5f00c5a341bd5b098edaa506fa | rectangletangle/email_lib | /iso_time.py | 830 | 3.859375 | 4 | ''' This module contains functions which return ISO 8601 formatted time
strings. '''
import time
__all__ = ['iso_date_time', 'iso_date', 'iso_time']
ISO_DATE_CODE = '%Y-%m-%d'
ISO_TIME_CODE = '%H:%M:%S %Z'
def iso_date_time () :
''' This returns the date and time (as a unicode string) in ISO 8601
f... |
651de1a3a2345fc38618b5be600c01d8e0a92354 | sugamkarki/NAMI-Year-II-TERM-I-Group_Project | /Python/100Excersises/26 to 50/27/27.py | 113 | 3.5 | 4 | def acceleration(v1,v2,t1,t2):
a=(float(v2-v1)/float(t2-t1))
return a
print(acceleration(0,10,0,20)) |
d97a653f2f8f01ceef70577990cd1e95defe43fd | sugamkarki/NAMI-Year-II-TERM-I-Group_Project | /Python/100Excersises/1 to 25/21/21.py | 201 | 3.6875 | 4 | d = {"a": 1, "b": 2, "c": 3}
newDict={}
for (key,value) in d.items():
if(value<=1):
newDict[key]=value
# for key,values in d.items():
# if values>1:
# d.pop[key]
print(newDict)
|
7f0658e10abc67845c1478a0d4d39c95763f89d3 | sugamkarki/NAMI-Year-II-TERM-I-Group_Project | /Python/100Excersises/26 to 50/36/36.py | 113 | 3.703125 | 4 | wordFile=open("words.txt",'r')
# print(wordFile)
word=(wordFile.readline())
word=word.split(' ')
print(len(word)) |
9c49331fe4bf9c37a85900b0562125f43f07cf85 | gszabo/aoc-2019 | /day-05/main.py | 3,938 | 3.671875 | 4 |
class Computer:
def __init__(self, program, inputs):
self.program = program
self.inputs = inputs
self.instruction_pointer = 0
self.outputs = []
self.stopped = False
def run(self):
while not self.stopped:
instruction, parameters = self.decode()
... |
82e443b1fb2c7d5449f14cf9c74bea51a6fc0dac | gszabo/aoc-2019 | /day-18/main.py | 5,848 | 3.625 | 4 | from collections import deque
from functools import wraps
from frozendict import frozendict
class Vault:
"""
Immutable representation of the vault.
"""
def __init__(
self, walls, corridors, keys, keys_by_pos, doors, doors_by_pos, entrances
):
self.walls = frozenset(walls)
... |
efc11eb43e66d8fef7f61e2278e442a10f937c84 | Peter-Immanuel/Complex-Number-Analysis | /complexOpr.py | 1,852 | 4.03125 | 4 | from math import sqrt, atan, degrees
class ComplexAnalyses:
''' A function to perform basic complex operation and conversion'''
def __init__(self,*numbers):
self.numbers = [complex(number) for number in numbers]
self.__results = {}
def add(self):
result = 0
for number in s... |
10d1870f60d8cd946af6e9b6c7e93f2943c89d04 | anand1115/Data-Structures-2021 | /Graphs/bellman_ford.py | 1,206 | 3.9375 | 4 | class Graph:
def __init__(self,edges,vertices):
self.edges=edges
self.vertices=vertices
self.graph_dict={}
for i,j,v in edges:
if i in self.graph_dict:
self.graph_dict[i][j]=v
else:
self.graph_dict[i]={j:v}
def print(self):... |
04cc1bf256b66212097dec0b845b24bd69f2f085 | anand1115/Data-Structures-2021 | /bit_manipulation_new/count_set_bits.py | 309 | 3.859375 | 4 | def count(num):
c=0
while num:
if(num&1):
c+=1
num=num>>1
return c
def count2(num):
c=0
while num&(num-1):
num=num*(num-1)
c+=1
return c
print("{:b} count of 1 is {}".format(15,count(15)))
print("{:b} count of 1 is {}".format(15,count(25)))
|
c5c1e4f215f74ff606eb6d83c385ff064a965952 | anand1115/Data-Structures-2021 | /dynamic_programming/dynamic_programming_2/ugly_numbers.py | 353 | 3.875 | 4 | def divide(a,b):
while(a%b==0):
a=a/b
return a
def isugly(number):
number=divide(number,2)
number=divide(number,3)
number=divide(number,5)
return 1 if number==1 else 0
n=int(input())
count=1
ugly=[1]
i=2
while count<n:
if(isugly(i)):
count+=1
ugly.append(i)
i+=... |
224b99904018091b220eb2b8ed7f0a2c3133dd8c | anand1115/Data-Structures-2021 | /bit_manipulation/convert_to_any_base.py | 681 | 3.65625 | 4 | def dec_to_any_base(num,base):
final=""
while num>0:
rem=num%base
if(rem<10):
final+=str(rem)
else:
final+=chr(55+rem)
num=num//base
return final[::-1]
def any_base_to_dec(num,base):
num=str(num)
num=num[::-1]
final=0
for i in range(le... |
bba824cc1b8fe74aa949f22904c1843763a6f09b | anand1115/Data-Structures-2021 | /Graphs/bellman_ford_practice.py | 2,621 | 3.625 | 4 | class graph:
def __init__(self,edges,vertices):
self.edges=edges
self.vertices=vertices
self.graph_dict={}
for i,j,v in self.edges:
if i in self.graph_dict:
self.graph_dict[i][j]=v
else:
self.graph_dict[i]={j:v}
def print(s... |
0ec8012684c59ed5a8e1a1729fd692a47626614f | anand1115/Data-Structures-2021 | /bit_manipulation/check_ith_is_set_or_not.py | 137 | 3.671875 | 4 | def check(num,i):
return num==(num and (1<<i))
k=int(input("Enter Number : "))
i=int(input("enter digit place : "))
print(check(k,i)) |
933d8dc40086e8d0b8fbe0b91d0617ad443649e1 | anand1115/Data-Structures-2021 | /edyst_training/perfect.py | 347 | 3.5625 | 4 | import math
n=int(input())
for i in range(n):
k=int(input())
if(k&1==1):
print("NO")
else:
sum=1
for j in range(2,int(math.sqrt(k))+1):
if(k%j==0):
sum+=j+(k//j)
if(sum==k):
print("YES")
else:
print("NO")
... |
31ed2dcb4d60174894594c19f0250d20d13f98b0 | anand1115/Data-Structures-2021 | /Graphs/weighted_graph.py | 427 | 3.75 | 4 | class graph:
def __init__(self,edges,vertices):
self.edges=edges
self.vertices=vertices
self.graph_dict={}
for i,j,v in self.edges:
if i in self.graph_dict:
self.graph_dict[i][j]=v
else:
self.graph_dict[i]={j:v}
def print(s... |
0b9e99de62602e8c72230ed86312d7f690e6b856 | Wuwenxu/code-camp-python | /src/base/Day11/json2.py | 389 | 3.578125 | 4 | """
写入JSON文件
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import json
fruits_list = ['apple', 'orange', 'strawberry', 'banana', 'pitaya']
json_str = json.dumps(fruits_list)
print(json_str)
print(type(json_str))
# teacher_dict = {'name': '白元芳', 'age': 25, 'title': '讲师'}
# json_str = json.dumps(teacher_... |
665de25e2c9a6791e89809b8c43619b3c36036fd | Sophiabattler/homework-repository | /homework2/task02_var1.py | 654 | 3.890625 | 4 | """Task02_var1 - Most&least common"""
from collections import Counter
from typing import List, Tuple
def input_list():
nums = [int(i) for i in input().split()]
return nums
def input_list_if_wrong():
nums = [int(i) for i in input().split()]
return nums
def major_and_minor_elem(inp: List) -> Tuple[i... |
614296777df31030b7136127cf84fcdbbb65536e | Sophiabattler/homework-repository | /tests/homework3/test_task01.py | 927 | 3.75 | 4 | """Test for task01 - Cache n times"""
from unittest.mock import Mock, call
from homework3.task01 import cache, make_key
def test_cache_with_same_arg():
"""Testing that program calls the same function only 2 times"""
mock = Mock()
cached_func = cache(times=1)(mock)
cached_func(1, 3)
cached_func(1,... |
0a4ce0aed03e4a3346798d50fab6336b974002c1 | Sophiabattler/homework-repository | /homework2/task03.py | 236 | 3.625 | 4 | """Task03 - All possible lists"""
from itertools import product
from typing import Any, List
def combinations(*args: List[Any]) -> List[List]:
"""Does all combinations from some lists"""
return list(map(list, product(*args)))
|
3b70647b0bc0eda2d8e8cce155d481c27c2519ea | Sophiabattler/homework-repository | /tests/homework2/test_task05.py | 926 | 3.671875 | 4 | """Tests for task05 - Custom range"""
from string import ascii_lowercase
from homework2.task05 import custom_range
def test_custom_range_different_range():
"""Testing how func slices"""
assert custom_range(ascii_lowercase) == [
"a",
"b",
"c",
"d",
"e",
"f",
... |
88313d70f6c613423cb3cbd6b5258f2eb81fea44 | PacktPublishing/Text-Processing-using-NLTK-in-Python | /Section04/3.py | 589 | 4 | 4 | import re
#search for literal strings in sentence
patterns = [ 'Tuffy', 'Pie', 'Loki' ]
text = 'Tuffy eats pie, Loki eats peas!'
for pattern in patterns:
print('Searching for "%s" in "%s" ->' % (pattern, text),)
if re.search(pattern, text):
print('Found!')
else:
print('Not Found!')
#searc... |
2d2d825362f9eaa8567c61cd321a42b90cbeb26e | PacktPublishing/Text-Processing-using-NLTK-in-Python | /Section02/2.py | 365 | 4.1875 | 4 | str = 'NLTK Dolly Python'
print('Substring ends at:',str[:4])
print('Substring starts from:',str[11:] )
print('Substring :',str[5:10])
print('Substring fancy:', str[-12:-7])
if 'NLTK' in str:
print('found NLTK')
replaced = str.replace('Dolly', 'Dorothy')
print('Replaced String:', replaced)
print('Accessing each... |
45d69e3c8a947a20fc83ca7432b5f99d391a4578 | coleberhorst/python-exercism | /forth/forth.py | 957 | 3.796875 | 4 | class StackUnderflowError(Exception):
pass
def evaluate(input_data):
result = []
for line in input_data:
line = [int(i) if i.isnumeric() else i for i in line.split(" ")]
print(line)
while len(line) >= 2:
if in line and len(line) < 3:
raise StackUnderflo... |
101aafb441773dafa9401f2343b994e4bfc8199c | coleberhorst/python-exercism | /binary-search/binary_search.py | 407 | 4.0625 | 4 | def binary_search(list_of_numbers, number):
first, last = 0, len(list_of_numbers) - 1
while first <= last:
half = (first + last) // 2
if list_of_numbers[half] == number:
return half
elif number < list_of_numbers[half]:
last = half - 1
elif number > list_of... |
5fd22c59e6c13a8b200f5b908b60d5d930b766ac | coleberhorst/python-exercism | /bank-account/bank_account.py | 1,379 | 3.796875 | 4 | from threading import Lock
class BankAccount(object):
def __init__(self):
self.balance = None
self._lock = Lock()
def get_balance(self):
with self._lock:
if self.balance == None:
raise ValueError("Account is not open.")
return self.balance
... |
6e661b5c32b889d72487ec39953d75dcc66a20cb | coleberhorst/python-exercism | /beer-song/beer_song.py | 907 | 3.6875 | 4 | def recite(start, take=1):
lyrics, stop = [], start - take
while start >= 0 and start != stop:
lyrics.extend(verse(start))
start -= 1
if start != stop:
lyrics.append("")
return lyrics
def verse(count):
it_one = (count == 1) * "it" + (count > 1) * "one"
b1 = (cou... |
1f3304a2b167bc7aa8c1c80ba55f462354224b55 | coleberhorst/python-exercism | /simple-linked-list/simple_linked_list.py | 1,188 | 3.9375 | 4 | class Node(object):
def __init__(self, value, next=None):
self.__value, self.__next = value, next
def next(self):
return self.__next
def value(self):
return self.__value
class LinkedList(object):
def __init__(self, values=[]):
self.__head, self.__length = None, 0
... |
5285cfd187a4dfa20f3a3f35776921fbc899891f | SerCharles/THSS-Machine-Learning | /hw2_SVM/src/utils.py | 438 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def plot_curves(loss_train):
'''
描述:绘制训练-测试曲线
参数:训练,测试的准确度
返回:无
'''
x_axix = []
for i in range(len(loss_train)):
x_axix.append(i)
plt.title('Loss Comparison')
plt.plot(x_axix, loss_train, color='red', label='training loss')... |
dc38bf8b9f1e7934db4023ac4818304126b06d1e | kiennt/algorithms | /src/com/kiennt/codility/09_max_profit.py | 2,262 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
https://codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/
A zero-indexed array A consisting of N integers is given. It contains daily prices of a stock share for a period of N consecutive days. If a single share was bought on day P and sold on day Q, where 0 ≤ P ≤ Q < N, ... |
7c41dbd684721351cc1c255924667402a1360039 | kiennt/algorithms | /src/com/kiennt/codility/06_number_of_disc_intersections.py | 2,619 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
https://codility.com/programmers/lessons/6-sorting/number_of_disc_intersections/
We draw N discs on a plane. The discs are numbered from 0 to N − 1. A zero-indexed array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (... |
1957d5c4d7392b4bf42d1bc999aaadbecf5a376c | adam-m-mcelhinney/MCS507Midterm | /E1_Fraction.py | 3,446 | 3.78125 | 4 | """
MCS 507 Midterm
Exercise 1
1. Consider a real number x. Let i be the integer part of x and let f be the fractional part of x. If f is zero,
then the continued fraction representation of x is [i]. Otherwise, the continued fraction representation
of x is [i,L], where L is the continued fraction representation of 1/f... |
3ae822b4a0235b3ec9652d840ab56e85d8d76dca | ricardoITW/cursoPythonPropio | /chicharron.py | 272 | 3.90625 | 4 | #!/usr/bin/python
import math
a=input("introduce a: ")
b=input("introduce b: ")
c=input("introduce c: ")
x1 = (-b+math.sqrt(pow(b,2)-(4*a*c)))/(2*a)
x2 = (-b-math.sqrt(pow(b,2)-(4*a*c)))/(2*a)
print 'el valor de x1 es: ',float(x1)
print 'el valor de x2 es: ',float(x2)
|
cc64512712b0d5e6c293c31d19b7939c29728319 | hollyrebecca/Final-year-EV-project | /snakeProblem.py | 16,475 | 3.5 | 4 | # This code defines the agent (as in the playable version) in a way that can be called and
# executed from an evolutionary algorithm. The code is partial and will not execute. You need to
# add to the code to create an evolutionary algorithm that evolves and executes a snake agent.
import curses
import random
import ... |
8acf29e2353b50cb762568e2646ca833b3437a9c | DCC-Lab/RayTracing | /raytracing/examples/ex12.py | 1,146 | 3.5625 | 4 | TITLE = "Thick diverging lens built from individual elements"
DESCRIPTION = """ If you build a lens from individual elements
(DielectricInterface, Space and DielectrcInterface), then the rays inside the
lens may be blocked from the finite diameter (in this case, Space() has a
finite diameter of 25 mm). The draw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.