blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0e9600f2ff523ceb2dcf6298cfe016c1e42fa5ab
davidandinom/david_andino_curso_python
/Tarea 3/Ejercicio_4.py
539
4
4
#Ejercicio 4 #Realiza un programa que pida al usuario cuantos números quiere introducir. Luego lee todos los números y realiza una media aritmética. cantidad = int((input("Cuántos números quiere introducir: "))) i = 1 num = 0 datos = [] while True: if i <= cantidad: num = float (input("Introduce un número:...
b6627d9c8a2e0c16a969ce35d937eabad56e44bd
geek8565/leetcode
/python/sort/selectionSort.py
643
3.703125
4
# -*- coding: utf-8 -*- from __future__ import print_function import sys import os import copy reload(sys) sys.setdefaultencoding("utf-8") """ 每次找全局最小的,找而不交换,最后交换一次; O(n²) 不稳定 """ def selectionSort(array): size = len(array) for i in range(size): minIndex = i for j in range(i+1, size): ...
a51410d708f19b0259a90833878b97f5a46d9343
ladosamushia/PHYS639F19
/NathanMarshall/Warmup2/Fourier Series.py
2,739
4.15625
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 5 13:21:36 2019 Nathan Marshall This code computes Fourier coefficients for an arbitrary function on the interval -pi to pi. As an example it is shown computing Fourier coefficients for a step function that is 0 for t < 0 and 1 for t >= 0. The actual function and Fourie...
8e89e225531628d95a459864f6d7389a06e7620d
HamPUG/examples
/ncea_level2/snippets/snip_l2_21_d.py
3,956
4.125
4
#!/usr/bin/env python3 # import sys import math import time _description_ = """ Locate prime numbers. Use recursive division up to the square root of the integer being tested for being a prime int(math.sqrt(integer_under_test)) Provide heading with number of primes located Include the time taken to...
c1526ad4c5ea4f098eab70e7bb7456a2fd00b2f0
liyong561/python_research
/deep_learning_primary/cv_ops/draw_lable.py
1,940
3.515625
4
from PIL import Image from PIL import ImageDraw from PIL import ImageFont from matplotlib import pyplot as plt ''' python有成千上万的包和类,不可能系统的学习,只能边学边用,在用到时记下。 还有Python的类和方法一般参数众多,但是大部分都可以使用默认值,少部分需要定制 ''' font = ImageFont.truetype('/Library/Fonts/Times New Roman.ttf', 54) # 印象了可移植性 # 学习数组时怎么转换成坐标的 x = [100, 100, 200, ...
07f32970e1b8512646b0fcfecd2f9c7172f017c9
edtech980/python_game_repo
/hand_module.py
1,259
3.625
4
#A hand playing cards from collections import Counter class hand(object): """A hand of playing cards.""" def __init__(self, name = None): self.cards = [] self.name = name def __str__(self): if self.cards: rep = "" for card in se...
fe448ab32cffb4ed343dd86c29a17f2c9628a1ff
GumpDev/PythonTutorial
/hipotenusas.py
322
3.859375
4
import math def calcularHipotenusa(cateto1, cateto2): soma = (cateto1 * cateto1) + (cateto2 * cateto2) return math.sqrt(soma) c1 = float(input("Digite o valor do primeiro cateto: ")) c2 = float(input("Digite o valor do segundo cateto: ")) vlr = calcularHipotenusa(c1,c2) print(f"O valor da hipotenusa é {vlr:.2f}"...
3fba4f17cb20f765a69561273fdf20f1156704db
beingsagir/python-basics
/6. basic_string_operation.py
679
4
4
strVal = "Hello World" print(strVal) # This will print the length of the string print(len(strVal)) # This will print the location of the O print(strVal.index("o")) # This will count and print a perticular string in the string print(strVal.count("l")) #this will find letters in the menssioned position print(strVal[3...
975403aadf5760901aa01e5afa3c446524cf2953
dmitriyVasilievich1986/home-work
/Algorithm/Lesson_03/lesson_3-1.py
1,087
3.765625
4
# region Текст задания # В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. # endregion # инициализация констант START_POSITION = 2 STOP_POSITION = 99 # инициализация словаря для сравнения и хранения счетчика digit_count = {} for item in range(2, 10): ...
41e896f2b07288611b36b66bb3cbcd37ebd1c337
miloserdow/homework
/task0/unit7.py
221
3.84375
4
n = int(input()) primes = [] isprime = [True] * (n + 1) j = 2 while j <= n: k = 2 if isprime[j]: primes.append(j) while j * k <= n: isprime[j * k] = False k += 1 j += 1 print(' '.join(str(x) for x in primes))
7ca961817bd03fd9c71049d21f8ac726861ee724
kovalexal/made_advanced_dl
/task01/blackjack_with_double_counting_split.py
15,279
3.796875
4
import math import random import numpy as np import gym from gym import spaces from gym.utils import seeding def cmp(a, b): return float(a > b) - float(a < b) # 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10 deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def usable_ace(hand): # Does this hand have a ...
d1c8f7accd83eb8a3defc1f41c618e1133c026e6
feisal-Codes/tictactoewithsimpleAI
/loginexample.py
1,671
3.5625
4
import json filename="/home/fesal/Desktop/pythonpractise /thinkPython/details.json" count=3 def details(): details=dict() while True: name=input('Set A username:or press 1 to quit \n') deta=load_details() if name=='1': break if check_if_user_exist(name,deta)==True: ...
463beeb558eccbd167c33c602b9523d0fae94df8
krnets/exercism-python
/rotational-cipher/rotational_cipher_5.py
672
3.796875
4
from string import ascii_lowercase as abc def rotate(text, key): cipher = abc[key:] + abc[:key] table = str.maketrans(abc + abc.upper(), cipher + cipher.upper()) return text.translate(table) q = rotate("a", 0), "a" q q = rotate("a", 1), "b" q q = rotate("a", 26), "a" q q = rotate("m", 13), "z" q q = rot...
6384cb684685401c372799c818e8352efe05ecb4
ambujbpl/pythonBasics
/for_example.py
213
3.984375
4
import turtle_square_using_function; for i in range(3): print("i : ",str(i)); turtle_square_using_function.side6(); for i in range(4): print("i : ",str(i)); turtle_square_using_function.square();
7111730be6aa767e27ada04e3eafc8ae474e568f
oatovar/Artificial-Intelligence
/Problem Set 1/data_structures.py
1,043
3.890625
4
class Queue: def __init__(self): self.queue = list() self.counter = 0 def __len__(self): return len(self.queue) def __str__(self): str = "" for state in self.queue: str += state.name return str def getList(self): return self.queu...
8501acf755550c62636edc89564a8f0de419ca60
samuelveigarangel/CursoemVideo
/ex50_numImpares.py
119
4
4
soma = 0 for x in range(0, 6): n = int(input('Digite um valor: ')) if n % 2 == 0: soma += n print(soma)
af59b604aba0ae9a980c126a229f4e1127b8fe65
lievi/python_study
/decorators.py
915
3.796875
4
# Class Decorator class Decorator_class(object): def __init__(self, original_function): self.original_function = original_function def __call__(self, *args, **kwargs): print("Call method executed this before {}".format( self.original_function.__name__)) return self.original_...
81e62e2224bfc220714d803d37c9c25ff97c85a4
Youngj7449/cti110
/M3HW1_AgeClassifier_Young.py
505
4.3125
4
# A persons age is entered and then they're classified as infant, child, teenager or adult #6/15/2017 #CTI-110 M#HW1 - Age Classifier #Jessica Young # # user_age = int(input('Enter individuals age: ')) if user_age <= 1: Print ('They are an infant.') elif user_age > 1 and user_age < 13: print ('T...
fe92e1e524b8c868cadc027ef832e87fc6308af6
chrisl0411/Python-Fundamentals-Part-1
/Factorial.py
387
4.21875
4
def main(): number = int(input("Enter a number: ")) #sentinel value will be -1 while number != -1: fact = 1 for i in range(1,number+1): fact *= i print ("The factorial of",number,"is",fact) #User Confirmation to keep code running if desired ...
16e98f6812f419cecdf685aca9b214b6decb5cfa
caoxin1988/algo
/python/sort/sort.py
1,104
3.609375
4
m = [2, 3, 3, 7, 3, 9, 9, 12, 6] n = [1, 3, 4, 7, 10, 16, 12, 9, 17, 19] a = m + n n = len(a) def bubble_sort(): for i in range(0, n): for j in range(0, n-i-1): if a[j] > a[j+1]: tmp = a[j+1] a[j+1] = a[j] a[j] = tmp print('new array:') ...
b585f26591b5c5983749cabb697e2941b6132448
mfuentesg/hackerrank
/algorithms/strings/super_reduced_string/super_reduced_string.py
403
3.59375
4
#!/bin/python3 def solve(s): f = [] for i in range(len(s) - 1): if i + 1 in f or i in f: continue if s[i] == s[i + 1]: f.append(i + 1) f.append(i) if len(f) == 0: return 'Empty String' if len(s) == 0 else s else: return solve(''.join...
816c7948514df49f51b970bff7bcfdfd716ac084
Kdcc-ai/python-Numpy-Matplotlib...
/Matplotlib/5个基本绘图绘图函数/3 绘制直方图.py
929
3.515625
4
# 绘制直方图:直方图有啥元素,肯定得有个数据数组,这可以用numpy来实现一个正态分布、泊松分布的数组啥的 # 总结:1. # 关键理解bin参数 bin是多少就生成多少个直立的形状 # 怎么做呢:通过数组a,a中数据有个取值范围, # 直方图将a中数组最大值-最小值均等划分bin个区间 # 但是从元素的值来看他并不是等分落在这个区间上的 # 比如那个正态分布的数组a,在均值100附近落的比较多, # 所以说在直方图每个区间内落了多少个数据,就构成了那个区间的高度 # 2. # 直坐标图的颜色,标题边缘线之类的都可以 import matplotlib.pyplot as plt import numpy as np np.ran...
d372161932dacdd8a27488699a2d2635ee0e0424
FriggD/CursoPythonGGuanabara
/Mundo 2/Desafios/Desafio#62.py
521
3.890625
4
#Melhore o DESAFIO 061, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos. print('------- GERADOR DE PA v2 -------') a1 = int(input('Primeiro termo: ')) r = int(input('Razão: ')) termo = a1 cont = 1 total = 0 more = 10 while more != 0: ...
6946f88d69c064882a98c73bea4a44be06d608d0
basnetaakash23/leetcode_solution
/coding_exercises/nondivisible_subset.py
4,476
3.796875
4
def nonDivisibleSubset(arr,k): for x in range(0, len(arr)): arr[x] = arr[x]%k print(arr) # nums = arr # count = 0 # remainder_list = [] # for i in range(len(nums)): # remainder_list.append(nums[i] % k) # taking all the remainders # if 0 in remainder_list: ...
26fdc12a47eda4e9f2b312bb70bf61d8b7437af8
linyongjietest/unittest
/test_practise2.py
1,695
3.96875
4
#数据参数化,一个函数代替多个函数 import unittest from parameterized import parameterized def mul(x,y): #定义乘法 z = x*y return z class TestAddDemo(unittest.TestCase): # @classmethod # def setUpClass(cls) -> None: # print("=====执行setUpClass方法=====") # @classmethod # def tearDownClass(cls) -> None: ...
1543e31bbe36f352dd18b284bd9fc688332e9486
LucasBeeman/Whats-for-dinner
/dinner.py
1,446
4.40625
4
import random ethnicity = [0, 1, 2, 3] type_choice = -1 user_choice = input("Which ethnnic resturaunt would you like to eat at? Italian(1), Indian(2), Chinese(3), Middle Eastern(4), Don't know(5)") #if the user pick I dont know, the code will pick one for them through randomness if user_choice.strip() == "5": ...
dd82edf75673c867010dbf74377e40f6813c19cd
gomesrodolfo/TrabalhoDeMD_CodigoHuffman
/huffman.py
2,422
3.734375
4
#gera tabela de frequencia def frequencia(arq_freq): tab_freq = {} arq = open(arq_freq, "rt") linha = arq.readline() while linha != "": for i in linha: if i in tab_freq: tab_freq[i] += 1 else: tab_freq[i] = 1 linha = arq.readline(...
09489a013599c2b4fa9e94348eb8b1b8d3f633f9
huiyi999/leetcode_python
/Champagne Tower.py
3,501
3.96875
4
''' We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup (250ml) of champagne. Then, some champagne is poured in the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to th...
3f758ecbfeaa0c4db99d99f355a3c54c61501075
SDRLurker/starbucks
/20150602/20150602_1.py
651
3.53125
4
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ res = [] for ri in range(numRows): row = [ 1 if i in (0, ri) else res[ri-1][i-1] + res[ri-1][i] for i in range(ri+1)] res.append(row) ...
9ccca6e2a68dab3648087db358992b3170dcd8de
nickatnight/wall
/wall_engine.py
7,323
3.671875
4
import os.path, sys, getpass from collections import OrderedDict import cPickle as pickle from users import User class Wall(): """ Creates a new wall engine that will handle data """ def __init__(self): """ Instantiate all defaults for the instance. A new ordered dict word list ...
0c5ebf0c17c2e026355c1da19a0a787bd7cf72e8
gasiferox/Grupo97_Python_Ciclo_I
/Class_Excersices/03. Practicas_Clases/cifrar_listas.py
403
3.671875
4
cifrado=str(input("Ingrese por favor el texto a cifrar: ")) p_clave="murcielago" p_tradu="0123456789" lista_clave=list(p_clave) lista_tradu=list(p_tradu) for i in range(len(p_clave)): cifrado=cifrado.replace(lista_clave[i], lista_tradu[i]) tempcifrado = cifrado print(cifrado) for i in range(len(p_clave)): temp...
8ddffb4f1885f9610efae76f1c6a23ddee8acbe0
pointschan/pylearning
/simpleClass_1.py
450
4.0625
4
__author__ = 'pointschan' class Thing(object): def test(self, str): print str #Class instantiation uses function notation - #creates a new instance of the class and assigns this object to the local variable a a = Thing() #A method can be called right after it is bound a.test("hello") class MyClass:...
318967852a4d792c177a8ab21b0362f554357217
Maben-jm/python-base
/base_002_variable.py
1,214
4.59375
5
""" 变量命名规则: 1.由数字、字母、下划线组成 2.不能使用数字开头 3.不能使用内置关键字 4.严格区分大小写 """ tom = "this is tom" print(tom) jerry = 'this is jerry' print(jerry) print('*****************数据类型**************') ''' 数据类型 1.数值类型 int -- 整数类型 float -- 浮点型 2.布尔型 true false 3.str字符串 4.list列表 ...
3e77e9b581f7595fb6e0489d7e8ed2ad752c37a9
zelestis/3804ICT-Data-mining
/density/slides_distance_matrix.py
3,361
3.5
4
import random import numpy as np from sklearn.cluster import DBSCAN def distance_matrix_slides_dbscan(similarity_matrix, radius: float, minimum_points: int): """ Does DBSCAN (Density Based Clustering of Applications with Noise) Time: O(n^2) Space: O(n^2) (pre-existing in similarity matrix) :param...
c3eef6098b7b774b491ddfbea33e3e9014dfc835
LukeCostanza/CIS106-Luke-Costanza
/Assignment 13/Activity 1.py
1,198
4.03125
4
#This program displays the users input in a different order the it is recieved. def get_name(): while True: print("Enter name (First Last):") name = input() error_1 = get_error_1(name) if error_1 == "n": error_2 = get_error_2(name) if error_2 == "n": ...
cb527e7a6b5a199c338e767fbcc49cd5dd41865d
eriksylvan/AdventOfCode2019
/day_01.py
1,516
3.953125
4
# https://adventofcode.com/2019/day/1 from math import floor inputFile = 'input/01_input' def fuel_calculator(mass): """Calculates the fuel required to launch a given module Parameters: mass (int): the mass of a module Returns: int: the amount of fuel needed to launch """ fuel = flo...
4e8e879bad99714e9201f2b80e870714823277da
losangelesdsa/meetups
/2017-03-20-stacks-queues/queue.py
323
3.5625
4
class Queue: def __init__(self): self._items = [] def enqueue(self, value): self._items.insert(0, value) return self._items def dequeue(self): return self._items.pop() def size(self): return len(self._items) def isEmpty(self): return self.size() ==...
740b4cdca1f7eaa1e3753085ec37b7510be5fa98
gh-develop/coding-test-kw
/ssoonnwwoo/스터디/배열과 연결리스트/연습문제2.py
613
3.75
4
''' 리스트 내포 기능을 이용해 다음 문장으로부터 모음('aeiou')을 제거하십시오. "Python is powerful... and fast; plays well with others; runs everywhere; is friendly & easy to learn; is Open." ''' s = "Python is powerful... and fast; plays well with others; runs everywhere; is friendly & easy to learn; is Open." vowel = ['a', 'e', 'i', 'o', 'u']...
d923fcd71ec1786abca402d707a84f78f1f98823
johnwatterlond/playground
/turtle_random_walk.py
8,912
4.3125
4
""" Module used to simulate random walks with turtle geometry. This module was created while reading parts of `Turtle Geometry` by Harold Abelson and Andrea diSessa. Make sure to set the turtle speed to zero and the screen delay to zero. """ import turtle import math import random class Point: """ Repres...
1e1a2d52445839695cc7ab2c3d0682589d50a637
Gendo90/topCoder
/400-600 pts/topcoderExerciseMachine.py
1,810
4.03125
4
#Problem Statement #     #You are writing firmware for an exercise machine. Each second, a routine in your firmware is called which decides whether it should display the percentage of the workout completed. The display does not have any ability to show decimal points, so the routine should only display a percentage if ...
6324d2c031d8ee56f72be211a9962460219eaa71
Dearin/PracDemo
/test_mock/test_mock_func_undo.py
409
3.5
4
import unittest from unittest import mock def add(self, a, b): # 功能暂未完成 pass class TestMock(unittest.TestCase): '''功能未完成,mock一个方法''' def test_add(self): # 当测试的功能未开发时,实例化一个mock对象并赋值给被测方法 mock_add = mock.Mock(return_value=6) add = mock_add self.assertEqual(add(3, 3), 6...
3d0f3f772dacdfc4f605db5dee40d196c1510b27
nicoleta23-bot/instructiunea-if-while-for
/prb8.py
420
3.890625
4
a=int(input("dati primul nr: ")) b=int(input("dati al doilea nr: ")) c=int(input("dati al treilea nr: ")) if (a<(b+c)) and (b<(a+c)) and (c<(a+b)): print("este triunghi") if ((a==b==c)): print("echilateral") if (((a==b) and (a!=c)) or ((b==c) and (b!=a)) or ((a==c) and (a!=b))): prin...
b88011bf3a0ee9246264cfb8fb260dc101ad1d34
krystiankkk/excers
/classBG.py
669
3.515625
4
import random import bubblesort class biggame(): def __init__(self, count, lim): results = [] user=[] trafione=0 self.lim = lim self.count=count results = random.sample(range(1, lim), count) #print(bubblesort.bubble(results)) a=bubblesort.bubble(resul...
8146e4f59669b4e791eeab1d9eaa07320baa9e6b
Psingh12354/CodeChef
/Reverse The Number.py
112
3.53125
4
# cook your dish here n=int(input()) for i in range(n): k=int(input()) x=str(k) print(int(x[::-1]))
0bf749c20ce129767a63ed560fb89c70263addcc
brpat/IntroToPython_Projects
/COP1000/Chapter 1/test11.py
532
3.5625
4
# Today is chapter 1 lesson, we work on canvas from tkinter import * import time master = Tk() canvas_width = 800 canvas_height = 700 w = Canvas (master, width=800, height=canvas_height) w.pack() img = PhotoImage(file ="images.gif") pic1= w.create_image(10, 400, anchor=NW, image=img) pic2=w.create_i...
5705c4696d946aa3a284cb07482c289ba1d3e834
isabellabvo/Design-de-Software
/Palavra mais frequente.py
680
3.96875
4
#---------ENUNCIADO---------# ''' Faça uma função que recebe uma lista de palavras e retorna a palavra mais frequente. Por exemplo, para a lista ['abobora', 'chuchu', 'abobora', 'abobora', 'chuchu’] sua função deve retornar 'abobora'. O nome da sua função deve ser mais_frequente. ''' #----------CÓDIGO----------...
13d9c22ad534a6b663a76ec98dfa319c4b51649a
LadyM2019/Python-Fundamentals-Softuni
/02. Lists/10. Square Numbers.py
233
3.765625
4
import math as m arr = input().split(" ") for i in range(len(arr)): arr[i] = int(arr[i]) arr.sort() for num in reversed(arr): if num < 1: continue if m.sqrt(num) == int(m.sqrt(num)): print(num, end=" ")
14d7f22e0e624136ea2ef8c1d5841906e874cd60
PurnaKoteswaraRaoMallepaddi/PreCourse-2
/Exercise_5.py
817
3.9375
4
# Python program for implementation of Quicksort # This function is same in both iterative and recursive def partition(arr, l, h): # Pick the rightmost element as a pivot from the list pivot = arr[h] pIndex = l for i in range(l, h): if arr[i] <= pivot: # swap(a, i, pIndex) ...
81ff3f60d461c0aca06a22f6c27b1aae968aabdf
jhembe/python-learning
/classes/Inheritance.py
643
4.28125
4
# Inheritance is basically a mechanism of re-using code.. class Mammal: def __init__(self,name,leg_count,color): self.name = name self.leg_count = leg_count self.color = color def walk(self): print(f"{self.name} can walk") # NOTE in order to show / innitialise inherita...
cfe10fa0f1e1022212bd32333ac0ec97c224140e
ManishBhojak/Python-Projects
/Factorial(prac 3).py
279
4.1875
4
#Print Factorial of given number n=int(input("Enter a number: ")) f=1 if n<0: print("Sorry, Invalid Entry") elif n==0: print("Factorial : 1") else: for i in range(1,n+1,1): f=f*i print("Factorial of ",n,"is ",f) #Program Ended
d0922c5ee11b8644dc3bff6436e8aa52cd4e4799
abdul-musawwir/algorithmsproject
/source/functions/knapsack.py
1,079
3.765625
4
# Input: # Values (stored in list v) # Weights (stored in list w) # Number of distinct items (n) # Knapsack capacity (W) def knapSack(v, w, W): # T[i][j] stores the maximum value of knapsack having weight less # than equal to j with only first i items considered. T = [[0 for x in range(W + 1)] for y in rang...
beaabf38663bc4ee7fafc7946dada50a6fc0c239
theovoss/Chess
/chess/board/base.py
1,174
3.71875
4
class Board: def __init__(self, num_rows, num_columns): self._board = dict() for row in range(num_rows): for column in range(num_columns): self._board[(row, column)] = None self.rows = num_rows self.columns = num_columns @property def board(self...
6c4eeb562e0618eb753b9eaf29fe4b6e90a5ab70
megasan/210-CT
/coursework 2.py
393
4.25
4
""" Count the number of trailing 0s in a factorial number. """ import math def factorial(number): i = 1 result = 0 """ use maths to work out the number of trailing 0s. """ while i: current = math.floor(number / (5**i)) if current == 0: break result = r...
a301bd14ecec53d619b472c8298cace962b835c8
aly22/cspython
/own_projects/shopping_cart.py
1,878
4.15625
4
# I will be making a shopping cart app which takes 3 inputs the number of items # the item name and the price of the item and stores them in a list. # the writing to file is not possible because the data would be inconsistent # sorted in the order of price, number of items, and name of the item # while item name is not...
fa049740d93d91a3b7d62b37f75e68d605dbc695
itsolutionscorp/AutoStyle-Clustering
/assignments/python/61a_hw4/src/34.py
219
3.53125
4
def num_common_letters(goal_word, guess): final, new_lst = 0, [] for elem in goal_word: for letter in guess: if elem == letter: new_lst += [elem] return len(set(new_lst))
831e8d0571ebaeb4b37f4ce33fc19424bd35adc8
Mhychuang/Data-Structure
/1. Two Sum.py
383
3.578125
4
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dict_ = {} for i in range(len(nums)): num = nums[i] print (num) if num not in dict_: dict_[target - num] = i print (dict_) else: ...
2f65c6651f2385558f131463468c0e9844c53cd8
danjpark/python-projecteuler
/019.py
468
4.09375
4
""" How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? """ import datetime from datetime import date def main(): count = 0 for year in range(1901, 2001): for month in range(1, 13): # weekday 0 is monday if datetime...
e9464d23812ccb5a6e0ea4ab7ede24ab91c119cc
mykb2018/chap4_function
/chap4_function.py
770
4.09375
4
# Basics of Python function. def function_name(parm1, parm2): return parm1 + parm2 print(function_name(5, 10)) # When you have multiple parameters and if one of those have default value, you have to # define the parameter which have default value at last. def function_name2(parm4, parm3=100): print(parm4) ...
ee0e090989204f5b91f0f6c2ee6d981e370ace84
wonpyo/Python
/Basic/RandomNumber.py
1,025
4.25
4
# Using the random module, we can generate pseudo-random numbers. # The function random() generates a random number between zero and one [0, 0.1 .. 1]. # Numbers generated with this module are not truly random but they are enough random for most purposes. import random as rand # The random module provides access ...
72c187595d651863a9eb62fc6164e4c1d8e06d92
greghull/advent-of-code-2020
/day10.py
2,292
3.546875
4
# To solve part 2: # Based on the constraints of the puzzle: # Any edge length of 3 must be included in all paths # We can split a large graph into independent graphs at those edges # # Given array of independent graphs [G_1, G_2, ..., G_n] # Then the total number of paths from start to finish is: # n_paths(G_1) * n_pa...
3d598d15cb3d8ed03a25cffed2256cf098f47b5f
sebaxtian/raspberrypi3
/lighting_led/gpio_control_1.py
600
3.921875
4
''' Ejemplo de encender un LED durante 3 segundos despues de presionar un boton. Fuente: https://www.raspberrypi.org/learning/physical-computing-with-python/worksheet/ Fecha: mar dic 6 21:06:10 COT 2016 Version: 1.0 ''' from gpiozero import LED, Button from time import sleep # Usando el GP17 controlamos el LED led =...
4801c333c9a989d482d25da341c29e36a4c8cefb
clesk/unitconvert
/unitconvert/temperature.py
517
3.921875
4
""" Python module for converting temperature units F to C or C to F """ def celsius_to_fahrenheit(temp): """Converts temperature units C to F PARAMETERS ---------- temp : float Scalar temp in Celsius RETURNS ------- float Scalar temp in Fahrenheit """ return 9/5*temp + 32 def fahrenheit_to_celsius(te...
07c041418fa1c3afd9a3db17cf3b58a971e0b566
taro-0/python-notes
/instrucciones/imc-v2.py
547
3.734375
4
# Proyecto: Índice de Masa Corporal # Autor: Estuardo Díaz # Carnet: 1324545-3 # Calcular el índice de masa corporal de una persona print("¡Bienvenidos! Vamos a calcular el IMC") altura = input("Ingrese su altura en metros: ") # Convierte simbolos a decimales altura = float(altura) peso = input("Ingrese su peso en K...
dcce8c23b97e69e83ad156994668f97451fbe6b6
Dharokerme/1-Millonario
/Pregunta.py
1,609
3.78125
4
import random class Pregunta(): # Se instancian los metodos y atributos necesarios para el correcto funcionamiento lista = [] def __init__(self): self.categoria = int(input('Ingresa la categoria:')) self.pregunta = input('Ingresa la pregunta:') self.resp_correcta = input('Ing...
5d1ec89b6e96a0d76e74d00a9b6c2be5aa2c4d8e
AbhinavJain13/oct_2016_python
/shirfeng_chang/Animals.py
943
3.890625
4
class Animal(object): def __init__(self, name, health=100): self.name = name self.health = health def walk(self): self.health-=1 return self def run(self): self.health-=5 return self def displayHealth(self): print self.name print self.healt...
12c049fdcf6c3ff05efc9d6e3d454d0336dfa112
fding/evilpoker
/neuralnet/neuralnet.py
10,126
3.875
4
import theano.tensor as T import theano import numpy import math #from theano.compile.nanguardmode import NanGuardMode ''' Choice of activation functions: For output units, use: LINEAR_FUN if you want to predict the mean of a Gaussian distribution SIGMOID_FUN if you want to predict a Bernoulli var...
42d4034457bffdd9159a4053621b3f78e6202575
mkterhov/advent-of-code-challenges
/Edition2019/day1.py
993
3.84375
4
import math def read_input(file): file = open(file, 'r') Lines = file.readlines() data = list() count = 0 # Strips the newline character for line in Lines: data.append(int(line.strip())) return data def calculate_req_fuel(mass): req_fuel= mass/3 req_fuel = math.floor(req_fu...
83e3540ee1a9d233137c3ea7f39b745bd0d0e511
vkmb/py101
/intro1/fibo.py
428
3.890625
4
#Create an array of the first two numbers in the Fibonacci series # accept the range from command line # usage: # python fibo.py count import sys try: count = int(sys.argv[1]) except: count = 20 fs =[1,2] for n in range(count-2): # Except for the first two every number in the series is the sum of two previous nu...
2378f03799465bc9d830b721e82a06dcd3fc30cc
clayll/zhizuobiao_python
/练习/day07/2.初识numpy.py
1,805
4
4
#前言:numpy时一个模块,把所有matlab的功能都包括了。涵盖了所有已知数学函数领域的内容。 #数据类型是数组 Numpy都是围绕数组展开。一般称之为ndarray。 #引入numpy包 import numpy as np #1.创建数组的方法:a = np.array(),括号中接受任何numpy可接受的容器(元组和列表),转换成数组 # a = np.array([0, 1, 2, 3, 4]) # print(a)#[0 1 2 3 4] <class 'numpy.ndarray'> # print(a[1]) #下标查询方式基本同python # # b = np.array((0, 1, 2, 3, 4)) ...
d78a75603db4ada33487a6f8b63e4400bb17afc7
ballib/SC-T-111-PROG
/prof/Lokaprof/Midterm_2/longest_word.py
585
4.375
4
def open_file(filename): with open(filename, 'r') as file: word_list = [] for word in file.readlines(): word_list.append(word.strip()) return word_list def find_word(word_list): longest_word = "" for word in word_list: if len(word) > len(longest_word): l...
52a313ba8b06f57298089d0361c8cc62037527ef
njerigathigi/learn-python
/join.py
325
4.375
4
# The join() method takes all items in an iterable and joins them into one string. # A string must be specified as the separator. # string.join(iterable) # Parameter Description # iterable Required. Any iterable object where all the returned values are strings letter = 'a' new_letter = ''.join(letter) print(new_let...
a1b0e6c4d99c560049d086bfce954c2770e16c29
leesoongin/Python_Algorithm
/프로그래머스/튜플.py
1,256
3.875
4
#하나짜리가 맨 앞자리 # 두개짜리에서 맨앞자리를 제외한 나머지가 2번쨰 자리 # 세개짜리에서 앞의 두개를 제외한 나머지가 3번째 자리 # 네개짜리에서 앞의 세개를 제외한 나머지가 4번째자리 import re def solution(s): answer = [] s = s[2:-2].split("},{") tmp = [] for item in s: tmp.append(item.split(',')) tmp.sort(key=len) for item in tmp: for ele in it...
fec36bf79a1434deee10bb9c02d55715f44a0591
rajkumar2521/PF
/practice36.py
790
4.25
4
def find_target_positions(input_string, target_word): target_list=[] #Start writing your code here input_string=input_string.split(" ") count=0 for i in input_string: if i==target_word: target_list.append(count) count+=1 return target_list def find_inv...
0486e08fc8bccee06d79db378d3b3f88ddde81e5
fabriciolelis/python_studying
/coursera/Michigan/chapter_8/number_list.py
217
4.0625
4
numlist = list() while True: inp = input('Enter a number: ') if inp == 'done': break value = float(inp) numlist.append(value) print('Maximum: ', max(numlist)) print('Minimum: ', min(numlist))
570de6fd6b8a4c025e058ee32d495df3f8d27e7a
zcybupt/leetcode
/014_longest_common_prefix/Solution.py
456
3.75
4
class Solution: def longestCommonPrefix(self, strs: list) -> str: if not strs or len(strs) == 0: return '' common_prefix = '' for tmp in zip(*strs): tmp = set(tmp) if len(tmp) == 1: common_prefix += tmp.pop() else: break return common_prefix if...
9b866249f15dcce33a7d5a7b0dcc58eef3dbcaa4
ueoSamy/Python
/lesson1/easy.py
1,598
3.890625
4
__author__ = 'Kayumov S. K' # region Задача-1: # поработайте с переменными, создайте несколько, # выведите на экран, запросите от пользователя и сохраните в переменную, выведите на экран a = 5 b = 3 c = "Сумма" d = int(input("Введите 3 число")) print(c, + "3х чисел = ", a + b + d) # endregion # region Задача-2: # З...
835e30c501ac858a6a6f41865877a2fe0dfe6c22
Keneisanuo/Keke
/car.py
319
3.953125
4
class car() : def __init__(self, color,price): self.color = color self.price=price def cars(self): return self.color,self.price col=(input("enter color:")) pr=int(input("enter price:")) obj=car(col,pr) print("the car color and price is: ",obj.cars())
4c0ddcbc0c35decc0ee23283b90eae55d271ba72
prajjwalkumar17/DSA_Problems-
/dp/Knapsack_fractional.py
1,721
4.28125
4
""" Knapsack problem using the fractional/greedy method given the weights and their corresponding profit values, fractional implementation allows filling knapsacks with parts/fractions of the items We fill knapsack of capacity W to obtain maximum possible value in bottom-up manner. Time Complexity = O(n logn) """ def...
8a43b7551899503343b1b33af7c4ce3017475ad9
jparng/Exercises
/Examples.py
473
4.1875
4
name = input("What's your name? ") # Asks for a name and prints it out print('Hello ' + name + '!') hours = float(input('Enter your hours: ')) # Asks for number of hours at rate = float(input('Now enter your rate: ')) #rate and then calculates the pay pay = int(hours * rate) print('Here is your pay: ' + str(pay)) f...
1304a451225548fb083eb9844d113d0fb150d1c0
milroy-cmd/AI-assignment
/app.py
1,895
4.1875
4
# loading in the model to predict on the data import pickle import streamlit as st model = pickle.load(open('model.pkl', 'rb')) def welcome(): return 'welcome all' # defining the function which will make the prediction using # the data which the user inputs def prediction(Contract, MonthlyCharges,...
f9f02090aec7d5de22a734718581f407d086ffa9
daincz/algoritmia
/sa_knapsack_vfinal.py
3,579
3.703125
4
#! /usr/bin/python ##################################### ## Knapsack -- Simulated Annealing ## ##################################### ## Diana Cruz ## UART - UNPA ## version final import random import math COOLING_FRACTION = 0.995 def init_solution(weight_cost, max_weight): ## generacion de solucion inicial ale...
7a697c8242cc5cf3553e2f231a920672f68af06b
paul5566/leetcode-cli
/19.remove-nth-node-from-end-of-list.py
1,166
3.78125
4
# # @lc app=leetcode id=19 lang=python3 # # [19] Remove Nth Node From End of List # # https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ # # algorithms # Medium (33.91%) # Total Accepted: 347.4K # Total Submissions: 1M # Testcase Example: '[1,2,3,4,5]\n2' # # Given a linked list, remove the...
4eafc7208ac8ace7fee0893421d2bd484ffeca3e
LCintra/faculdade
/2 Semestre/Algoritmo e Lógica de Programação II/Outubro/7 Outubro/teste2.py
198
4.03125
4
primeiro = '100' #string segundo = '200' #string print(primeiro+segundo) #concatenação print(primeiro * 3) #repete 3 vezes a string "primeiro" print(segundo * 2) #repete 2 vezes a string "segundo"
a612b76b0e5c4fc8e1547435ca9584fedec7b368
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/171/47322/submittedfiles/testes.py
297
3.578125
4
# -*- coding: utf-8 -*- import math #COMECE AQUI ABAIXO n=int(input('digite n:')) num=1 den=1 s=0 for i in range(1,n+1,1): valor=num/den num=num+i den=den+(i**2) for termo in range(1,n+1,1): if termo!=0: s=s+valor else: s=s-valor print(s)
597636ae69138502f277353ea1f7f351a368baf2
silasjimmy/Intro-to-Python-programming
/ps4/ps4b.py
8,375
4.0625
4
# Problem Set 4B # Name: Silas Jimmy # Collaborators: None # Time Spent: 3 hrs import string def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. ''' ...
7186bf5ddd38886396a994570661b700ceb1740b
jordanatimoteo/lp2
/ex5.py
70
3.5
4
n = int(input("entre com a idade do cachorro:")) print(2*10.5+(n-2)*4)
a4a6a4e500575430e515360e7575704ad7522cf4
ahmetihsankaya/week5
/exercise 5.3.23/6th.py
229
3.5625
4
def scalar_mult(scalar, vector): results = [] for i in vector: results.append(scalar * i) return results #print(scalar_mult(5,[1,2])) #print(scalar_mult(3, [1, 0, -1])) print(scalar_mult(7, [3, 0, 5, 11, 2]))
9d7863e9fd85cd1504fbd39593933bc900f3e6f0
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc045/B/4911037.py
126
3.84375
4
# -*- coding utf-8 -*- d = {x:list(input()) for x in "abc"} s="a" while d[s]: s = d[s].pop(0) print(s.upper())
5587f970354cfc0f13d8ce900cdec6fc6ba08428
RayWLMo/Eng_89_Python_OOP
/animal.py
826
4.46875
4
# Creating an Animal class # Step 1 class Animal: # follow the correct naming convention # we need to initialise with built-in method called __init__(self) # self refers to current class def __init__(self): # Declaring attributes in the init method self.alive = True self.spine = True ...
3fc723c523713967961a38c3499e08701f8766ac
bgalamb/adventofcode
/2017/3/solutionDictbuilder.py
1,532
3.796875
4
#number, coordx, coordy matrix = {(0,0):1} coord = [0,0] directions=["right","up","left","down"] def cangotodirection(direction): #right if direction == "right": if (coord[0]+1,coord[1]) in matrix: return False #left if direction == "left": if (coord[0]-1,coord[1]) in matrix...
164f38c98620f6aab847b99d2ff2a10bbb32c2ae
zhangwang0537/LeetCode-Notebook
/source/Clarification/Dynamic_Programming/零钱兑换.py
906
3.578125
4
# 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 # # 示例 1: # # 输入: coins = [1, 2, 5], amount = 11 # 输出: 3 # 解释: 11 = 5 + 5 + 1 # 示例 2: # # 输入: coins = [2], amount = 3 # 输出: -1 # 说明: # 你可以认为每种硬币的数量是无限的 class Solution: def coinChange(self, coins: List[int], amount: ...
1af5e1c18d5d2302fdf3beaeda925854c30f6687
hanan-saad11/Task2
/task2.py
1,310
3.78125
4
#>>> H <<< for row_h in range(7): for col_h in range(6): if col_h == 0 or col_h == 5 or (row_h == 3 and (0 < col_h < 5)): print("$", end="") else: print(end=" ") print() print("*********************************************************************************************")...
779c1b4b1aa45adc9d07f8805b810d4c6dc48083
SofiaNikolaeva-adey-201/self_Education
/exc2.py
124
3.625
4
numbers = [5, 2, 5, 2, 2] for i in numbers: output = '' for j in range(i): output += 'x' print(output)
6059ca42c2c8c20189d1ad0f4064366f88ebad45
Taeg92/Problem_solving
/Baekjoon/Recursion/BOJ_1074.py
478
3.703125
4
# Problem [1074] : Z import sys n = 0 def recursion_Z(x, y, size): global n # 종료조건 if x == r and y == c: print(n) return # 재귀 if x <= r < x + size and y <= c < y + size: recursion_Z(x,y,size//2) recursion_Z(x,y+size//2,size//2) recursion_Z(x+size//2,y,size//...
0fce9dbfd318353d38f3d6480acd2c7f2d3e5aec
amitsaxena9225/XPATH
/sakti/dict comprehension.py
650
4.40625
4
# Python code to demonstrate dictionary # comprehension # Lists to represent keys and values keys = ['a', 'b', 'c', 'd', 'e'] values = [1, 2, 3, 4, 5] # but this line shows dict comprehension here myDict = {k: v for (k, v) in zip(keys, values)} # We can use below too # myDict = dict(zip(keys, values)) print(myDict...
553573a71ebbc15d14f2c81daed919574ccdf22c
AmanSingh1611/Sorting-Algos
/selectionsort.py
265
3.78125
4
def selection_sort(arr): for i in range(0,len(arr)-1): min_val = i for j in range(i+1,len(arr)): if arr[j]<arr[min_val]: min_val=j if min_val!=i: arr[min_val],arr[i]=arr[i],arr[min_val] arr=list(map(int,input().split())) print(selection_sort(arr))
b73a632a64b10f4e477b3cbcf06461e9ac5797a5
jan25/code_sorted
/leetcode/weekly162/1_odd_mat.py
474
3.734375
4
''' https://leetcode.com/contest/weekly-contest-162/problems/cells-with-odd-values-in-a-matrix/ ''' class Solution: def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int: rows, cols = [0] * n, [0] * m for a, b in indices: rows[a] += 1 cols[b] += 1 o = 0 ...
33e4c0c3c4630066151c46a3cab8b61b772f89cf
zadoev/codeeval
/solutions/prime_palindrome/main.py3.py
1,048
3.828125
4
__author__ = 'zadoev@gmail.com' def primes(n): """ http://habrahabr.ru/post/122538/ 4x faster then used in prime_palindrome :param n: :type n: :return: :rtype: """ lst = [2] for i in range(3, n+1, 2): if (i > 10) and (i % 10 == 5): continue for j in ...
ea14d44fc0fbe6e62998dfe08f442f051de0e4be
curellich/guias
/guia000/guia000-ej1.py
1,330
4.21875
4
''' 1. Escribir una función que reciba como parámetros el inicio y fin (inclusive) de un rango numérico. La función debe: a. Imprimir en pantalla todos aquellos números que sean divisibles por 7 pero no sean divisibles por 5. b. Imprimir el mismo resultado anterior, pero separados por coma. Resultado Esperado: Por ejem...
ccc3efcf920a91eb42d7337a2eaffa2741d2e846
l4uro/lenguajesyautomatasU3
/Ejerc9_globales.py
338
3.953125
4
#-*- coding: utf-8 -*- import aritmetica a = int (input("ingrese un numero: ")) b = int (input("ingrese un numero: ")) print ("La suma es: ", aritmetica.suma(a,b)) print ("La resta es: ", aritmetica.resta(a,b)) print ("La multiplicacion es: ", aritmetica.multiplicar(a,b)) print ("La divicion es: ", aritmetic...