blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d62c2e7b6fe1981f14d7b36a4404a1d58c8e2d57 | Archanasurendran12/python-myworks | /numpyar/np10_arithmatic.py | 1,515 | 3.9375 | 4 | # import numpy as np
# a = np.arange(9, dtype =float).reshape(3,3)
#
# print('first array:')
# print(a)
# print('\n')
#
# print('second array:')
# b = np.array([10,10,10])
# print(b)
# print('\n')
#
# print('add the two arrays:')
# print(np.add(a,b))
# print('\n')
#
# print('substract the two arrays:')
# print(np.subtr... |
3d9b0e99515d80dec7481fa0c3bd451b76555478 | EDalSanto/ThinkPythonExercises | /dictionaries.py | 1,301 | 3.96875 | 4 | def histogram(s):
"""
Returns histogram of string as dictionary
s: string
"""
d = {}
for c in s:
if c != " ":
d[c] = d.get(c,0) + 1
return d
print histogram('helllloo') == {'h': 1, 'e': 1, 'l': 4, 'o': 2}
h = histogram('parrot')
def print_hist(h):
"""
Returns ... |
1f9c18db0857575e02e908906deacba309ddf39f | kmgowda/ds-programs-python | /src/string-permutations.py | 838 | 3.796875 | 4 |
def get_perms(lt):
perms = list()
if len(lt) == 0:
return perms
first = lt[0]
rem = lt[1:]
words = get_perms(rem)
if len(words):
for i in range(len(words)):
for j in range(len(words[i])+1):
tmp = list()
tmp.extend(words[i])
... |
5929b0f423754095527085d66c722bf22f210b39 | Hardik11794/TicTacToe-Game-Python | /TicTacToe.py | 6,944 | 4.15625 | 4 |
import random
print("This is TicTacToe !!!")
print(' ')
#*********************************************************
# This function print a board
#*********************************************************
def display_board(board):
print(board[7],'|',board[8],'|',board[9])
print(board[4],'|',board[... |
92cae5e83eb2b42bbfdc05da3f4e4728839448f1 | YaohuiZeng/Leetcode | /438_Find_All_Anagrams_in_a_string.py | 2,086 | 4.03125 | 4 | """
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
... |
514f19e9f1e0faf06e6a44354ab8e519392893a7 | coldmanck/leetcode-python | /0289_Game_of_Life.py | 1,599 | 3.84375 | 4 | # Runtime: 32 ms, faster than 57.55% of Python3 online submissions for Game of Life.
# Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Game of Life.
import copy
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board ... |
81f084c3929007e781197fd0f7f55255da1c91fa | FranckNdame/leetcode | /problems/98. Validate Binary Search Tree/solution.py | 691 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not root:
return True
return self.helper(root, float('-inf'... |
e82fa2a4e3929ae9ec35e3cead18fef1e09e6638 | tnmcneil/Algorithms | /zerosumsort.py | 3,898 | 3.71875 | 4 | # Theresa McNeil
# U09757615
# CS 330 Assignment 1
# 4 a: zerosumsort.py in O(n^2 logn) time
#Python 3.6.4
def zerosumsort(sequence):
# make a hard copy of the sequence to refer to later to preserve the original indices
# takes O(n) time
original = list(sequence)
... |
bf1d62f9bde86f8350dab6b89b692a3ea8d84549 | haldokan/PythonEdge | /pythonEdge/src/org/haldokan/edge/lunchbox/pserver.py | 1,998 | 3.53125 | 4 | # server
#!C:\haldokan\3p\Python34\python.exe -u
import sys
import http.server
import urllib
from urllib import request
import cgi
import cgitb
cgitb.enable() # for troubleshooting
"""
By default this is a file server: 'http://localhost:8000' lists the files wher the server is run.
Specifying ... |
5c549fdb6872feba3b8035cc08d44fdbcefea6a2 | adrielleAm/ListaPython | /Slide2_1.py | 753 | 4.34375 | 4 | '''
Faça um programa que:
a. Solicite ao usuário que digite o nome de um arquivo texto (caminho completo);
b. Solicite ao usuário que digite uma palavra;
c. Verifique em todo arquivo quais as linhas contêm a palavra. Todas as linhas localizadas devem ser salvas em um novo arquivo texto com o nome FIND_<nome_arquivo_ori... |
dff685ca6bc2b1bdfbfd960da06f0f18890f1aca | invenia/mailer | /mailer/mailer.py | 5,714 | 3.5625 | 4 | """
The Mailer class provides a simple way to send emails.
"""
from __future__ import absolute_import
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
from smtplib import SMTP
import six
_ENCODING = 'utf-8'
class Mailer(o... |
a1de82f0dee560ede5dd413adb937d6977de2a16 | karnsaurabhkumar/soscipy | /soscipy/utilities/progress_bar.py | 1,009 | 3.9375 | 4 | import sys
def update_progress(progress):
"""
Update_progress() : Displays or updates a console progress bar
Accepts a float between 0 and 1. Any int will be converted to a float.
A value under 0 represents a 'halt'.
A value at 1 or bigger represents 100%
:param progress: Float as input
:r... |
d1f021119db123ded005b1fd6c1b7b5070ae02a6 | mfnu/Python-Assignment | /Section4-PickleUnpickleUserData.py | 1,337 | 3.890625 | 4 | ''' Author: Madhulika
Program: Section4-PicleUnpickleUserData.py
Input: Enter name, age and country.
Output: Creates a text file and stores the input information in form of list,
and then reads it back.
Date Created: 5/7/2015
Version : 1
'''
import pickle
f = open("picklesUserData.... |
d2d64d210e36255f05881fdea149386e30776d42 | Nand4Kishore/Personal_Projects | /TIC-TAC-TOE-WithAI/TicTacToeGame.py | 7,004 | 4.03125 | 4 | import random
random.seed(1)
import math
class TicTacToeGame:
def __init__(self):
cells = "_________"
self.area = [[*cells[i:i + 3]] for i in range(0, len(cells), 3)]
self.x_turn = len([x for x in cells if x == "X"]) <= len([x for x in cells if x == "O"])
# print(self.area)
... |
fca3a978ca9fcd17fab22cfecfd4e7e81a318edb | Linxichuan/drone | /test.py | 131 | 3.578125 | 4 | print("this is tklin for drone test")
def save(num):
if num == 2:
return
else:
print("tklin")
save(5)
|
10ed38baf9ff435dd2c0bb3ae87b671f4d3241b4 | Energy-Gauntlet/energy-gauntlet-server | /energy_gauntlet/commands/__init__.py | 783 | 3.609375 | 4 | from command import Command
def factory(cmd_type, params = {}):
"""Used to define command classes at run time."""
def __init__(self, new_params = {}):
params.update(new_params)
Command.__init__(self, cmd_type, params)
newclass = type(cmd_type, (Command,),{"__init__": __init__})
return newclass
Drive ... |
83336bc9e82144d67fa8b7766f3365ec4c43ecfb | klaseskilson/aoc-2020 | /day03/main.py | 535 | 3.53125 | 4 | def count(trees: [str], dy: int, dx: int) -> int:
c, x, y = [0, 0, 0]
while y < len(trees):
c += trees[y][x % len(trees[0])] == "#"
x += dx
y += dy
return c
def main():
inputs = [str(s) for s in open("input.txt", "r").read().splitlines()]
print("part one:", count(inputs, 1,... |
810d269b316d05fe7fa043409267428810861665 | ggbiun/roulette | /roulette.py | 4,977 | 3.75 | 4 | from random import randint as r
from math import log2, floor
class Roulette:
""" Roulette class for representing and manipulating a roulette spin wheel. """
def __init__(self, color_streak, min_bet, max_bet, spin_time, max_dur, net_gain_stop):
self.color_streak=color_streak #Sets how many same color ... |
3b37e643e793cb43bb9e48f79ba352d847cdd96c | JEH127/EXERCICES | /somme_multiple_3_5.py | 310 | 3.609375 | 4 | somme_multiple_3 = 0
for i in range(1000):
if i % 3 == 0:
somme_multiple_3 += i
print(f"somme_multiple_3 < 1000 = {somme_multiple_3}")
somme_multiple_5 = 0
for i in range(1000):
if i % 5 == 0:
somme_multiple_5 += i
print(f"somme_multiple_5 < 1000 = {somme_multiple_5}")
|
cd513bf8c89d6a9fb0a64d5ea6686d745961adcf | michaelatmywork/TopoE | /calculations/binary_decision_tree.py | 8,021 | 3.921875 | 4 | test = "trees are connected"
#######################################################################
# SCENARIO RESULTS -- tied to the leaves of the binary decision tree.
msg_condition_results = {
1: "Your customers complain about losing energy on a normal basis, and the electric grid tends to go dark during he... |
4ba5396e9671bc2572d4377cf71c2b4911c4e095 | loredanasandu/algorithms-and-data-structures | /Course 1 - Algorithmic Toolbox/algorithmic-warmup/fibonacci_last_digit.py | 821 | 4.1875 | 4 | # Computes the last digit of the n-th Fibonacci number.
# Input: A non-negative integer n.
# Output: the last digit of the n-th Fibonacci number.
import sys
def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current ... |
6cfa54df17f8cee35cc244272602c6eecddb98b2 | daniel-reich/turbo-robot | /9wfEZ4898nnpa9wL5_23.py | 466 | 3.765625 | 4 | """
Create a function that returns the ASCII value of the passed in character.
### Examples
ctoa("A") ➞ 65
ctoa("m") ➞ 109
ctoa("[") ➞ 91
ctoa("\") ➞ 92
### Notes
* Don't forget to `return` the result.
* If you get stuck on a challenge, find help in the **Resources** tab.
* I... |
7609f87c1f60972ad820641bebafcb5256eed5ab | jerrylee17/Algorithms | /KattisPractice/Winter2020/SecureDoors.py | 430 | 3.75 | 4 | tc = int(input())
room = set()
for _ in range(tc):
action, name = input().split(' ')
if action == 'entry':
res = f'{name} entered'
if name in room:
res += ' (ANOMALY)'
else:
room.add(name)
print(res)
else:
res = f'{name} exited'
if nam... |
5e26e7218d373be3eb84369154caeb5292c286f4 | polmonroig/bird_call | /src/utils/stats.py | 392 | 3.9375 | 4 | import numpy as np
def count_unique(data):
"""
Counts the quantity of unique values in a list
of values
"""
count = {}
for d in data:
d = d.split('-')[0]
if d in count:
count[d] += 1
else:
count[d] = 1
values = [count[k] for k in sorted(co... |
8471adafff728201425af98e4a609e071cf2fc86 | nikuzuki/I111_Python_samples | /1/34.py | 236 | 3.8125 | 4 | # 最大値を取得する
# 最大値を求めたいデータが入ったlistを用意
data = [3, 2, 1, 5, 7, 9, 0, 4, 6, 8]
ans_max = data[0]
for i in data:
if ans_max < i:
ans_max = i
print("最大値は"+str(ans_max))
|
74fb7adf733ca1a5474ffdfb056fb1acf54bff99 | dariadiatlova/spellchecker | /src/utils.py | 1,709 | 3.84375 | 4 | from data import DATA_ROOT_PATH
import pandas as pd
import nltk
def filter_vocabulary():
"""
Function filters vocabulary from words we consider incorrect and adds to the dictionary correct words from lowercase
and capital letter.
:return: list
"""
df = pd.read_csv(DATA_ROOT_PATH / "wordlist.t... |
2867127992952e9d2e2c609db7a299d3af424cd1 | seilkhanovk/Pavlo_Glovo | /user/shit.py | 81 | 3.640625 | 4 | arr = ["a", "b", "c"]
dict = {"abc": arr, "b": None}
for a in dict:
print(a)
|
62840b9dedf42071fe05e344c02cfbe9ac2ce8e4 | ncc1701k/Database | /Modeling/processor/helpers/data_objects.py | 3,545 | 4.09375 | 4 | import itertools
class ShotsData(object):
'''
ShotsData: This object holds some shots data for easier manipulation and
output.
Attributes:
oord: Whether the shots data represents offense or defense.
size: Data for player size, ie big/small/ALL
data: A dict with keys of dates, values of di... |
dd6f6f85690bcdca49e0dbe46f72194ad65362c6 | milnorms/pearson_revel | /ch6/ch6p2.py | 1,335 | 4.28125 | 4 | '''
(Financial application: compute the future investment value)
Write a function that computes a future investment value at a given interest rate for a specified number of years. The future investment is determined using the formula in Programming Exercise 2.19 in Chapter 2 Programming Exercise from the Book.
Use th... |
b7d3fbb06a7618af9cfaf29b008ab50ad60515d7 | kumar-akshay324/projectEuler | /proj_euler_q007.py | 351 | 3.90625 | 4 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
n,c,n_count=1,0,0
while True:
for i in range(1,n+1):
if n%i ==0:
c = c +1
if n==2:
n_count = n_count +1
if n_count == 10001:
break
n = n + 1
print ("The 10 001st pr... |
5cc02d81a0e8a0b7ec41999720f6ccca922ac6dc | HarperHao/python | /exercise/002.py | 442 | 3.796875 | 4 | """
请编写一个函数fun(),它的功能是:求解一个数各个数据位的平方和,
一个数各数字的平方求和最终得到1或145,返这个数。主函数已经实现结果的输出
"""
def fun(number):
sum = 0
for i in number:
sum = sum + int(i) ** 2
if sum == 1 and sum == 145:
return number
else:
return sum
number = input("请输入一个数:")
x = fun(number)
print(x)
|
245d359cf6956c709c5f9d368c612798f10adb8c | Holladaze804/Python-Problems | /Input_Number_Problem.py | 206 | 4 | 4 | a = int(input("What is the first number that you want to enter into the equation? "))
b = int(input("What is the second number that you want to enter into the equation? "))
print(a+b)
print(a-b)
print(a*b)
|
882c0480c9ae73e554bf02d77e2c641dd14dd82a | anomitra/ds-algo-python | /heaps/heap_classes.py | 3,214 | 3.78125 | 4 | class Heap(object):
def __init__(self):
self.array = [-1]
def size(self):
return len(self.array) - 1
def show(self):
print(*self.array[1:], sep=' ')
def move_up(self, index):
return NotImplementedError()
def insert(self, element):
self.array.append(elemen... |
4663d769b1a12a981de13fe958e9f40e5ebc0f3b | yumesaka/CheckiO_jungwoo | /Scientific Expedition/10.Double Substring.py | 675 | 3.90625 | 4 | def double_substring(line):
sameword_list = []
for i in range(len(line)-1):
for j in range(i, len(line)):
if line[i:j] in line[j:]:
sameword_list.append(line[i:j])
if len(sameword_list) >0 :
print(max(sameword_list, key=len))
return len(max(sameword_list,... |
73237a418ce6f2e1bb88317a5e37fce51b4a201f | mhoma-b/exercice-algo | /int_divisible_by_3_or_5.py | 689 | 3.59375 | 4 | #exercice 1: Calculer la somme des entiers divisible par 3 ou par 5 entre 1 et n.
class N : # Définition de notre classe
def __init__(self, nb): # Définition du constructeur
self.n = nb
def run(self): # Définition de la méthode run
i = 0 # la variable qu'on incrémentera
sum_int = 0 # la variable qui s... |
68e1a53bbb8f5ac45559ebf23b3db6845dad4d0b | devsantoss/Modelos-II | /ejercicios de arboles binarios/arbol.py | 1,298 | 3.734375 | 4 | class Nodo:
def __init__(self, valor, izquierda = None, derecha = None):
self.valor = valor
self.izquierda = izquierda
self.derecha = derecha
def buscar(arbol, valor):
if arbol == None:
return False
elif arbol.valor == valor:
return True
e... |
f77204c6ef78db55a1496586055ed0e62322724b | AnhTuan-AiT/CBIR | /v2/FeatureDescriptor.py | 2,530 | 3.578125 | 4 | """
Step1: define feature descriptor
1. convert to HSV and initialize features to quantify and represent the image
2. split by corners and elliptical mask
3. construct feature list by looping through corners and extending with center
"""
import numpy as np
# extract 3D HSV color histogram from images
from cv2 import... |
98c88bdf948e6fd8a64c0f1db5b5f7f1c00925fd | AV272/Python | /Tasks/bank.py | 473 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 17:14:22 2020
@author: alex
Task: function takes two arguments - amount of money and time, and returns
two values - full amount of money on account and sum of percent (10% for year).
"""
def bank(money,years):
x=0;
x = money
for i i... |
f669906e38df06b99068f931cbeac8063fbf15b0 | DanielSBaumann/dias.de.vida | /maisDias.py | 2,919 | 3.8125 | 4 | from datetime import datetime
#definindo datas com int
print('Este programa calcula os dias de vida de uma pessoa')
print()
dia=input('Digite data de nascimento : \ndd/mm/aaaa : ')
vetor_dia=dia.split('/')
data_hoje=datetime.today()
#primeiro calculo qtd de dias pela diferença de anos
dias_anos=(int(dat... |
835441961131299bd6a9fc6b34175a3c2734a2d6 | Environmental-Informatics/06-graphing-data-with-python-thejibin | /program-06.py | 2,641 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on 2020-02-28
by Jibin Joseph -joseph57
Assignment 06 - Graphing Data with Python
Revision 03-2020-04-14
Modified to add comments
"""
## Import the required packages
import numpy as np
import matplotlib.pyplot as plt
import sys
## Check the command lines options before accepting... |
d3a209eaeb1fc72004abc7feb5bad25260c802b1 | OsmanC4hit/PythonNotlarm | /23-hesapmakinesi.py | 920 | 3.875 | 4 | import math
def new_function():
key = 1
while key == 1:
soru = input("Yapmak istediğiniz işlemin numarasını girin 1 giriş (Çıkmak için q): ")
if soru == "q":
break
elif soru == "1":
sayı1 = int(input("bir sayı giriniz"))
sayı2 = int(input("ikinci sa... |
17fb6c5a7cefc0187923a7ab341e73eaae9f801e | syurskyi/Python_Topics | /020_sequences/examples/ITVDN Python Essential 2016/15-list_shallow_copy_bug.py | 2,764 | 4.25 | 4 | # Операция умножения часто используется со списками
# для инициализации списка заданным количеством одинаковых элементов
some_list = [0] * 10
print(some_list)
print()
# Операция * конкатенирует неполные копии списков, то есть объекты
# внутри копий не копируются, а сохраняются ссылки на них.
# Об этом следует помнит... |
2a2d85801b28743256fbb621c87d76cf30e179e3 | PARKGOER/Python | /200717/200717_08.py | 342 | 3.640625 | 4 | class MyError(Exception) :
def __str__(self) :
return "허용되지 않는 별명입니다"
def say_nick(nick) :
if nick == "천사" :
print(nick)
elif nick == "바보" :
raise MyError ()
else :
pass
try :
say_nick("천사")
say_nick("바보")
except MyError as e :
print(e)
|
5d37e73b9a293bf1a8d96ba745aa2a7c43189543 | santospat-ti/Python_Ex.EstruturadeRepeticao | /ex33.py | 735 | 3.890625 | 4 | """O Departamento Estadual de Meteorologia lhe contratou para desenvolver um programa que leia as um conjunto
indeterminado de temperaturas, e informe ao final a menor e a maior temperaturas informadas, bem como a média
das temperaturas."""
import time
quant_temp = int(input("Quantidade de temperaturas que ir... |
13f86b9e68db90e52da2354ec91877b5330686d2 | Maxim-Kovalenko/my-lyceum-python-code | /word_counter.py | 372 | 3.984375 | 4 | string = str(input("Input sentence: "))
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
n = 0
for text in counts:
n = n + 1
return n
print("There are", (wo... |
a47b01e60842feb7a91432fa219eafa3e2827fee | Androspy/myfirstprogram | /licuado.py | 139 | 3.859375 | 4 |
dato = int(input("dime tu edad: "))
if dato >= 18:
print("eres mayor de edad")
else:
print("jajaja que estupidin, largo de aqui") |
f02c346ce2a3c126d68c82b716c8076327432f16 | MLoopz/CodeWars | /baker/baker.py | 687 | 3.6875 | 4 | def cakes(recipe, available):
spent = {}
for demanded in recipe:
if demanded in available:
qty = calculate_quantities(recipe[demanded], available[demanded])
if qty < 1:
return 0
else:
spent[demanded] = qty
else: return 0
re... |
8de946ba202b59ef0592af9005e24958f48ec184 | sivanesanceg/music_recommender | /server_recom/queue_dll.py | 884 | 3.828125 | 4 | class Node():
def __init__(self, path, hp, index):
self.prev = None
self.data = [path,hp,index]
self.next = None
class Queue():
def __init__(self):
self.top = None
self.back = None
def display_top(s):
temp = s.top
a = ''
while temp != None:
print(temp.data)
temp = temp.prev
de... |
1fbf9652e1838c765d12c6e490e579571e01125d | Gonzalowc/HLC_2122 | /Tema1/Ejercicio7.py | 135 | 3.953125 | 4 | nombres = input("Introduce 3 nombres: ")
nombres_separados = nombres.split(" ")
for nombre in nombres_separados:
print(nombre)
|
9e1b8c1cd8966ca6d99c6f1552242e776f25eef3 | Jiezhi/myleetcode | /src/540-SingleElementinaSortedArray.py | 1,473 | 3.65625 | 4 | #!/usr/bin/env python
"""
CREATED AT: 2021/11/20
Des:
https://leetcode.com/problems/single-element-in-a-sorted-array/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Medium
Tag: BinarySearch
See:
"""
from typing import List
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
... |
8609c58ab9677b6af41c50f7191be745e69f7e7a | littlepriyank/guvi_rep | /bs1-3.py | 255 | 4.15625 | 4 | r = input()
if((r>='a' and r<='z')or(r>='A' and r<='Z')):
if(r=='a' or r== 'A' or r == 'e' or r == 'E' or r=='i' or r =='I' or r=='o' or r =='O' or r == 'U' or r =='u'):
print("Vowel")
else:
print("Consonant")
else:
print("Invalid Input")
|
9fcde3cb681fc2891b3257d53f07a842ebd7e071 | lightmen/leetcode | /python/tree/recover-binary-search-tree.py | 701 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inOrder(self,root):
if root is None:
return
self.inOrder(root.left)
if self.pre... |
86d9015447f38166960480cac9ec770098da511f | lukaskellerstein/PythonSamples | /2_OOP/1_inheritance_polymorphism.py | 1,190 | 4.3125 | 4 | class Animal(object):
def __init__(self):
print("Animal created")
def whoami():
print("I am an animal")
def eat():
print("i am eating")
# abstract method
def speak():
raise NotImplementedError("Subclass must implement this abstract method")
# Inheritance
class Do... |
f4964e436eef2fae9b19f9d143ac2408048bf057 | PRAVEEN100999/praveen-code-all | /data.py | 304 | 3.9375 | 4 | def square(a):
return a**2
l = [1,2,3,4]
def my(func , p):
new= []
for item in p :
new.append(func(item))
return new
print(my(square,l))
print(my(lambda a :a**2,l))
#list comprehension
def my2(func,l):
return [func(item) for item in l]
print(my2(lambda a:a**3,l))
|
64fdcc48ea588dc972b89e4ff9b5e26d3163ecd0 | lancelote/advent_of_code | /src/year2020/day01a.py | 646 | 3.59375 | 4 | """2020 - Day 1 Part 1: Report Repair."""
def process_data(data: str) -> list[int]:
return [int(number) for number in data.strip().split("\n")]
def find_2020_summands(numbers: list[int]) -> tuple[int, int]:
for i in range(len(numbers)):
for j in range(i, len(numbers)):
if numbers[i] + nu... |
c3161404357e29027220d25e97c651277a3cb630 | chenjienan/python-leetcode | /144.binary-tree-preorder-traversal.py | 1,578 | 3.859375 | 4 | #
# @lc app=leetcode id=144 lang=python3
#
# [144] Binary Tree Preorder Traversal
#
# https://leetcode.com/problems/binary-tree-preorder-traversal/description/
#
# algorithms
# Medium (50.40%)
# Total Accepted: 310.4K
# Total Submissions: 615.8K
# Testcase Example: '[1,null,2,3]'
#
# Given a binary tree, return the... |
5b8b4de659c0a5bec9dc7cb13ddd0a1b8a416f18 | salimuddin87/Python_Program | /algorithm/sort_quick.py | 1,411 | 4.28125 | 4 | """
Quick sort is in-place sorting and divide and conquer algorithm.
best case: O(nlogn)
worst case: O(n^2) if we pick greatest/smallest element as pivot
There are different way to pick quick sort pivot element:
1. Pick first/last element as pivot
2. Pick random element as pivot
3. Pick median as pivot
"""
... |
abe40e802054502e41f92dacf3d960eb4b9fb13e | suyundukov/LIFAP1 | /TD/TD6/Code/Python/4.py | 381 | 3.609375 | 4 | #!/usr/bin/python
# Retourner l'indice de la plus petite valeur contenue dans le tableau
def recherche_min(tab):
val_min = tab[0]
for i in range(len(tab)):
if tab[i] < val_min:
val_min = tab[i]
return tab.index(val_min)
tab = [5, 18.5, 13.2, 8.75, 2, 15, 13.5, 6, 17]
# val_min = t... |
8212aa73f22b787613e7620025a5ca5370a21a0b | PriyankaMali-13/Python_Learning | /courseera_1_assignment/ex2.py | 391 | 3.515625 | 4 | #try-expect
hrs = input("Enter Hours:")
rate = input("Enter rate:")
try:
h =float(hrs)
r = float(rate)
except:
print("Error, Please put valid input")
#if err do not continue and run further stmt ->
# this will nt give u traceback err, try running without quit()
quit()
if h>40:
reg = h*r
... |
3d006116243f289ff7dc62e8732f4375c5775b34 | Chatwaroon/Portfolio | /workshop/สร้างระบบพยากรณ์อากาศด้วย Yahoo API/WeatherForcast.py | 642 | 3.703125 | 4 | import yweather
from weather import Weather,Unit
client=yweather.Client()
name=input("Input Your City :")
dataid=client.fetch_woeid(name+",Thailand")
weather=Weather(unit=Unit.CELSIUS)
lookup=weather.lookup(dataid)
condition=lookup.condition
location=weather.lookup_by_location(name+",Thailand")
forcasts=loca... |
bb037d511e22c99d7339e2eec9552c24f99774e5 | raghav1674/graph-Algos-In-Python | /Recursion/03/permutations.py | 681 | 3.671875 | 4 | # O(n*n!)
def permutation_helper(input_str, count, output, out, level):
if level == len(input_str):
output.append(out)
else:
for i in range(len(input_str)):
if count[i] == 1:
count[i] = 0
level += 1
permutation_helper(input_str, count,... |
008f8f90fd00a6f34be05bcf3f9b3eb5b6837358 | PatZarama/appTest7 | /conditional.py | 696 | 4 | 4 | '''
this script let you apply basic math operations as:
add, mult, divide, sustract
'''
#libraries####################################
import os
##############################################
#function#####################################
def calc(x, y, z):
if z == 1 :
Ans = x + y
elif z == 2 :
Ans =... |
d26607468c4d818b12eddbc971f9a09624e0b45e | chibitofu/Coding-Challenges | /leap_year.py | 536 | 4.15625 | 4 | def leap_year(year):
"""Take in a year and determines if it's a leap year"""
## Is the year evenly divisible by 4
if year % 4 is 0:
## Is not evenly divisible by 100
## Unless it's also evenly divisible by 400
if year % 100 is 0 and year % 400 is 0:
return True
... |
384d6b9cfd7ed5a68b86f9f9488c393eb845c385 | KingKerr/Interview-Prep | /Arrays/hasSingleCycle.py | 1,030 | 4.09375 | 4 | """
Single Cycle Check.. Given an array of integers that represents a jump of it's value in the array. If your integer is 2, then you
have to jump 2 indices forward. If the integer is -5, then you have to jump 5 indices backwards. If your jump exceeds the bounds of the array,
it wraps over.
Examples:
[2, 3, 1, -4, -4,... |
bb4953dac42b03c09b89a0213afe212e239141ce | hebertmello/pythonWhizlabs | /estudo_for.py | 188 | 3.75 | 4 | # For
# -------------------------------------
l = [1, 2, 3, 4, 5]
sum = 0
for i in l:
sum = sum + i
print(sum)
for i in l:
print(i)
else:
print('fim do loop')
|
4827c1d8e619286abf5a85f72698785f2a0de28d | frodosamoa/cmsi386 | /homework-1/pythonwarmup.py | 1,342 | 3.796875 | 4 | import random
def change(cents):
"""Returns a tuple containing the smallest number of U.S. quarters,
dimes, nickels, and pennies that equal the passed amount of cents."""
if cents < 0:
raise ValueError('Amount of cents must be 0 or greater.')
quarters, remaining = divmod(cents, 25)
dimes, remaining = divmod(rem... |
2ec83b0fdf784b2072c71b69667eda1239fc62c1 | morganmann4/cse210-tc06 | /mastermind/game/director.py | 3,503 | 3.71875 | 4 | from game.code import Code
from game.check import Check
from game.guess import Guess
from game.player import Player
from game.end_game import End_game
guess = Guess()
check = Check()
code = Code()
end_game = End_game()
class Director:
"""A code template for a person who directs the game. The responsibility of
... |
c8b208fc36d19970e637fd628225c8faacd49ad3 | emurph1/unit4 | /localDemo.py | 281 | 3.515625 | 4 | #Emily Murphy
#2017-10-23
#localDemo.py - learn how to us local variables
#local variables are ones that are declared in the function
def f():
x = 77 #x is a local variable
y = 10 #y is a local variable
x = 5
f() #x does not change
print(x)
print(y) #this will cause an error |
04e9218dfb3b5ae86e5808396f92cad83567f34e | vwinkler/LDE-Solver | /DiophanticSum.py | 1,466 | 3.609375 | 4 | class DiophanticSum:
def __init__(self, coefficients, constant):
assert all([type(c) is int for c in coefficients.values()])
assert type(constant) is int
self.coefficients = coefficients
self.constant = constant
def getConstant(self):
return self.constant
def getCoeff... |
bc076ad529c44038294dbc9d8e678dec929cdab7 | liuyazhou0917/hello- | /exercise04.py | 378 | 3.703125 | 4 | """
创建Python文件exercise04.py
结果:终端中显示 请输入武器名称: 用户在控制台中输入了名称
终端中显示 请输入攻击力: 用户在控制台中输入了攻击力
终端中显示 xx的攻击力是xx
"""
armament = input("请输入武器名称:")
att = input("请输入攻击力:")
print(armament + "的攻击力是" + att)
|
636ab3e3567008ed4b6840ed8c6f005f34ccd6f0 | devile-xiang/-_python_spider | /LintCode_test/dome4-统计出现次数.py | 677 | 3.515625 | 4 | #encoding:utf-8
def main(n,k):
print("N的值是%s"%n)
narray = []
for i in range(0, n+1):
narray.append(i)
print("要统计的次数是:%d"%n)
print(narray)
global a
a=0
if type(narray)==int:
print("只有一个数")
for j in str(narray):
print(j)
if j == str(k):
... |
462827628f02f1f2e82f6c9899f521a6c249dda6 | serinamarie/CS-Hash-Tables-Sprint | /hashtable/hashtable.py | 9,122 | 3.9375 | 4 | class HashTableEntry:
"""
Linked List hash table key/value pair
"""
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
# Hash table can't have fewer than this many slots
MIN_CAPACITY = 8
class HashTable:
"""
A hash table that with `capac... |
263e315573713d6393211784f444559fa4933bf0 | merely-useful/py-rse | /src/package-py/08/bin/check_zipf.py | 358 | 3.5625 | 4 | #!/usr/bin/env python
import sys
import zipfpy.check
USAGE = '''zipf num [num...]: are the given values Zipfy?'''
if __name__ == '__main__':
if len(sys.argv) == 1:
print(USAGE)
else:
values = [int(a) for a in sys.argv[1:]]
result = zipfpy.check.is_zipf(values)
print('{}: {}'.fo... |
d2267342acdb1f3bae86a9b0f7cb965192c2e0c1 | iverson52000/DataStructure_Algorithm | /LeetCode/0057. Insert Interval.py | 959 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 10:02:49 2019
@author: alberthsu
"""
"""
!57. Insert Interval
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their sta... |
885c940986da6678fad03f3c8dbd2cb006ea8e36 | Sgggser/python_homework | /lesson_loops.py | 1,604 | 3.96875 | 4 | import random
for i in range (5):
if i % 2 == 0:
print('hello world', i)
else:
print('happy new year', i)
for i in range(20, 10, -2):
print('iteration#:', i)
for _ in range(10):
print('hello world')
print('-----------------------')
for char in "abc":
print(char)
for weekday in ... |
ff522fc326262390ff8362b6dce985d5747b497e | sanjoy-kumar/pythontutorial | /variables.py | 3,367 | 4.625 | 5 | ## Assigning Values to Variables ##
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print(counter)
print(miles)
print(name)
## Multiple Assignment ##
a = b = c = 1 # assign a single value to several variables simultaneously
print(a)
print(b)
print(c)
x, y, z = 1,... |
3575b3f38e21ec62fa1df35cbc012adf3d047ea5 | shv07/dsa | /Arrays/MoveZeros.py | 585 | 3.734375 | 4 | def moveZeroes(nums):
"""
Move all the occurence of zeros to end of the array without changing anyone's relative order.
Do it inplace in O(n)
Ref - Question taken from LeetCode
"""
l = len(nums)
zpos = 0
nextnz = 1
while zpos<l and nextnz<l:
if nums[zpos]!=0:
zpo... |
bad43afa77c8afe4bdb9404cf1180fae6cf7ca3c | zafodB/pythonAssignments | /venv/Assignments/TicTacToe/TicTacToe.py | 13,230 | 3.78125 | 4 | '''
* Created by filip on 26/02/2018
'''
import copy
def main():
board = [["." for j in range(3)] for i in range(3)]
difficulty = 3
# Prints out any board
def print_board(to_print):
print("___________")
for i in to_print:
print("|", end="")
for j in i:
... |
2264a5c3a7cab95d439255747ff0c6c19d836e5c | tomattman/pythonTrain | /c1/4.py | 564 | 3.5625 | 4 | import random
import sys
articles = ['the', 'a']
nouns = ['cat', 'dog', 'man', 'woman']
verbs = ['sang', 'ran', 'jumped']
adverbs = ['loudly', 'quietly', 'well', 'badly']
i = 0
try:
count = int(sys.argv[1])
if 1 > count > 10:
count = 5
except ValueError:
count = 5
except IndexError:
count = 5
while i < count... |
935bf472e2b81b3fc10b91219d94adc81705c707 | mayh0x/funcional_UFC | /topic_3/Python/2-final.py | 415 | 3.609375 | 4 | # Retorne os x números finais da lista
def final(n, xs):
listafinal = []
tamlista = len(xs)
n = tamlista - n
for x in xs:
if n < tamlista:
if x == xs[n]:
listafinal.append(x)
n += 1
return listafinal
print(final (3, [2,5,4,7,9,6]) == [7,9,6]) #Tr... |
7aa7a341064355b4ed0c1e431a6e0273b8f5167c | woxsao/K-Means-implementation | /KMeansImplementation.py | 7,900 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import distance
class KMeansImplementation:
def __init__(self, k, max_iter, tol):
"""
Constructor: k is the number of clusters
max_iter is the maximum number of iterations
tol is the tole... |
76e163673c7ebbb1fca33852fc4a9c8e19ad5b37 | CescWang1991/LeetCode-Python | /python_solution/051_060/SpiralMatrix.py | 2,232 | 3.734375 | 4 | # 054. Spiral Matrix
# 059. Spiral Matrix II
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
spiral = []
if len(matrix) == 0:
return []
if len(matrix) == 1:
spiral += matrix[0]
... |
8040fa64d67ebf11ad647c21aab6fc18b17db528 | yhbyhb/data_analyst_nanodegree_p2 | /P2_codes/data.py | 7,567 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.cElementTree as ET
import pprint
import re
import codecs
from bson import json_util
import json
import dateutil.parser
import audit
"""
data.py wrangles the data(.osm) and transform the shape of the data into the model that
is similar with used in Lesson 6... |
4b98ef5632276a5ffa5f5da33b400dc8f1c986ba | Victody/Pygame | /MovNave.py | 3,000 | 3.5625 | 4 | import pygame
import random
def main():
#Definições dos objetos
screen_width = 600
screen_height = 600
#variáveis para tamanho de tela
pygame.init()
#Iniciando a biblioteca
tela = pygame.display.set_mode([screen_width, screen_height])
#Defini o tamanho de Tela
pygame.display.set... |
3cf3377fccbf1b3d3bbe091ab10ec927d53fb9f6 | green-fox-academy/TemExile | /week-03/day-1/bank_account.py | 1,532 | 3.8125 | 4 | class currency(object):
def __init__(self, code, centralBank, value):
self.code = code
self.centralBank = centralBank
self.value = value
class USADollar(currency):
def __init__(self, value):
self.code = 'USA'
self.centralBank = 'Federal Reserve System'
super().__... |
7e5d65a3ea3a0f341e2c94c441bb76e94c9177d9 | uohzxela/fundamentals | /data_structures/hashset.py | 1,050 | 3.578125 | 4 | class HashSet(object):
def __init__(self, capacity=1000):
self.capacity = capacity
self.buckets = [[] for i in xrange(self.capacity)]
def hash(self, key):
return sum([ord(c) for c in key]) % self.capacity
def add(self, key):
bucket = self.buckets[self.hash(key)]
for i in xrange(len(bucket)):
if bucket... |
b22adfbd6f0b2f667669cfb62953eb98642f0ed9 | finddeniseonline/sea-c34-python.old | /students/MeganSlater/session06/special.py | 713 | 4.3125 | 4 | """Question 1:
If my class inherits from object, do I have to define every special
method I want to be able to use or are special methods set to
some kind of default?
"""
class Rectangle(object):
"""define rectangle class with attributes of height
and width as well as a special method of add"""
def __init... |
65aadd74e28373d7d4258082dcf251fbcec83004 | GMwang550146647/network | /0.leetcode/0.基本数据结构/6.其他/1.LinkHashMap(LFU&LRU)/base.py | 1,238 | 3.765625 | 4 | class Node():
def __init__(self, key=None, val=None):
self.key = key
self.val = val
self.next = None
self.pre = None
class DoubleList():
def __init__(self):
self.head = Node('HEAD', 'HEAD')
self.tail = Node('TAIL', 'TAIL')
self.head.next = self.tail
... |
fad7b1730d73619f9a4a66d2f1658f06f4f64531 | maiali13/cs-module-project-hash-tables | /applications/word_count/word_count.py | 1,185 | 4.09375 | 4 | def word_count(s):
"""
Input: This function takes a single string as an argument.
Output: It returns a dictionary of words and their counts.
Case should be ignored. Output keys must be lowercase.
Key order in the dictionary doesn't matter.
Split the strings into words on any whitespace.
... |
4c486d41f9fdcb05b418b616d656077cbc2ae1ff | Audarya07/Core2Web | /Python/31August/prog1.py | 442 | 3.671875 | 4 | num=0
num1=num;
for outer in range(1,6):
cnt=1
for inner in range(1,10):
if((inner+outer)>=6 and (inner-outer)<=4):
if(inner<=5):
num1=num1+1
print(num1,end=" ")
flag=1;
else:
print(num1-cnt,end=" ")
... |
ccb1fac21d3fe5d40bf58c33810c41c23ec6e761 | simonfqy/SimonfqyGitHub | /lintcode/easy/1283_reverse_string.py | 556 | 3.953125 | 4 | '''
Link: https://www.lintcode.com/problem/1283/
'''
# My own solution. Using two pointers.
class Solution:
"""
@param s: a string
@return: return a string
"""
def reverse_string(self, s: str) -> str:
# write your code here
left, right = 0, len(s) - 1
# Using * is called unp... |
c6e233b891e9fc8f30c8a01b63f5beb2b7ef7acc | Ivan270991/homework2 | /map_filter.py | 159 | 3.515625 | 4 | a=[1,2,3,4,5]
def dubble(i):
return i*2
a=list(map(dubble,a))
print(a)
b=[1,2,3,4,5]
def chek(x):
return x<3
b=list(filter(chek,b))
print(b) |
26c4c9a4e9c221459b025e98ecbf34f1d0a8c26f | shubhamkumar1739/Coding-Practice | /Perfectice/LinkedList(Easy 5).py | 802 | 3.75 | 4 | class Node :
def __init__(self,data):
self.next=None
self.data=data
def insert(root,data):
global tail
node=Node(data)
if root==None:
root=node
tail=node
else :
tail.next=node
tail=node
return root
def traverse(root,position) :
position-=1
if position==0 :
print (root.data)
else :
count=0
tem... |
88540351581e03485b274259863ea5be05e8019b | EduardoAlbert/python-exercises | /Mundo 1 - Fundamentos/028-035 Condições/ex029.py | 443 | 3.875 | 4 | speed = float(input('Qual é a velocidade atual do carro? '))
if speed > 80:
multa = speed - 80
print('\033[32mVocê foi multado em \033[31mR${:.2f} \033[32mpor execeder \033[31m{}Km \033[32mda velocidade limite de 80Km/h!\033[m'.format(multa*7, multa))
else:
kms = 80 - speed
print('\033[34mA velocidade l... |
e36bd108d7e79882a4979fff4d271af38c90a00f | Vihan226/project-104 | /median.py | 862 | 3.921875 | 4 | # list of elements to calculate mean
import csv;
from collections import Counter;
with open('data.csv', newline="") as f:
reader=csv.reader(f)
file_data=list(reader)
file_data.pop(0)
#print(file_data)
#sorting data to get the height of people
new_data= []
for i in range(len(file_data)):
n... |
7b5d263364fd35fe6b9cb94e13ff9800c1ab8ce1 | Constellation-Labs/economic-model | /reference-impl/plots.py | 517 | 3.5625 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
import sys
def graph(func, x_range):
# x = np.arange(*x_range)
# y = func(x)
x = np.linspace(sys.float_info.min, 1.0, 100)
y = np.exp(-1/x)
plt.figure()
plt.plot(x, y)
plt.title('address stake vs bandwidth')
plt.xlabel('DAG in addr... |
923e79928c6dec05c55620e709fc656bb98f54f6 | Fihra/Python-for-linear-algebra | /matrix-hw.py | 1,159 | 4 | 4 | import numpy as np
#create 3 matrices: 2 x 2, 2x2, 3x2
# compute scalar-matrix multiplication
# add all pairs of matrices
m1 = np.array([[4, 5],
[7, 3]])
m2 = np.array([[2, 8],
[9, 12]])
m3 = np.array([[7, 14],
[3, 5],
[11, 10]])
output = np.zeros((2,2))
out... |
80567bd42c68d03007ef024f5c0a3d0204053837 | paulamachadomt/estudos-python-Guanabara | /Python_Guanabara_mundo123/ex017.py | 663 | 3.828125 | 4 | #cálculo do comprimento da hipotenusa com a fórmula
cat_oposto = float(input('qual o comprimento do cateto oposto? '))
cat_adj = float(input('qual o comprimento do cateto adjacente? '))
hipotenusa = (cat_oposto ** 2 + cat_adj ** 2) ** (1/2)
print('A hipotenusa vai medir {:.2f}'.format(hipotenusa))
print ('=' * 100)
pri... |
fe8841204098f2fddd2019899d277dd29601da55 | marcepan/algorithms | /sort/RecursiveBubbleSort.py | 308 | 3.921875 | 4 | def Sort(unsorted_list):
sorted_list = unsorted_list
for i in range(len(sorted_list)):
if i < len(sorted_list)-1 and sorted_list[i] > sorted_list[i+1]:
sorted_list[i], sorted_list[i+1] = sorted_list[i+1], sorted_list[i]
Sort(sorted_list)
return sorted_list |
c4ed1bbea88bf6402633040301772d7390e759ef | Felienne/PythonKoans | /koans/week_3_lesson_1_about_file_IO.py | 1,725 | 3.578125 | 4 |
from runner.koan import *
class AboutFileIO(Koan):
#1
def test_reading_full_file(self):
the_file = open("one_line.txt")
contents = the_file.read()
self.assertEqual(__, contents)
#2
def test_reading_file_with_multiple_lines(self):
the_file = open("short_lines.txt")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.