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 |
|---|---|---|---|---|---|---|
71efc5a0ed8df870a4a18ab7919f84e77cb8c5ea | Terrencebosco/data_structures | /stack/Stack.py | 393 | 3.703125 | 4 | from collections import deque
class Stack:
def __init__(self):
self.container = deque()
def push(self, val):
self.container.append(val)
def pop(self):
return self.container.pop()
def peek(self):
return self.container[-1]
def is_empty(self):
return len(sel... |
999ee8f2892b37f8781d18d3667658c8f7186fec | Artem100/python_lessons | /lesson_7/lesson_7_homework.py | 1,720 | 3.5 | 4 | """
1. Реализовать все декораторы - таймер, запоминатель, счетчик вызовов и единичный вызов
2. Реализовать примеры с functools - wraps и singledispatch
3. Реализовать свой lru_cache (описание в конце презентации)
"""
import time
def timer(f):
def tmp(a, b, c):
t = time.time()
res = f(a, b, c)
... |
b5a8fa653d9dcce4e85552b82b21d9520297fe64 | Artem100/python_lessons | /lesson_2/lesson_2_home_work.py | 2,997 | 3.71875 | 4 | import string
from collections import Counter
from random import choice
def task_1():
"""Дана строка “spam and eggs or eggs with spam”. Посчитать сколько раз встретился каждый символ."""
some_string = "spam and eggs or eggs with spam"
lis = list(some_string)
print(f"Задача 1.\nCounter(lis)")
def tas... |
3e4f01ce10fbc19b3519003c2dde72c57557dada | Timo-Verbist/Make1.2.1pt2 | /1.3) age_extra.py | 668 | 3.859375 | 4 | #!/usr/bin/env python
"""
Info about our project comes here
"""
__author__ = "Timo Verbist"
__email__ = "timo.verbist@student.kdg.be"
__status__ = "Development"
from _datetime import datetime
def main():
name = str(input("What's your name?\n"))
age = int(input("Give your age please.\n"))
bool = str(inpu... |
b294e93d4b95eda93ba6574d6728bd4c24ac354e | ngp111/Information-Security | /Assignment-1/rotate_matrix.py | 912 | 4.09375 | 4 | import numpy as np
def rot_90_clock(matrix) :
"""
Rotates the given matrix by 90 degrees in clockwise direction
Args : matrix - the matrix that is to be rotated
"""
return np.rot90(matrix, k = 3)
def rot_90_anticlock(matrix) :
"""
Rotates the given matrix by 90 degrees in ... |
c7da08635245eeac7509606b135f0dace7e249d0 | gasuketsu/py-sandbox | /mycal/mycal.py | 722 | 4.0625 | 4 | #!/usr/bin/env python3
import datetime
import calendar
calendar.setfirstweekday(calendar.SUNDAY)
def print_calendar_header(year, month):
weekdays = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
print('%d/%d' % (year, month))
print(' '.join(weekdays))
def print_calendar_body(year, month):
cal = calenda... |
7809a7a561486c90f44145ca09100e8501d2b8d6 | georgynemirovsky/gosha-programming-practice-1sem | /turtle1/10.py | 285 | 3.875 | 4 | import turtle
turtle.shape('turtle')
def f(k):
for i in range(180):
turtle.forward(k)
turtle.left(2)
turtle.left(180)
for i in range(180):
turtle.forward(k)
turtle.left(2)
turtle.left(90)
for i in range(1, 6, 1):
f(i)
x = input(' ')
|
f2db58d264acbbd619642114e250fd686f0a6ce7 | LucasMonteiroBastos/python3_mundo01 | /ex019.py | 797 | 4.0625 | 4 | #Exercício Python 19:
#Um professor quer sortear um dos seus quatro alunos
#para apagar o quadro.
#Faça um programa que ajude ele,
#lendo o nome dos alunos e escrevendo na tela o nome do escolhido.
#importando o modulo random
import random
#variaveis com os 4 alunos
aluno1 = str(input('Digite o nome do primeiro Aluno... |
0be16c108fc4361fddf8fe0117804e88d4aa4adc | LucasMonteiroBastos/python3_mundo01 | /ex028.py | 611 | 4.28125 | 4 | '''Exercício Python 28:
Escreva um programa que faça o computador “pensar”
em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir
qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.'''
import random
a = int(input('Em que numero estou pensando... |
e0570157331e13764802a35a754400f05ece2913 | LucasMonteiroBastos/python3_mundo01 | /ex034.py | 681 | 3.984375 | 4 | #Exercício Python 34:
# Escreva um programa que pergunte o salário de um funcionário
# e calcule o valor do seu aumento.
# Para salários superiores a R$1250,00,
# calcule um aumento de 10%.
# Para os inferiores ou iguais, o aumento é de 15%.
salario = float(input('Informe o salario do funcionario: R$ '))
if salario ... |
18b4e8fdf1bf347edd4951f2583320d45b8635fc | Betrezen/SimpleCV2 | /SimpleCV/Display/Base/DrawingLayer.py | 12,881 | 3.703125 | 4 | from Shapes import *
from ...Color import Color
class DrawingLayer:
"""
**SUMMARY**
DrawingLayer gives you a way to mark up Image classes without changing
the image data itself.
**NOTE**
This class should be kept picklable so that the it can be sent over a Pipe
"""
... |
47267ff2c1f770d432faf2577713f411d7de90d3 | LLeung49/PracticeTemp | /crack the code interview/product_array.py | 1,697 | 3.734375 | 4 | #Calculate the product of other elements of each element in a list
def test():
test =[[1,2,4,6],[1,2,3,4],[2],[1,2,'a'],[1,3,3,54,0],[9,0,8,6,0],[]]
test_result = [[48, 24, 12, 8],[24,12,8,6],[1],'error',[0,0,0,0,eval("9*54")],[0,0,0,0,0],[]]
# test =[[1,2,4,6]]
# test_result = [[48, 24, 12, 8]]
fo... |
ba44c84242dda2363081e9ae7786d64add582d50 | yangmtou/TestPython | /test_while.py | 402 | 3.875 | 4 | flag = True
number = 1
while flag:
if number <=3:
answer = input('为什么超级英雄都穿紧身衣')
if answer == '救人要紧':
flag = False
print('恭喜你答对了')
else:
print('回答错误')
else:
print('次数用完了')
break
print(f'这是你的第{number}次回答')
number += 1
... |
ce9fe98b29d74290d1811c04bc4173bec49375d8 | ccollins12000/AddressLookup | /bing.py | 11,244 | 3.71875 | 4 | import requests
import json
class RouteRetriever:
"""An object for retrieving the route between two locations using Bing's custom search API"""
def __init__(self, api_key):
"""The constructor for the route retriever utilizing bing
Args:
api_key (str): The secret key for ac... |
0062eb73333fbb36791f164a7d3743691eb36490 | vbanurag/python_set1 | /set_1/Ques_2.py | 687 | 4.125 | 4 | a=[1,1,2,3,5,8,13,21,34,55,98]
#part 1
#prints all elements of the list which are less than 5
print "\nThe no. are less than 5 is : ",[x for x in a if x<5]
#part 2
#print a seperate list and stored a no which is less than 5
new_a=[]
for x in a:
if x<5:
new_a.append(x)
print "\n New list is ",new_a
#... |
f866beb6c60476f55a5353f84dfe964843ad6f0d | ElspethBair/frc-hw-submissions | /lesson8/Lesson 8 HW.py | 1,889 | 4.0625 | 4 | class Robot:
starting_arm_pos = 0
starting_robo_pos = 0
starting_cube = False
starting_score = 0
def __init__(self, arm_pos, robo_pos, cube, score ):
self.arm_pos = arm_pos
self.robo_pos = robo_pos
self.cube = cube
self.score = score
def move(self):
a = int(raw_input("How far would you like to move?")... |
8d8b023e2cf1f69e237c04f3d307d02203d90892 | glatif1/Practice-Programs-in-Python | /MiniPrograms/rec_list_sum.py | 146 | 3.78125 | 4 |
def recsum(list1):
if len(list1) ==1 :
return list1[0]
else:
return recsum(list1[1:])+list1[0]
list1 = [1,1,1,7,1,1,7]
print(recsum(list1)) |
26cb1fcfdbfe5d5ca07fe93981c4a3c54ad092e5 | glatif1/Practice-Programs-in-Python | /MiniPrograms/rec_sum_to_ n.py | 97 | 3.609375 | 4 | def recsumton(n):
if n == 1:
return n
else:
recsumton(n-1)+recsumton(n)
print(recsumton(3)) |
cb3893616a5b762d42c0b01dfd4b95aff4963f52 | glatif1/Practice-Programs-in-Python | /MiniPrograms/string_functions.py | 348 | 4.09375 | 4 | string=input("Enter something:")
onlyletters=string.isalpha()#checks if the string has only letters
onlyuppercase=string.isupper()#checks if the string is all upper case
onlylowercase=string.islower()#checks if the string is all lower case
onlydigits=string.isdigit()#checks if the string is all digits
digitsandlet... |
816f9356260733757e153099b45a7bba919daa67 | glatif1/Practice-Programs-in-Python | /Practice Programs/lab2/sumRange.py | 291 | 4 | 4 | low = int(input("Enter low number:"))
h = int(input("Enter high number:"))
high = h+1 # this adds 1 to the high beause range doesn't include the last number
result=0
if low <= high:
for i in range(low, high):
result = result + i
print(result)
else:
print("Error:", h ,"<" , low) |
e3d20362e94a8f187ed5d9fbd4358eb36a0bc304 | glatif1/Practice-Programs-in-Python | /Practice Programs/word_count.py | 308 | 3.546875 | 4 | from sys import argv
for i in range(1,len(argv)):
file = argv[i]
openedfile = open(file, 'r')
lines = openedfile.readlines()
for i in lines:
print(i)
#print(lines)
# i=-1
# while i <len(openedfile):
# if argv[1] in lines[i]:
# print("found:", lines[i])
# i = len(lines)
# else:
# i+=1
|
82f00760019a48bd84a303bc98303165a23199ec | glatif1/Practice-Programs-in-Python | /MiniPrograms/numberguessinggame.py | 851 | 4.0625 | 4 | import random
actualguessesTaken = 0
print("This is the number guessing game!!!")
number = random.randint(1, 20)
print(' the number is between 1 and 20.')
continuegame='y'
while actualguessesTaken < 6:
while continuegame =='y':
Playerguess = int(input("Enter your guess:"))
actualguessesTaken = ac... |
c750ba3e76b3684c3d1cd2b19de04024fc56c3bf | manojns/sllab | /Part A/10/a10.py | 134 | 3.53125 | 4 | s={34:"walter",67:"jesse",78:"gustavo",32:"marie",89:"frank",12:"skyler"}
for i in s:
if i%2==0:
print (str(i)+" : "+s[i])
|
d271c783c110ef79be0de24e7080136f4db87219 | SilentGrig/sql | /10_sql_homework01.py | 983 | 3.609375 | 4 | # SQL JOIN - Homework01
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
# Create new table orders
c.execute("""CREATE TABLE orders
(make TEXT, model TEXT, order_date DATE)
""")
orders = [
('Ford', 'Focus', '2017-04-30'),
... |
f1d4ec58d4333dcf64cba7d2d50cbbdbd4614d68 | gsrivast92/pythonPrograms | /mergesort.py | 803 | 4.0625 | 4 | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid_index = len(arr) //2
mid_element = arr[mid_index]
left_arr= arr[:mid_index]
right_arr = arr[mid_index:]
merge_sort(left_arr)
merge_sort(right_arr)
merge_two_sorted(left_arr,right_arr, arr)
... |
d61d1c364dda591b2f431c52dd684ccc0cc0a35b | gsrivast92/pythonPrograms | /different_list_ops.py | 572 | 3.703125 | 4 |
if __name__ == '__main__':
N = int(input())
lst = []
for i in range(N):
stg = str(input())
a=stg.split()
if (a[0]== 'append'):
lst.append(int(a[1]))
elif(a[0]== 'insert'):
lst.insert(int(a[1]),int(a[2]))
elif(a[0]== 'print'):
prin... |
1589c2055e116474e9a06a02f7479b631004dfe5 | gsrivast92/pythonPrograms | /sort_without_func.py | 240 | 4.03125 | 4 | #Sorting number without sort function
data_list= ['1','6','5','2','-1','2']
#Arbitrary Number
smallest_num= data_list[0]
sorted_list = []
while data_list:
for i in data_list:
if i < smallest_num:
i = smallest_num
sorted_list = |
ead8daf44fff521c46a124500108ec2e2c403dbe | gsrivast92/pythonPrograms | /reversewithspecialchar.py | 890 | 4.03125 | 4 | #Function to reverse a string
def reverse(s):
l1 = len(s)//2
for i in range(l1):
s[i],s[-i-1] = s[-i-1],s[i]
return s
#Function to convert a string into List
def toList(s):
l=[]
for i in s:
l.append(i)
return l
#Function to return a list having only alphabets#
def isAlphabet(s):
isAlphabet = []
f... |
3d9f7be39b7f2518c22952b76b09601d14b0bc02 | shwetgarg/algorithms | /Interviews/snake_ladder.py | 2,109 | 3.734375 | 4 |
from collections import deque
class SnakeLadder():
def __init__(self, M, N, s_l):
self.M = M
self.N = N
self.s_l = s_l
def prepare_graph(self):
size = self.M*self.N
graph = {}
for i in range(1, size+1):
graph[i] = [i + 1]
... |
6541a366e8c3d7bb72711a7b38148ec75e6cd334 | shwetgarg/algorithms | /Trees/views_of_tree.py | 729 | 3.921875 | 4 | from tree import Tree
def main():
a = Tree(1)
b = Tree(4)
c = Tree(6)
d = Tree(8)
e = Tree(2, a)
f = Tree(3, e, b)
g = Tree(7, c, d)
h = Tree(5, f, g)
print "####### Left View ########"
print_next = False
for node in Tree.get_level_order_traversal(h):
if not isinsta... |
539f71bf4a852c80e80baa00726723b1d92b6643 | shwetgarg/algorithms | /Memoization/lcs.py | 702 | 3.75 | 4 | '''It was long description for a DNA problem. Main DNA sequence(a string) is given (let say strDNA) and another string to search for(let say strPat). You have to find the minimum length window in strDNA where strPat is subsequence.'''
from memoize import memoized
@memoized
def get_lcs(str_dna, str_pta):
if len(st... |
e3bffb14748f86989f500369f7d2b91d0d5bf493 | shwetgarg/algorithms | /Dynamic_Programming/min_len_window_of_subsequence_in_another_string.py | 1,499 | 3.96875 | 4 | '''It was long description for a DNA problem. Main DNA sequence(a string) is given (let say strDNA) and another string to search for(let say strPat). You have to find the minimum length window in strDNA where strPat is subsequence.'''
def get_lcs(str_dna, str_pta):
n = len(str_dna)
m = len(str_pta)
table =... |
38de4bc4ef423d44994dee576b8669b4ec955475 | cpe202fall2019/lab1-kaanan99 | /location_tests.py | 1,859 | 3.65625 | 4 | import unittest
from location import *
class TestLab1(unittest.TestCase):
def test_repr(self):
#Making the default object
loc = Location("SLO", 35.3, -120.7)
self.assertEqual(repr(loc),"Location('SLO', 35.3, -120.7)")
#Creating a different object
loc2 = Location("Paris", 48... |
82ca2746a9cfdc640d6dca0c0c7ab618e9633e12 | eaamankwah/Using-Python-for-Research | /wk4-case-studies-part2/HW4-3.py | 9,730 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Using Python for Research Homework: Week 4, Case Study 3
#
# Homophily is a property of networks. Homophily occurs when nodes that are neighbors in a network also share a characteristic more often than nodes that are not network neighbors. In this case study, we will invest... |
2d238f83ca589d0ef010972aca8cdcdb7c51bceb | BichiZhang96/Python-Programming | /Assignment/Assignment6Q3.py | 1,047 | 3.578125 | 4 | # Assignment6Q3
import logging
logging.basicConfig(filename='Assignment6Q3.log', level=logging.DEBUG)
def main():
try:
string1 = eval(input("Please input the string array:")) # ["Python", "Programming", "Programming"]
string2 = eval(input("Please input the pattern array:")) # ["X", "Y", "Y"]
judge... |
cc06b5a77f8e5d7fb56dae71c270067a90a9db9b | BichiZhang96/Python-Programming | /Assignment/Assignment6Q2.py | 2,465 | 3.75 | 4 | # Assignment6Q2
import logging
logging.basicConfig(filename='Assignment6Q2.log',level=logging.DEBUG)
class Group:
def __init__(self, ori): # have one parameter: original matrix
self.ori = ori
def split(self): # split the original matrix, get the ingredients than appear more than once
dishes,number,... |
8102e2e4c74c03c2a372b726267debc8e2be9098 | jenlen91/Sudoku | /Solver.py | 4,894 | 3.953125 | 4 |
from random import randint, seed
import click
Empty = click.style('-', fg='red')
mainboard = []
optboard = []
# for i in xrange(9):
# tmp=[]
# for j in xrange(9):
# tmp.append((j+1))
# mainboard.append(tmp)
def make_board(mainboard,r,c):
for i in xrange(r):
tmp=[]
for j in xrange(c):
tmp.append(Empty)
... |
f4aff7e1b83c95178889b40955f3748aa9ddf095 | mehrdadmzn/openprescribing | /openprescribing/matrixstore/matrix_ops.py | 3,385 | 3.625 | 4 | from __future__ import division
import numpy
import scipy.sparse
# Above a certain level of density it becomes more efficient to use a normal
# dense matrix instead of a sparse one. This threshold was determined through a
# not particularly scientific process of trial and error. Due to the
# compression we apply th... |
a8eb8e414fd5e3755d38e1a46eaf28427af7432f | mehrdadmzn/openprescribing | /openprescribing/matrixstore/row_grouper.py | 3,056 | 3.734375 | 4 | from collections import defaultdict
import numpy
class RowGrouper(object):
"""
The `RowGrouper` class provides a method which sums together groups of
matrix rows. We generally use it for aggregating practice level data into
organisations that consist of groups of practices like CCGs or STPs.
Exa... |
2dff046cd742e179bafb89e87e14e0ab3bf60d50 | wylu/algorithm | /sort/merge_sort.py | 2,674 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File : merge_sort.py
@Time : 2020/11/27 13:43:28
@Author : wylu
@Version : 1.0
@Contact : 15wylu@gmail.com
@License : Copyright © 2020, wylu-CHINA-SHENZHEN. All rights reserved.
@Desc : 归并排序
归并排序(Merge sort),是创建在归并操作上的一种基于比较的排序算法。
1945 年由约翰·冯·诺... |
ac3592b8ded5a075e9d9a0929a5247c011a740e7 | wylu/algorithm | /datastruct/linear/binarysearch/template_1.py | 1,299 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File : template_1.py
@Time : 2020/10/02 23:12:29
@Author : wylu
@Version : 1.0
@Contact : 15wylu@gmail.com
@License : Copyright © 2020, wylu-CHINA-SHENZHEN. All rights reserved.
@Desc : 模板I
模板 #1 是二分查找的最基础和最基本的形式。这是一个标准的二分查找模板,
用于查找可以通过访问数组中的单个... |
f239660e5a2ccdc2991ca59d4aa0bc26970b9e8b | Chasmiccoder/Digital-Fortress-Encryption | /func.py | 2,660 | 3.8125 | 4 | '''
Digital Fortress Common Functions:
'''
def stringToList(message):
# Converts a given message from string format to list format.
word_list = []
word = ''
delimiter = ' '
for i in range(0, len(message)):
if message[i] != delimiter:
word += message[i]
else:
... |
4e574670f75ab7d9c3a9d4430d2fda01481de9ee | KareliaConsolidated/CodePython | /Basics/151_Python_Ex_12.py | 503 | 4.09375 | 4 | # Letter Counter
# Write a function called letter_counter which accepts a string and returns a function. When the inner function is invoked it should accepts a parameter which is a letter, and the inner function should return the number of times that letter appears. This inner function should be case insensitive.
def l... |
b48badb612bf6e8029d4bd62829feca9c6e37d17 | KareliaConsolidated/CodePython | /Basics/130_Regex_Module.py | 436 | 3.75 | 4 | # import regex module
import re
# define our phone number regex
pattern = re.compile(r'\d{3} \d{3}-\d{4}')
# search a string with our regex
res = pattern.search('Call me at 950 555-5656 or 950 555-6565')
print(res) # <re.Match object; span=(11, 23), match='950 555-5656'>
print(res.group()) # 950 555-5656
# Return ... |
aed55c61659e5efbc2c9330ca54947651c00bb67 | KareliaConsolidated/CodePython | /Basics/08_Functions.py | 1,431 | 4.125 | 4 | # Create variables var1 and var2
var1 = [1, 2, 3, 4]
var2 = True
# Print out type of var1
print(type(var1))
# Print out length of var1
print(len(var1))
# Convert var2 to an integer: out2
out2 = int(var2)
# Create lists first and second
first = [11.25, 18.0, 20.0]
second = [10.75, 9.50]
# Paste together first and s... |
23ce14c416b32d4aa28e7c342c9ab201b8f640df | KareliaConsolidated/CodePython | /Basics/49_Functions_Ex_09.py | 312 | 4.25 | 4 | # Write a function called multiply_even_numbers. This function accepts a list of numbers and returns the product all even numbers in the list.
def multiply_even_numbers(li):
total = 1
for num in li:
if num % 2 == 0:
total *= num
return total
print(multiply_even_numbers([1,2,3,4,5,6,7,8,9,10])) # 3840
|
0f356c921a8a20d2fb178d4c1ddd0ec31afda9ba | KareliaConsolidated/CodePython | /Basics/133_Symbolic_Group_Names.py | 224 | 3.890625 | 4 | import re
def parse_name(input):
name_regex = re.compile(r'^(Mr\.|Mrs\.|Ms\.|Mdme\.) (?P<first>[A-Za-z]+) ([A-Za-z]+)$')
matches = name_regex.search(input)
print(matches.group('first'))
parse_name('Mr. Sheldon Copper') # Sheldon |
873d59c466d5d1b9820cfb3ce30d8fce24f74876 | KareliaConsolidated/CodePython | /Basics/17_Conditional_Statements.py | 1,008 | 4.25 | 4 | # Conditional logic using if statements represents different paths a program can take based on some type of comparison of input.
name = "Johny Stark"
if name == "Johny Stark":
print("Hello, " +name)
elif name == "John Fernandes":
print("You are not authorized !" +name)
else:
print("Calling Police Now !")
# In Pyth... |
4dac05e28d6efd9441100f9d70a9f61318e8bb65 | KareliaConsolidated/CodePython | /Basics/21_Loops.py | 613 | 4.34375 | 4 | # In Python, for loops are written like this:
for item in iterable_object:
# do something with item
# An iterable object is some kind of collection of items, for instance; a list of numbers, a string of characters, a range etc.
# item is a new variable that can be called whatever you want
# item references the curr... |
89f86d571bcf10d16fe5f7709d4b96bf3eac2af6 | KareliaConsolidated/CodePython | /Basics/155_Python_Ex_16.py | 378 | 4.09375 | 4 | # List Check
# Write a function called list_check, which accepts a list and returns True if each value in the list is a list. Otherwise the function should return False.
def list_check(li):
return all(type(l) == list for l in li)
print(list_check([[], [1], [2, 3], (1, 2)])) # False
print(list_check([1, True, [], [1],... |
f6f144ae9939c97e2f3ee45dff82029100277512 | KareliaConsolidated/CodePython | /Basics/166_Python_Ex_27.py | 443 | 4.21875 | 4 | # nth
# Write a function called nth, which accepts a list and a number and returns the element at whatever index is the number in the list. If the number is negative, the nth element from the end is returned.
# You can assume that number will always be between the negative value of the list length, and the list length ... |
998e37abce39a8645d26033c2c65ae621feb9396 | KareliaConsolidated/CodePython | /Basics/112_Iterators_To_Load_Large_Files_Into_Memory.py | 1,736 | 4.0625 | 4 | # Loading data in chunks
# There can be too much data to hold in memory
# Solution : Load Data in Chunks
# Pandas Function: read_csv()
# Specify the Chunk: Chunk_Size
# Processing large amounts of Twitter data
# Sometimes, the data we have to process reaches a size that is too much for a computer's memory to handle. ... |
84dea473a9911b96684c54d1f339a442ecac41a6 | KareliaConsolidated/CodePython | /Basics/158_Python_Ex_19.py | 400 | 4.25 | 4 | # Vowel Count
# Write a function called vowel_count that accepts a string and returns a dictionary with the keys as the vowels and values as the count of times that vowel appears in the string.
def vowel_count(string):
lower_string = string.lower()
return {letter:lower_string.count(letter) for letter in lower_string ... |
8fc9bfd8055671b565f4617c76cd82a4d6a272af | KareliaConsolidated/CodePython | /Basics/14_Basic_Plots_With_Matplotlib.py | 428 | 3.78125 | 4 | import matplotlib.pyplot as plt
year = [1950, 1970, 1990, 2010]
pop = [2.519, 3.692, 5.263, 6.972]
# Line Plot
plt.plot(year,pop)
# Scatter Plot
plt.scatter(year,pop)
plt.show()
# When you have a time scale along the horizontal axis, the line plot
# is your friend. But in many other cases, when you're trying to as... |
856cab3eec0dd13ebf864055cbc2e61beae5da70 | KareliaConsolidated/CodePython | /Basics/52_Functions_Ex_12.py | 639 | 4.09375 | 4 | # Write a function called intersection. This function should accepts two lists and return a list with the values that are in both input lists.
# Sets Solution
def intersection(li1,li2):
si1 = set(li1)
si2 = set(li2)
return list(si1 & si2)
print(intersection([1,2,3],[2,3,4])) # [2, 3]
# List Comprehension Solution
... |
c06f926ba0c3bf416e403eed81a0497605ab1eeb | KareliaConsolidated/CodePython | /Basics/160_Python_Ex_21.py | 781 | 4.375 | 4 | # Write a function called reverse_vowels. This function should reverse the vowels in a string. Any characters which are not vowels should remain in their original position. You should not consider "y" to be vowel.
def reverse_vowels(s):
vowels = 'aeiou'
string = list(s)
i, j = 0, len(s) - 1
while i < j:
if string... |
a568d63bac6fbf1c0b2084579dd1126358671177 | danoff0101/python-django | /consumo.py | 359 | 3.84375 | 4 |
# consumo eletricidade
kwh = float(input("digite a quantidade de kwh consumida: "))
tipo = (input("digite o tipo de intalaçaõ: "))
if ((tipo == "r"),(kwh <= 500)) :
preco = float(0.40)
valorfinal=float (kwh*preco)
print (valorfinal)
else:
preco = 0.65
valorfinal=float (kwh*pre... |
0099eb909edb958a1c7540559d589adcdedfac18 | CoWeDeveloper/School-Sheets | /Marksheet and attendence sheet.py | 6,037 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
stuName = input("Enter the student name :")
sub = ["English","Chemistry","Calculus ","Physics","Islamiat"]
markObt = []
percent = []
totMarks = [100, 100, 100, 100,100]
totpercent = 0
for i in range(len(sub)) :
print(f"enter the marks of {sub[i] }")
m... |
1d30b7eef57c813d687869fe248abd97f5422cff | neuropil/pysnips | /ch05_pandas_series.py | 895 | 3.6875 | 4 | import numpy as np
from pandas import Series, DataFrame
import pandas as pd
obj = Series([4, 7, -5, 3])
obj
obj.values
obj.index
obj2 = Series([4,7,-5,3], index=['d','b','a','c'])
obj2
obj2.index
# You can also use the index when selecting calues
obj2['a']
obj2['d']=6
obj2[['c','a','d']]
# Scaler operations wil... |
0cfb32951749e839cc422be9f003ec7dc378b254 | marcof90/g84 | /clase 5/ciclos.py | 112 | 3.546875 | 4 | numeros = [54, 58+5, 45, 12, 57, 84, 64, 25]
i = 0
while i < len(numeros):
print(numeros[i])
i+=1
|
4fce7237070ba196bfc9be81f6419dbc6d569b2a | marcof90/g84 | /retos/reto2.py | 711 | 3.875 | 4 | sesion = True
opciones = ['1', '2', '3', '4', '5', '6', '7']
# indices 0 1 2 3 4 5 6
while sesion:
print('Digita el numero de la opción')
for opcion in opciones:
print(f'Opción {opcion}')
option = input()
if option == '6':
result = input('Cuanto es 5 + 7? ')
... |
58cf05b72653e8cebf52e486ee35ed668d036b80 | lexiewh/spotify-archive | /spotify_archive.py | 4,808 | 3.5625 | 4 | import json
import requests
import sys
from datetime import datetime
import calendar
class SpotifyArchive(object):
"""Move all songs from daily playlist into a month archive"""
def __init__(self, spotify_token):
self.header = {
"Content-Type": "application/json",
"Authorizatio... |
1109711dbb5930140ba324cfdeace23c69f9fd12 | aswinsanakan/python-dojo | /line_plot.py | 519 | 3.8125 | 4 | import matplotlib.pyplot as plt
# Year
year = [1950, 1956, 1978, 1984, 1990, 1994, 2000, 2006, 2011, 2017 ]
# Population
pop = [2.5, 2.9, 3.5, 4.3, 5.2, 5.9, 6.3, 6.5, 6.7, 6.9]
# Generate a line plot ( x axis -> year, y axis -> pop )
plt.plot(year, pop)
plt.xlabel("Year")
plt.ylabel("Population")
plt.title("World P... |
bbbb95519e1f58642b25b4642b7ef20bc0bbbf05 | neoguo0601/DeepLearning_Python | /Python_basic/python_basic/python_basic_1.py | 2,066 | 4.5 | 4 | days = 365
print(days)
days = 366
print(days)
#Data Types
#When we assign a value an integer value to a variable, we say that the variable is an instance of the integer class
#The two most common numerical types in Python are integer and float
#The most common non-numerical type is a string
str_test = "China"
int_tes... |
172f6a5ce73604e8593d603bf877afffd03d7adf | nabetse28/Arqui2-Proyecto2 | /src/processor/clock.py | 984 | 3.890625 | 4 | import time
class Clock:
def start(self, clock):
print("Do you want to run it you or all???\n")
x = input("1. You or 2. All: ")
print(str(x))
if(str(x) == "1"):
print("All")
flag = True
while(flag):
x = input("")
... |
a7513d4983f7fdf3b947c19ea546a66d98b9216b | jianxx/exercism | /python/robot-name/robot_name.py | 699 | 3.765625 | 4 | import random
from string import ascii_uppercase
ALPHABET_SIZE = len(ascii_uppercase)
class Robot:
name_used = set()
def __init__(self):
self.reset()
def reset(self):
name = self.__random_name()
while name in Robot.name_used:
name = self.__random_name()
Robot.... |
9e811700705e97b3c590ea4a1fec955a2cb6f2ec | GaoFan98/HOG-face-algo | /Face similarity/face_similarity.py | 1,384 | 3.734375 | 4 | import face_recognition
from pathlib import Path
from PIL import Image
# Load the image of the person we want to find similar people for
known_image = face_recognition.load_image_file("test.jpg")
# Encode the known image
known_image_encoding = face_recognition.face_encodings(known_image)[0]
# Variables to keep track o... |
13bce8b82d10abec021b12f6a86b64ab14c687d4 | cmuth001/Web-sciences-CS532 | /Assignments/A6/substituteMe.py | 1,919 | 3.5625 | 4 | import csv
from pprint import pprint as pp
def substituteUsers():
users = []
with open("dataset/u.user") as csvFile:
lines = csv.reader(csvFile, delimiter='|')
for line in lines:
age = 24
gender = 'M'
occupation = 'engineer'
if age == int(line[1]) and gender == line[2] and occupation == line[3] and ... |
d78a38eb6e954225d81984b05cd5cc782b5b93b8 | bitlearns/TurtleGraphics | /Assignment14_RegularPolygonsWithTurtleGraphics.py | 2,672 | 4.9375 | 5 | #Program Description: The following program will use turtle graphics to draw
#polygons based on the user's input of how many sides it will have.
#Author: Madeline Rodriguez
#Imports turtle graphics and random
from turtle import *
import random
#The sides function will take in the user's input of number of sides and ... |
a0afe54f540a2858770603bc40e2e77cf5b3a502 | cproctor/quest | /quest/maze.py | 11,923 | 4.46875 | 4 | from collections import defaultdict
import random
def is_even(x):
"Returns True if x is even, otherwise False."
return x % 2 == 0
def is_odd(x):
"Returns True if x is odd, otherwise False."
return not is_even(x)
class Maze:
"""Generates a maze stored in a 2-dimensional array.
This class gene... |
6532cd84bfb71a8231e3640c42c12030e660e7e9 | PY312/hw | /less/HW6.py | 4,795 | 3.90625 | 4 | ru_en = {'монета': 'money',
'красный': 'red',
'кружка': "cup"}
ru_kg = {'монета': "тыйын",
'красный':'кызыл',
'нож':'бычак'}
kg_ru = {'акча':'деньги',
'тамак': 'еда',
'бала':'мальчик'}
kg_en = {'акча': 'money',
'тамак': 'food',
'эркек':'man'}
en_ru... |
bf109cc9761f0ccd520f5b5b49037bf544e99940 | anushreeShenoy3/Connect4 | /game.py | 6,608 | 3.9375 | 4 | import numpy
#define fixed board
rowCount = 6
columnCount = 7
board = numpy.empty([rowCount, columnCount], dtype="<U10")
def makeBoard():
'''
function to create an empty board
:return:
'''
#create an empty board
for x in range(0, len(board)):
for y in range(0, len(board[0... |
7c2660f87a6b9ebe8e1151867c3d72328fc755fd | JoA-MoS/Python-DeckOfCards | /card.py | 2,338 | 4.125 | 4 | # -*- coding: utf-8 -*-
# Check this out for cards display https://en.wikipedia.org/wiki/Playing_cards_in_Unicode
# Create a Suit Class???
SUITS = {1: {'Suit': 'Clubs',
'Symbol': '♣'},
2: {'Suit': 'Diamonds',
'Symbol': '♦'},
3: {'Suit': 'Hearts',
'Symbol': '♥... |
5285394d65bbb76910253fcc4611d22331024e03 | nholman143/LED-wd2812b | /Chase RBG.py | 675 | 3.640625 | 4 | """
LED chase animation loop
"""
import board
import time
import neopixel
#Name leds, set pin location, and led count
pixels = neopixel.NeoPixel(board.D18, 120)
#Set value to zero, x will be used for indexing
#Since indexing starts at zero and will be adding 1 before the animations start
#Keep set to -1
x = -1
while... |
210b377af4842693307e41e7632fb44afcc71842 | mschl/dailyprogrammer | /3x3magicsquare.py | 1,613 | 3.703125 | 4 | #! /usr/bin/env Python3
def test_one():
square1 = [8, 1, 6, 3, 5, 7, 4, 9, 2]
square2 = [2, 7, 6, 9, 5, 1, 4, 3, 8]
square3 = [3, 5, 7, 8, 1, 6, 4, 9, 2]
square4 = [8, 1, 6, 7, 5, 3, 4, 9, 2]
square5 = [9, 9]
print(is_magicsquare(square1))
print(is_magicsquare(square2))
print(is_magic... |
a64fee29b65474879949c905b005046e61298a8e | Isaac-Tait/Deep-Learning | /Python/scratchPad4.py | 893 | 4.15625 | 4 | # Exponent functions
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(3, 2))
# 2D list
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10]
]
print(number_grid[2][2])
print("It is time to... |
f130b1b9b6717d06e3395b37bbabf929a6ee4e5b | HamishFleming/DailyCodingChallenge | /2021-04-28/3.Solution/google-verbose.py | 1,271 | 4.0625 | 4 | #!/usr/bin/env python3
"""
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
"""
__author__ = "Hami... |
38dc0ee54034286a271059e193f9b0cd06c88939 | trammellmaurice/mapping | /djikstras.py | 2,882 | 4.03125 | 4 | """
"""
import sys
def dijkstra(matrix):
start = len(matrix) - 2
goal = len(matrix) - 1
path = {}
class PriorityQueue(object):
def __init__(self):
self.queue = []
# for checking if the queue is empty
def isEmpty(self):
return len(self.queue) == 0
... |
937130641a2ecba64137127a84d5d36de7721a77 | paulram2810/Python-Programs | /right_tri.py | 183 | 3.984375 | 4 | import math
print("Enter the base of triangle : ")
b = int(input())
print("Enter the height of triangle : ")
p = int(input())
h=math.sqrt((b*b)+(p*p))
print("Hypotenuse : ",h)
|
5e792230a55dea552765d704c156809f76aa628b | paulram2810/Python-Programs | /string_test.py | 746 | 4 | 4 | s1="John"
print(s1.isalnum())
s1="Welcome John"
print(s1.isalnum())
s1="ABC"
print(s1.isalpha())
s1="ABC1"
print(s1.isalpha())
s1="123"
print(s1.isdigit())
s1="A123"
print(s1.isdigit())
s1=" "
print(s1.isspace())
s1="A B"
print(s1.isspace())
s1="ABC"
print(s1.isupper())
s1="ABc"
print(s1.isupper())
... |
f600741a00af07cd5ea1ea3c2369dcf2346fa354 | paulram2810/Python-Programs | /table.py | 142 | 4 | 4 | num = eval(input("Enter a number : "))
print("Table of ",num," in reverse")
for n in range(10,0,-1):
print(num," x ",n," = ",(num*n))
|
e5dfd182fe3810d77335f56d8d73ff6d26603be0 | paulram2810/Python-Programs | /armstrong.py | 265 | 4.125 | 4 | num = eval(input("Enter number to check for armstrong : "))
x = num
flag = 0
while x!=0 :
temp = x%10
flag = flag+(temp**3)
x = x//10
if flag==num:
print(num," is an armstrong number.")
else:
print(num," is not an armstrong number.")
|
da3dd6defc3984a3a8d8de101dc2a3b7fc00c5a2 | paulram2810/Python-Programs | /list_fun.py | 207 | 3.828125 | 4 | def print_list(list1):
for i in list1:
print(i)
def rev_list(list1):
list1.reverse()
return list1
list1=[10,20,30,40,50]
print_list(list1)
rev_list(list1)
print_list(list1)
|
7bf1b5cdc24d282f4b45f343e387ecdce43d3d47 | paulram2810/Python-Programs | /101.py | 354 | 4.0625 | 4 | str1=input("Enter First String : ")
str2=input("Enter Second String : ")
if len(str1)==len(str2):
print("Strings are of equal length.")
print("Common characters in the strings are : ")
for i in range(0,len(str1),1):
if str1[i]==str2[i]:
print(str1[i],end=" ")
else:
print("St... |
35b5b504b79b7509927c1a2cec3c3a11a6b75fc9 | bmlegge/CTI110 | /P4LAB_Legge.py | 529 | 3.671875 | 4 | #CTI-110
#P4LAB: Nested Loops
#Bradley Legge
#3/25/2018
import turtle
snowflake = turtle.Turtle()
snowflake.pensize(3)
snowflake.pencolor("cornflower blue")
def branch():
for i in range(3):
for i in range(3):
snowflake.backward(30)
snowflake.forward(30)
snowflake... |
3be02701f737d06284c9a26f1c719cdab2c721d1 | bmlegge/CTI110 | /P3T1_AreasOfRectangles_Legge.py | 737 | 4.15625 | 4 | #CTI-110
#P3T1: Areas of Rectangles
#Bradley Legge
#3/3/2018
print("This program will compare the area of two rectangles")
recOneLength = float(input("Enter the length of rectangle one: "))
recOneWidth = float(input("Enter the width of rectangle one: "))
recOneArea = float(recOneLength * recOneWidth)
rec... |
07009ee6270576667d43ebc3c51cff42354bfcd7 | polarisary/leetcode | /5.py | 1,501 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding = utf8 -*-
"""
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class Solution:
def longest... |
e6af2d70b7912722044cbbd4d28f5574b5165c9c | razorkam/HH-school-challenge-2017 | /1st tour/permutations.py | 385 | 3.71875 | 4 | #TODO find less positive integer x, so that 3*x and 6*x are equal up to digits permutation
def solution():
number = 3
while True:
if (number % 9) == (number * 2) % 9: # digits sums are equal
if ''.join(sorted(str(number))) == ''.join(sorted(str(number*2))):
return number // 3
... |
a1890e556c9b9bae214ab65830c3d3adbef6e348 | 007Parthib/Probability-Calculator | /prob_calculator.py | 1,077 | 3.515625 | 4 | import copy
import random
#Consider using the modules imported above.
class Hat:
def __init__(self, **x):
contents = []
for key in x.keys():
for n in range(x[key]):
contents.append(key)
self.contents = contents
def draw(self, num):
contents = self.contents
i... |
8e9a522e7e223bd48d5b621e17ec68f0a7478dcb | Flek26/Projects | /Hangman_Python/hangman.py | 4,142 | 4.21875 | 4 | import random
import os.path
#Declare variables
#Dictionary that will store names and lives
name_dict = {'d1':{},'d2' :{}}
#List that will hold the values that are the current board list
current = []
#word that the players will try to guess, gets the relative path of the word list
#Pulls a random word from there aft... |
47652d5222e896ab4d5cc01f100e189b56093325 | Marie-EveGauthier/whatIShouldWatch | /bin/tag-analysis/process_urls_for_noentry.py | 1,089 | 3.71875 | 4 | """
get peopleurls as a director
get file list to compare
for each line in file
look for name in dict
when names match, add url
"""
import json
import csv
with open('crewurls.json') as jsonfile:
url_dict_list = json.load(jsonfile)
dictionary = {}
for line in url_dict_list:
entry = dict(line)
dictionary.... |
908bc6e7170ebdec6d8729a890b064c3185452c5 | hensonhusada/beginner-python-exercise | /email_slicer.py | 241 | 3.546875 | 4 | import re
file = open('testing.txt', 'r')
lines = file.read()
file.close()
def read_email(text):
reg = r'([a-zA-z-\.]+)@[\w-]+\.+[\w-]{2,4}'
result = re.findall(reg, text)
return result
result = read_email(lines)
print(result) |
2fe0769a1fa50d2c882ddba9845f9ef6144c3c5b | abhijeet-marekar/Data_structure_and_Alorithms_in_Python | /linked_list.py | 2,147 | 4.09375 | 4 |
class Node:
def __init__(self,data):
self.data = data
self.nextNode = None
class LinkedList:
def __init__(self):
self.head = None
self.number_of_Nodes = 0
def insert_start(self, data):
new_node = Node(data)
self.num... |
900adde72d4c0ea5cd90dc723ff8c9699c87e959 | josephlgheriany92/Machine_Learning | /linear_regression_with_correlation.py | 1,676 | 3.75 | 4 | #from https://medium.com/analytics-vidhya/linear-regression-using-python-ce21aa90ade6
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
USAhousing = pd.read_csv('USA_Ho... |
f4757eb581419b63362df05cbdebee759ec302d3 | flerdacodeu/CodeU-2018-Group7 | /lizaku/assignment2/Q2.py | 2,129 | 4.15625 | 4 | from Q1 import Node, BinaryTree, create_tree
def find_lca(cur_node, node1, node2):
result = find_lca_(cur_node, node1, node2)
if not isinstance(result, int):
raise KeyError('At least one of the given values is not found in the tree')
return result
def find_lca_(cur_node, node1, node2):
# This... |
b93f8ec573992e03b78f890fc8218ff4404ed435 | flerdacodeu/CodeU-2018-Group7 | /EmaPajic/assignment4/assignment4.py | 1,923 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: EmaPajic
"""
def count_islands(rows,columns,tiles):
"""
I am assuming that we can change tiles (set some values to false).
If we couldn't do that, we could just make another matrix where
we would store flags so that we don't visit same tile tw... |
ba1dbae0a1e388e25920186acfb7398a0d43f486 | flerdacodeu/CodeU-2018-Group7 | /lizaku/assignment3/assignment3_tests.py | 1,189 | 3.890625 | 4 | import unittest
from assignment3 import Grid, find_words, Dictionary
class Test(unittest.TestCase):
def setUp(self):
self.vocab = Dictionary(['card', 'cart', 'cat', 'car', 'a'])
self.grid = Grid([['a', 'a', 'r'], ['t', 'c', 'd']])
# tests for isPrefix and isWord
def test_is_word(self):
... |
b7200be40b0f163379aba0867f7d62760c1d178f | flerdacodeu/CodeU-2018-Group7 | /lizaku/assignment1/Q2.py | 901 | 3.875 | 4 | import random
class LinkedList:
def __init__(self):
self.head = None
class Node:
def __init__(self, val, next):
self.val = val
self.next = next
def append(self, val):
new_node = self.Node(val, self.head)
self.head = new_node
def find_kth_f... |
b527dc580492fcdf32ffc948cf71c08c19d639e3 | flerdacodeu/CodeU-2018-Group7 | /EmaPajic/assignment3/dictionary.py | 506 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: user
"""
class Dictionary:
def __init__(self, words = set()):
self.words = words
def add(self, word):
if word in self.words:
return
self.words.add(word)
def is_word(self, word):
re... |
924a555360383c20261dd7bd8d1d5f1f47db1a37 | gunslingeratlarge/python-crawler | /day01_urllib2/learnUrllib/urllib2_get.py | 364 | 3.671875 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import urllib2
import urllib
url = "http://www.baidu.com/s"
user_agent = 'Mozilla'
keyword = raw_input('please input your search keyword')
wd = { 'wd':keyword }
wd = urllib.urlencode(wd)
fullurl = url + '?' + wd
print fullurl
request = urllib2.Request(fullurl)
response = url... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.