blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
26fca762efec8e7a6dddcc2269dcb4c8bb681924
Llontop-Atencio08/t07_Llontop.Rufasto
/Rufasto_Torres/Bucles.IteracionRango.py
608
3.515625
4
#Ejercicio01 s=0 n=50 for n in range (103): if((n+2)==0): n+=2 #fin_if #fin_for print("serie:",n) #Ejercicio02 s=0 for i in range (60): if((i % 2 )==0): s=s+i #fin_if #fin_for print("Suma:",s) #Ejercicio03 i=0 for i in range(80): if((i%2)==0): i+=2 print(i) #f...
b15ab1d0f8c05d8833825cbd27b4f55f07065750
kjsk22/NumPyIndexSliceDemo
/NumpySlicingIndexing.py
1,159
3.609375
4
import numpy as np #create numpy array a = np.arange(9) a #get the element from array with index 5 a[5] #get elements from 0 to 4 a[0:5] #get last but one element a[-2] #get elements from 6 to 8 xy = a[6:9] xy #reshape the array to 3 by 3 a = np.arange(9).reshape(3,3) a #get element with ind...
c22dee0cd021b27ddf4b4d962e16dbc1508713b4
dancaps/python_playground
/wk2_a1.py
1,725
4.5625
5
#!/usr/bin/env python3 def is_even(n): """Function to test if a number (n) is an even or odd number Args: n (int) Returns: bool: Returns True if the number is even or False if it's odd. """ if n%2 == 0: return True else: return False def is_prime(n): """...
de60d11a37afccb89ccd95cb2f7612bb114194d9
ParsaYadollahi/leetcode
/one_away.py
582
3.59375
4
''' CTCI question 1.5 ''' def one_away(s1, s2): if len(s1) - len(s2) > 1: return False diff = 1 i = j = 0 while(i < len(s1) and j < len(s2)): if s1[i] != s2[j]: diff -= 1 if len(s1) > len(s2): i += 1 elif len(s1) < len(s2): ...
1dfb915efd6b973b8b8e7d0269116389d91d00ee
fukubaka0825/python-algorithm
/big_o_notation/main.py
530
3.578125
4
# O(long(n)) def func2(n): if n <= 1: return else: print(n) func2(n/2) # O(n) def func3(numbers): for num in numbers: print(num) # O(n * log(n)) def func4(n): for i in range(int(n)): print(i,end=" ") print() if n <= 1: return func4(n/2) # O(...
a4bda18e209ea9f72db4e438eb571dab37bcb5ff
SantoshN7/Programmes
/python/modules/fibo.py
110
3.546875
4
def fib(n): a,b=0,1 list=[] while a < n: list.append(a) a,b=b,a+b return list
0fab1138d6c0ac0a925db6324f02c78933c02d0c
emmanuelmacharia/algorithms-and-data-structures
/arrayIntersection.py
752
3.875
4
class ArrayIntersection: '''returns an array with the common values in both arrays. intersections for the two arrays are defined by the values that are common in both arrays''' def arrayIntersection(self, arr1, arr2): # turn both arrays into sets set1, set2 = set(arr1), set(arr2) ...
af676ce05150b718ac4608040cfd77ce8b73160f
Daggerpov/ICS3U-Python
/coding_problems/test.py
857
3.71875
4
'''aList = ['Mon', 'Tue', 'Wed', 'Thur', 'Fri'] for i in range(len(aList)): print(str(i+1)+'.', aList[i])''' '''x = 4 print(x==4) x += 3 print(x==4) print(x>=4) print(x)''' '''x, y = 10, 3 print("The answers are:", end=' ') print(x//y, x%y, x**y, x>y)''' '''myList = list(range(1, 10, 2)) print(myList)''' '''num = 1...
453e682ae38f15c3d54ae72b9b68fa49815f8be9
DjalmaJunior/CursoemVideo-Python-Desafios
/Desafios-Mundo1/Desafio08(Aula07).py
254
4
4
#Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. m = float(input('Digite um número:')) c = m*100 mm = m*1000 print('{0} metros em:\ncentímetros: {1:.0f}cm;\nMilímetros: {2:.0f}mm.'.format(m, c, mm))
053dccba376a2cdf9ac32ff8b2ab957779761ff6
daidaros08/LearningPython
/ActividadesLibro.py
6,461
4.21875
4
#Escribe un programa que use INPUT para pedirle al usuario su nombre y luego darle labienvenida nombre= input('ingrese su nombre: ') print (f'Bienvenido {nombre}!!!') #Escribe un prorama para pedirle alusuario el numero de horas y la tarifa por horas para calcular el salario bruto tarifaHora= int(input('Ingrese su ...
7eb842a855c8920d383cf0df5c08a29544a1ef4e
ibrahimkaratas88/devops_works
/python-code-challenge/password/password.py
1,093
3.859375
4
def print_menu(): print("Welcome to the password application") print("1. Show password list") print("2. Insert password") print("3. Find a password") print("4. Terminate") print("Select operation on Password App (1/2/3/4) :", '\n') print() sifreler=open('sifreler.txt','a+') sifreler.seek(0)...
b4b999ef12bab60a0019eda7f63b275e9d7fd3ad
omstokke/rulesOfClassAndInheritance
/personSimulation.py
2,086
3.640625
4
from personClasses import * def onboarding(list): print(""" Welcome! What follows is a short simulation, enabling you to catch up on the current status of humanity.""") list.append(input(""" What is the name of our subject today? """)) list.append(input(""" ...
1aa599ad19ccfa7f22194be501b3ed2b0674685c
ivorymood/TIL
/Python_200Q/051_/Q052.py
386
3.75
4
class MyClass: # 클래스 생성자 def __init__(self, *args): self.var = '안녕하세요' print('MyClass 인스턴스 객체가 생성되었습니다') class MyClass2: def __init__(self, text): self.var = text print('생성 인자로 전달받은 값은 <'+self.var+'>입니다') obj = MyClass() print(obj.var) obj2 = MyClass2('철수')
fbf4ebee75de3e235dad631e9184311b26205ca5
jahirulislammolla/CodeFights
/InterviewPractice/Arrays/isCryptSolution.py
278
3.53125
4
def isCryptSolution(crypt, solution): a,b={},[] for x,y in solution: a[x]=y for i in crypt: c='' for j in i: c+=a[j] if c[0]=="0" and len(c)>1: return 0 b+=[c] return int(b[0])+int(b[1])==int(b[2])
dea12deefa98bb130a997728c57ee186bdec472d
Jeffrey-A/Data_structures_and_algorithms_Programs
/HW4/HW4_Jeffrey/HW4_Jeffrey/HW4/1_CardGame/Player.py
958
3.859375
4
#Jeffrey almanzar from Deck import Deck class Player(object): """"Contains all the action that a player can make and keep track of the number of cards the player have in the pile.""" def __init__(self,deck): """pre: deck is an object of type Deck""" self.player_pile = [] sel...
8bf9dbc9d539c25edb8cced4c12b7b35434d528f
guiprestes/IMC_Calculator
/Calculadora IMC.py
492
3.96875
4
print('Calculadora IMC') weight = float (input('Insira o peso (kg): ')) height = float (input('Insira a altura (m): ')) imc = weight/(height ** 2) print('IMC = {:.1f}'.format(imc)) if imc < 18.5: print('Abaixo do Peso') elif 18.6 <= imc < 24.9: print('Peso Normal') elif 25 <= imc < 29.9: print('...
590d5ad63a0fcf7f0f27a6352051093acfc9923c
nbenkler/CS110_Intro_CS
/Lab 3/functions.py
1,026
4.4375
4
'''function.py Blake Howald 9/19/17, modified for Python 3 from original by Jeff Ondich, 25 September 2009 A very brief example of how functions interact with their callers via parameters and return values. Before you run this program, try to predict exactly what output will appear, and in what order....
4a8eda62f47b0e388f9366a72396e219e8b83605
je-castelan/Algorithms_Python
/Python_50_questions/13 Graphs/djikstra.py
2,277
3.8125
4
import collections import heapq class Solution: def networkDelayTime(self, times, N, K): """ times is a list of sublist. Every sublist has A, B, C. A is origin, B is destination and C is time distance N is count of nodes K is initial node """ # First, ...
1072ee53170ff5141d1e1e99f6b182506036c0b0
mmmacedo/python
/Capitulo 1/3 - operacoes.py
357
3.84375
4
# -*- coding: utf-8 -*- soma = 1 + 1 subtracao = 1 - 1 multiplicacao = 2 * 2 divisao = 5 / 2 modulo = 5 % 2 pFlutuante = 0.5 print ("Soma 1+1 =", soma) print ("Subtração 1-1 =", subtracao) print ("Multiplicação 2*2 =", multiplicacao) print ("Divisão 5/2 =", divisao) print ("Módulo 5%2 =", modulo) print ("...
e95857530ab714aad12cb908a3d494d861cb4064
altuhov-as/geekbrains-python-start-homework
/lesson_8/task_1.py
1,007
3.78125
4
import time class Date: def __init__(self, line: str): self.validate_numbers(Date.get_numeric(line)) @classmethod def get_numeric(cls, line_date: str): return list(map(int, line_date.split("-"))) @staticmethod def validate_numbers(numbers: list): # d, m, y = numbers ...
57976ebd31d814dbd1a7f414adf93ed95fc4bb79
lujamaharjan/IWAssignmentPython1
/DataType/Question20.py
407
3.90625
4
""" 20.​ Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. Sample List : ['abc', 'xyz', 'aba', '1221'] Expected Result : 2 """ sample_list = ['abc', 'xyz', 'aba', '1221'] counter = 0 for word in sa...
cddc3086d9c0d8730f086479f233de795ecdeeb8
mleue/min
/min/cli/io_ops.py
2,503
3.71875
4
import os from pydoc import pager from .config import DOCS_PATH def get_filenames(path): """Read the filenames in a dir and yield them. Arguments path -- the path to read filenames from Returns filenames -- list of filename strings (without hidden files) """ for f in os.listdir(path): if not ...
87c0f29dabcf80454fd9b1630fc02b8404da81e6
liusong-cn/python
/Encapsulation.py
391
3.890625
4
class Encapsulation: def __hide(self): print("示例的隐藏方法") def getname(self): return self.__name def setname(self,name): if len(name)<3 or len(name)>8: raise ValueError("长度不在范围内") self.__name = name name=property(getname,setname) e = Encapsulation() #e.name = "h...
28da3778d372d93cabc03e07bcdfb2a87c8e17e9
MikeyPPPPPPPP/Odd_text_game
/game/attacking.py
1,034
3.75
4
import random class attack: def __init__(self,player,monster): self.you = player self.mons = monster def start(self): print('\n') self.mons.mhit(self.you) if self.you.health >= 0: if random.randint(0, 1) == '1': self.mons....
76eab577692fe7129e04e80aeadc1397b82b48de
markbiek/r-dailyprogramming
/149-disemvoweler.py
756
3.734375
4
#!/usr/bin/python import re def disemvowel(s): v = re.sub(r'[^aeiou]', '', s) nonv = re.sub(r'[aeiou ]', '', s) print nonv print v print "" def disemvowel2(s): v = [ c for c in s if c in 'aeiou' ] nonv = [ c for c in s if not c in 'aeiou ' ] print "".join(nonv) print "".join(v) ...
33c62a45327ebf74beb9b1128d06185ed47678ad
soderdrew/Encoder-Decoder
/min_pq_tests.py
1,076
3.546875
4
import unittest from min_pq import * class MyTestCase(unittest.TestCase): def test_pq(self): pq = MinPQ([3, 10, 231, 5]) self.assertEqual(pq.is_empty(), False) self.assertEqual(pq.size(), 4) self.assertEqual(pq.capacity, 4) self.assertEqual(pq.min(), 3) s...
34de0e04969da931d3c4d0fb8d7c5117e2f61796
macnc/PythonL
/TreeHouse/Practice/number_game.py
1,217
4.125
4
#! /usr/bin/python # _*_coding: utf-8 import random def game(): # generate a radom number between 1 and 10 secret_num = random.randint(1, 10) guesses = [] # limit guesses while len(guesses) < 5: try: # get a number guess from play # safely make an int ...
7d8b7b78a84997192800871bf5208a4ddfc78b3e
ALCLynch/LearningToCode
/guessthenumber.py
503
3.765625
4
import random def main(): number_to_guess = get_random_number() user_input = get_user_input() while user_input != number_to_guess: print('guess again') user_input = get_user_input() print('you win') def get_user_input(): try: return int(input('Enter a number: ')) exc...
cb300ae5744e1633a99beedf66437acb6d2d3e14
ravee-interview/DataStructures
/Week5/Binary_Search/278_first_bad_version.py
823
3.765625
4
# The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): class Solution(object): def firstBadVersion(self, n): """ :type n: int :rtype: int """ #find the mid version #if it's a bad version log it as...
08ea9a137a093607dc0229ba0ad0e4316ac2fcb1
anitrajpurohit28/PythonPractice
/python_practice/Basic_programs/1_add_two_numbers.py
186
3.96875
4
# 1 Python program to add two numbers num1 = input("First number: ") num2 = input("Second numbrer: ") result = float(num1) + float(num2) print(f"sum of {num1} and {num2} is {result}")
f9621c14cbae39bce6478619b8a07472ffaa752c
MoSedky/Auto_Approval_Validator
/Auto_Approval_results.py
6,595
3.75
4
def pre_condition(): converted_firm = input("Are there Converted Firms ? ") foreign_partners = input("Are there foreign partners ? ") gulf_partners = input("Are there gulf partners ? ") saudi_minor_partners = input("Are there saudi minor partners ? ") saudi_disable_partners = input("Are there saudi ...
debe71f54394e57780757333e7cccf607dd3f15d
leobloise/desafios_code_war
/playing_with_digits/index.py
464
3.59375
4
def split_number(number): return int(number) def convert_to_tuple(n): return tuple(map(split_number,list(str(n)))) def couldBeInt(number): import re return bool(re.search('\.0$', str(number))) def dig_pow(n, p): digits = convert_to_tuple(n) x = 0 for digit in digits: ...
1424749f136d7045d4d63ed477d133718af9b66d
tezrivera10/Python-Code-Samples-1
/squareshape.py
518
3.796875
4
#Raul Rivera #2/28/19 #Drawing an square over squares using turtle import turtle def drawSquare(b,ft): for i in range (4): b.forward(ft) b.left(90) wn = turtle.Screen() bobby = turtle.Turtle() bobby.color ("green") size = [20,40,60,80,100] for x in size: ...
2a2db9e33aa336c89d089f248e88fab8eed8b0fa
coltonjcox30/cs1410
/bank_account/checking_account.py
433
3.515625
4
from account import Account class CheckingAccount(Account): def __init__(self,acc_name,acc_num,start_b,od): Account.__init__(self,acc_name,acc_num,start_b) self.od = od def deposit_Money(self,value): if value >= 0: self.start_b += value return def withdrawl_Money(self,value): OD = self.od + self.st...
21641cdab0df67e1b6c0cade39e9b95a063476bd
muran001/nlp100
/05.py
261
3.5625
4
#! /user/bin/env python # _*_ coding: utf-8 _*_ import re s='I am an NLPer' def ngram(n,x,d): return [d.join(x[i:i+n]).strip(' ') for i in range(len(x)-1)] print(ngram(2, list(s), '')) print(ngram(2, [t.strip('.') for t in re.split('[\s,]+', s)], '-'))
f985fbc04e830767d1f009dde1f05b5da8a29f78
yami-five/programming-challenge
/04_Encryption_decryption.py
451
3.78125
4
#from random import randint alphabet="abcdefghijklmnopqrstuwvxyz" cipher="lsavwipezjyrgdtqocnxuhkfbm" str1=input("Write password: ") str2="" for x in range(0,len(str1)): if str1[x]==' ': str2+=' ' else: str2+=cipher[alphabet.index(str1[x])] print("Encryption: ",str2) str1="" for x in range(0,len...
6228843825818ed124a5474210554c3a7db9b3c9
DrChrisLevy/python_intro_udemy
/book/_build/jupyter_execute/content/chapter6/practice_questions_solutions.py
4,401
4.53125
5
#!/usr/bin/env python # coding: utf-8 # # Practice Questions (Solutions) # ## 1. # For each of the following `if` statements, determine what will be printed. # In[1]: x = 0 if x: print(1) else: print(2) # In[2]: y = [0] if y: print(1) else: print(2) # In[3]: if 1 and 0: print(1) else: ...
e25be547832304a87b67a1cedcd818f953a19ab6
VartikaPandey1303/Python-Quiz
/myquiz.py
6,159
3.6875
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 7 01:17:14 2019 @author: user """ from tkinter import * from tqq import * root = Tk() root.configure(bg="white") root.geometry('1000x600') #WIDGETS FOR INTRO PAGE name_label = Label(root, text="NAME: ", bg = "white", fg = "black",anchor = CENTER, heig...
e0ff6b8d0ebfcb1351883ca0dd0679134f28f748
harithaasheesh/mypythonrepo
/flow_of_controls/looping/whileloop.py
138
3.84375
4
#while(condition): # body of loop #incr/decr a=0 while a<=10: print("hello") a+=1 # i=10 # while i>0: # print(i) # i-=1
0b5b9c06f739a8dbd5238eb4babf026fee2069fb
shobhit-bhatt-14/Getting-Started-with-Python
/python-bool.py
195
3.53125
4
a = bool('True') b = bool('False') c = bool('') d = bool(' ') e = bool('hello') f = bool(0) g = bool(1) h = bool('1') print(a,b,c,d,e,f,g,h,sep=' ') #auto bool print(1>3) print(1==2) print(3>0)
ac3c095dce32bd3ab31af6e307cf97f70c967b63
MaisenRv/EjerciciosCiclo1
/OOP/clase_persona.py
456
3.53125
4
class Persona: def __init__(self,nombre,edad, *varios, **d): self.nombre = nombre self.edad = edad self.valores = varios self.diccionario = d def desplegar(self): print("Nombre:",self.nombre) print("Edad:",self.edad) print("Valores (tupla):",self.va...
cf8ae2df53c5f82a3a4a201308b348ca8b41f79e
MidD3Vil/jokenpo.py
/main.py
2,219
3.6875
4
from random import randint from time import sleep from emoji import emojize jogar = 'S' jogador_vence = comp_vence = empate = 0 while jogar == 'S': pedra = emojize('Pedra :fist:', use_aliases=True) papel = emojize('Papel :hand:', use_aliases=True) tesoura = emojize('Tesoura :v:', use_aliases=True) opc...
ba686f89c58dd3030b55261df6aa109dae760279
v4nz666/MineClimbeR-L-
/RoguePy/Input/KeyboardHandler.py
662
3.5
4
from InputHandler import InputHandler class KeyboardHandler(InputHandler) : def __init__(self): self.keyInputs = {} self.key = None def _addKeyInputs(self, inputs): for i in inputs: self.keyInputs[i] = inputs[i] def setInputs(self, inputs): self.keyInputs = {} self._addKeyInputs(inpu...
1c27133bf4e93533345c50751e85b76831886c31
iamsaptorshe07/Python-Cheat-Codes
/Numpy Array Slicing.py
246
4.15625
4
import numpy as np arr1 = np.array([1,2,3,4,5,6,7,8,9,10]) print(arr1) print(arr1[0:5]) print(arr1.size) print(arr1[::-1]) #Copying a Array arr2 = arr1[5:].copy() print(arr2) #Reverse an Array arr3 = arr1[::-1].copy() print(arr3)
ac9a9c456bb4755ec42a1b7eabc78f3626ff437d
VladBaryliuk/my_trainings
/topics/topic_2/15_elecric_clocks2.py
218
3.734375
4
def electric_clocks(seconds): hours = seconds // 3600 seconds -= hours * 3600 minutes = seconds // 60 seconds -= minutes * 60 print(hours, minutes, seconds, sep=":") electric_clocks(int(input()))
79838cf30d04080e98551a0126655f914b599458
sentairanger/Linus-Google-AIY-Robot
/motor_button.py
589
3.71875
4
#!/usr/bin/env python3 #import libraries from gpiozero import Motor from aiy.board import Board from aiy.pins import (PIN_A, PIN_B) #Define the motor motor = Motor(forward = PIN_A, backward = PIN_B) #When the button is pressed the motor turns on. When it is released the motor turns off def main(): print('Press bu...
6376e26ea3627062676ad31466a4cda4cff756a2
adamzvx/ds9
/kelas-terbukaa/OOP/4 method.py
955
3.59375
4
# class/ templaate di deklarassikan sebelum program class Hero: # variabel class jumlahHero = 0 def __init__(self, inputNama, inputHealth, inputPower, inputArmor): self.nama = inputNama self.health = inputHealth self.power = inputPower self.armor = inputArmor Hero.ju...
93f316716f3680bcfc5338ebf0ca085fcf17520c
llwsykll/JianzhiOffer
/剑指Offer/矩阵覆盖/coverRECT.PY
303
3.78125
4
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here if number<3: return number res = [0] * (number+1) res[0],res[1],res[2] = 0,1,2 for i in range(3,number+1): res[i] = res[i-1]+ res[i-2] return res[number]
6f963072b59a1457beea06568c09fef7e45a3de6
JRLee0085/ichw
/pyassign3/tile.py
7,347
3.71875
4
#!/usr/bin/env python # coding: utf-8 # In[6]: def createlist1(m,n): list1=[["empty" for i in range(int(m))] for i in range(int(n))] return list1 #构建了一个二维的列表代表要铺砖的空间,empty代表未被铺,occupied代表被铺上 def findempty(n,list1): listfind=[] for i in range(n): if "empty" in list1[i]: listfind.a...
e16ca442c2ae9a0eb0adfd39764bdd37c6fc682d
Vinod096/learn-python
/lesson_02/personal/chapter_3/02_rectangle.py
956
4.40625
4
#The area of a rectangle is the rectangle’s length times its width. Write a program that asks #for the length and width of two rectangles. The program should tell the user which rectangle #has the greater area, or if the areas are the same. length_of_rectangle_1 = int(input("Enter a number : ")) width_of_rectangle_1 =...
7dd37c4703c7fbf47d91e489481491602aa71f94
mcfey/Conway-Life
/conway.py
2,148
3.75
4
""" conway.py Author: Mary Feyrer Credit: Tess Snyder, Mr. Dennison Assignment: Write and submit a program that plays Conway's Game of Life, per https://github.com/HHS-IntroProgramming/Conway-Life """ from ggame import App, RectangleAsset from ggame import LineStyle, Color, Sprite, Sound white = Color(0xffffff, 1.0)...
b9976e206758fedb315d4c60e1bdb13473646c18
Naman-Garg-06/Lecture-Series-Python
/Awesome-Scripts/exponentiation.py
1,234
3.984375
4
from decimal import * from fractions import Fraction from math import floor def getExponent(flot, exponent): # We need to know all significant digits that we will likely encounter # to gurantee maximum precision # 1.5 + 1.55 = 3.55 the second one had two digits of precision so we need # 2 digits of pr...
d4a359a2663356c5f611ef4b2e684d351f0c9ee3
clemmyn23/Nuclear-Fox
/2_notes/python/pylist.py
123
3.59375
4
mylist = [] mylist = [1, 2, [3, 4], 4] print(mylist) print(id(mylist)) mylist.append(5) print(mylist) print(id(mylist))
a00efba8d1d8626a1bdc7742025e393a01647f71
chenxy3791/leetcode
/No0762-prime-number-of-set-bits-in-binary-representation.py
2,989
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 5 07:41:15 2022 @author: Dell """ def countOnes(num): # a = [int(c) for c in bin(num)[2:]] # return sum(a) cnt = 0 while num > 0: cnt += num & 1 num = num // 2 return cnt import time import random import itertools as it class Solutio...
2d677c44bf196f1737e01744d2cafe9693bad18d
nidzelskyy/coursera_python_course
/week2/15_generators.py
660
3.984375
4
def even_range(start, end): current = start while current < end: yield current current += 2 print(list(even_range(0,10))) def fibonacci(number): a = b = 1 for _ in range(number): yield a a, b = b, a + b print(list(fibonacci(20))) def accumulator(): total = 0 w...
7fbd88f198aa2364a465be5ac0dc5e3a8bd8c712
Howardw3/cs229-assignments
/machine-learning-ex1/ex1/computeCost.py
596
4
4
import numpy as np def compute_cost(X, y, theta): # Initialize some useful values m = y.size cost = 0 # ===================== Your Code Here ===================== # Instructions : Compute the cost of a particular choice of theta. # You should set the variable "cost" to the corr...
0f95e03dc6f9b56d89e8185154d3f4ffca3d1583
MoAfshar/AlgoDS
/Mo/Week_5/200-Number of Islands.py
2,854
3.84375
4
""" Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 0...
84cf14bbf81caacaae762fa7a6ef94ddc6c9015d
Adilbek97/Arduino_projects
/robot_proby/prob5/time.py
1,087
3.640625
4
from datetime import datetime as dt import pyttsx3; import datetime def currentTime(): month={1:"Январь",2:"Февраль",3:"Март",4:"Апрель",5:"Май",6:"Июнь",7:"Июль",8:"Август",9:"Сентябрь",10:"Октябрь",11:"Ноябрь",12:"Декабрь"} day={0:"Понедельник",1:"Вторник",2:"Вторник",3:"Среда",4:"Четверг",5:"Пятница",6:"Воск...
f7aeab6b56fe6b35285b60331f9cf8581196d353
NguyenVanDuc2022/Self-study
/101 Tasks/Task 017.py
810
3.875
4
""" Question 017 - Level 02 Write a program that computes the net amount of a bank based a transaction log from console input. The transaction log format is shown as following: D 100 W 200 D means deposit while W means withdrawal. Suppose the following input is supplied to the program: D 300 D 300 W 200 D 100 Then, th...
6ee9ae6b9ff319bdd90943d8be55f55d3c6dc5a2
jclane/beginner-project-solutions
/python/factors_of_a_number.py
711
3.90625
4
def factor(num): nums = [] for i in range(2, num + 1): if i == num: print("{} is a prime number.".format(num)) elif (num % i) == 0: break if num == 0: return nums if num > 0: for i in range(1, num + 1): if num % i...
d5e7576afbd4e3e86168b8efc96d60aca2e74ffc
coquelin77/PyProject
/leetcode/1两数之和.py
1,273
3.796875
4
'''给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]''' # class Solution(object): # def twoSum(self,nums,target): # for i in range(0,len(nums)-1):#从数组第一个元素遍历 # ...
7e5bd99749c605e85c54063611c0eff188e4fb13
Sibinvarghese/PythonPrograms
/flowcontrols/looping/continue prgm.py
146
3.53125
4
num1=int(input("enter the low limit")) num2=int(input("enter the upp limit")) for i in range(num1,num2): if(i==24): continue print(i)
63e48859d9f62ebcd5c8c73a4cadf6ea449aa4f9
diegoasanch/Fundamentos-de-Progra-2019
/TP4 Estructura iterativa/Repaso parcial 1/ej 2.py
381
4.03125
4
print('Ingresar numeros y ver por pantalla el primero y ultimo ingresados, finaliza con -1') n=int(input('Ingrese un numero: ')) if n!=-1: primer=n ultimo=n while n!=-1: ultimo=n n=int(input('Ingrese un numero: ')) print() print('El primer numero ingresado fue',primer) print('Y e...
194f669737491eb682bbc99b3cc640fcb4fb1b71
Ekeopara-Praise/python-challenge-solutions
/Ekeopara_Praise/Phase 2/TUPLE/Day 53 Tasks/Task7.py
166
4.4375
4
'''7. Write a Python program to unzip a list of tuples into individual lists.''' zipped = [('a', 1), ('b', 2)] unzipped_obj = list(zip(*zipped)) print(unzipped_obj)
791a5187c9d68539dd43b32a49332840b861b3dc
daniel-reich/turbo-robot
/rQkriLJBc9CbfRbJb_8.py
708
4.40625
4
""" Create a function that takes a single string as argument and returns an ordered list containing the indices of all capital letters in the string. ### Examples index_of_caps("eDaBiT") ➞ [1, 3, 5] index_of_caps("eQuINoX") ➞ [1, 3, 4, 6] index_of_caps("determine") ➞ [] index_of_caps...
0ea492a1715c9885b03173ee86ff4631d2851883
Josh-Amos/wb272
/Tests/assignment5/richter.py
410
3.796875
4
def category(mag): """A function that returns the category of the earthquake related to the magnitude""" magn = "{0:.1f}".format(mag) f = float(magn) if f < 3.0: return "micro" if 3.0 <= f <= 3.9: return "minor" if 4.0 <= f <= 4.9: return "light" if 5.0 <= f <= 5.9: return "moderate" if 6.0 <= f <= 6....
b56d1c701caa3e358c5082220bb910aaf1e5a471
yusokk/algorithm
/extra/pro-비밀지도.py
372
3.828125
4
n = 5 arr1 = [9, 20, 28, 18, 11] arr2 = [30, 1, 21, 17, 28] def solution(n, arr1, arr2): answer = [] for i in range(n): temp_str = "" for j in range(n-1, -1, -1): temp = arr1[i] & (1<<j) | arr2[i] & (1<<j) temp_str += "#" if temp == (1<<j) else " " answer.append(...
d4f0e3f31027e9fb1ba45be71a08c3c62ace59df
mlsteele/integrator
/sublogger.py
523
3.84375
4
""" SubLogger """ class SubLogger(object): """ The SubLogger class keeps a record of messages. It organizes them hierarchically to preserve the notion of sub-problems. It is used by the solver to record the steps while solving a problem. """ def __init__(self, title="root"): self.title = title ...
f41870ed472af13be19228707ec2658e4ec40504
John-Jordan/Paper_Rock_Scissors
/main.py
1,417
4.28125
4
import random print('Let\'s play Rock, Paper, Scissors') options = ('rock', 'paper', 'scissors') def ai_choice(): rand_choice = random.choice(options) return rand_choice my_score = 0 AI_score = 0 pick = () while pick != 'exit': print('Choose "r" for rock, "p" for paper, or "s" for scissors. Type "exit" to en...
9290a9efb668e753917930da776f4f39fb75e4ab
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/smyjas002/question2.py
1,005
3.6875
4
#Jason Smythe #CSC 1015 #SMYJAS002 #assignment 6 #question 2 import math def vecAddition(a, b): strFormat = "[" x = [] for i in range(len(a)): x.append(a[i] + b[i]) strFormat += str(x[i]) + ", " strFormat = strFormat[:-2] +"]" return strFormat def dotProduct(a, b): dot = 0 for i in range(len(a)): dot += ...
3a4a164b870b419e4f3a692e886a9e348b8a8e3d
mjh09/python-code-practice
/arrayMaxContiguousSum.py
647
3.5625
4
def arrayMaxConsecutiveSum(inputArray, k): """ Sums and returns largest value of contiguous subsets in an array. Parameters: inputArray (array) : array of integers k (int) : length of subset Returns: result (int) : largest sum of subset """ if k == 1...
110b3670b19ca02d7415d5ad0106341ea4eb5c70
YuyaKagawa/atcoder
/special/エイシングプログラミングコンテスト2020/C_XYZTriplets.py
466
3.59375
4
##### 解けた、解説見た from math import sqrt N=int(input()) # 整数 C=[0]*(N+1) # カウントのリスト l=int(sqrt(N)) # せいぜいこの範囲 for x in range(1,l+1): for y in range(1,l+1): for z in range(1,l+1): s=x**2+y**2+z**2+x*y+y*z+z*x # 合計 if s<N+1: # もしありえるなら C[s]+=1 # カウントをインクリメント for n in ra...
397e7c527ae875b374c1acd4c1831a2d9f690fb1
tthtlc/sansagraphics
/hilbert2d.py
1,479
3.859375
4
#!python3 ### https://sites.google.com/site/algorithms2013/home/python-turtle-graphics # space filling hilbert curve in python 3 # adapted from http://www.fundza.com/algorithmic/space_filling/hilbert/basics/index.html import sys, math, time import turtle count = 0 def moveto(x,y): turtle.penup() turtle.goto(x...
f6ed8dd01ae12e5c65164ba460dfefdc5e9f002d
Julymusso/IFES
/2_PROGII/00_exercicios_05.py
91
3.53125
4
def divisores(k): for i in range (1,k+1): if k % i == 0: print (i)
0627633ae183f78a152e40c49b14d63a2a5db991
lryong/Algorithm-exercise
/jianzhioffer/python/reorder_array.py
583
3.96875
4
i#!/usr/vin/env python # -*- coding:utf-8 -*- # 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。 # My Solution class Solution: def reOrderArray(self, array): odd_list = [] even_list = [] for i in array: if i%2: odd_list.append...
9d68b7357c3d0aa1a2d1756d08d17b03a500f293
avnitsharma/data-anlysis-with-panda
/pulling data from yahoo.py
444
3.578125
4
from pandas_datareader import data, wb import datetime #using this in order to pull data from internet import pandas_datareader.data as web #creating start and end variable. we would need data between these dates start = datetime.datetime(2010,1, 1) end = datetime.datetime(2015, 8, 22) #metion the symbol of which you ...
794b76f8ed2a39268d8172e0ffc5e130fca65fdf
jibowers/lucas_series
/lucas-series_1.py
241
3.890625
4
##Lucas series generator a = int(input("First term: ")) b = int(input("Second term (larger than first term): ")) t = int(input("Number of terms to display: ")) - 2 i = 0 print (a, b) while i < t: c = a+b print (c) a, b = b, c i += 1
cc456e608e3435fb0f8172ed76d9db21a6069f00
xavierliang-XL/git-geek
/geekprogramming/practices/listpractice.py
537
4.15625
4
import random def generateRand(size,bound): """ this method is to generate a random list size:the length of the list bound:range of the random number """ list=[] for i in range(size): list.append(random.randint(0,bound)) print(list) return list def Min(list): """ th...
c33741d3d3cf4c0e13a584284dfd9f97a27c252d
EgbertGao/HelloWorld
/Learning/Test/Chapter8.py
1,682
3.984375
4
''' #8-1 打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。 def display_message(self): print('我在本章学的是{}!'.format(self)) display_message('函数') #8-2 def favorite_book(title): print('One of my favorite books is {}.'.format(title)) favorite_book('Alice in Wonderland') #8-3 def make_shirt(size, type): print('This T-shi...
0f761af8772ac7154ea4637be384f0f70cdf38a8
algometrix/LeetCode
/Assessments/SAP/Python Debugging.py
119
3.796875
4
N = input("enter : ") N = int(N) arr = [ val**2 for val in range(N) ] print('Square upto {} are:'.format(N)) print(arr)
7c26886ff26143b778e8c8ce382590005f43b52a
Xinghua-TAO/AutoViDevSpeech
/SpeechRecognition_Sphinx.py
1,192
3.953125
4
# use the package speech_recognition import speech_recognition as sr # define the function and the parameter audio_input means the path of the audio # and the txt_output means the path and the name of your output file def recognize_speech_s(audio_input,txt_output): r = sr.Recognizer() beginner = sr.Au...
82c9b1e02abd948cb9d4c9b396b2bedc1e060a74
NataliiaBidak/py-training-hw
/Homework4/dict_task8.py
533
3.984375
4
""" Write a Python program to find the list in a list of lists whose sum of elements is the highest. Sample lists: [1,2,3], [4,5,6], [10,11,12], [7,8,9] Expected Output: [10, 11, 12] """ def highest_sum(lst: list): summ = 0 for index,list1 in enumerate(lst): if sum(list1) > summ: summ = sum...
db52432a785a8bfab4e664c386d73d753f77bd64
hciudad/Advent-of-Code
/Day01.py
488
3.546875
4
#! /usr/bin/env python # Day 1: Not Quite Lisp # http://adventofcode.com/day/1 with open('input/Day01.txt') as f: data = f.read() # Part 1 print 'You end up on floor {}'.format( reduce(lambda x, i: x + 1 if i == '(' else x - 1, data, 0)) # Part 2 floor = 0 for iteration, instruction in enumerate(data, star...
2f8b00926601bd6a1f66944b0546bd2b4dec795e
reshmaladi/Python
/1.Class/PracticeInClass/class10/swap2.py
1,556
3.71875
4
#!C:\Python34 def swapbits(x,y,posx,posy, bits): print (" original x ", '{0:08b}'.format(x), end = "\n") print (" original y ", '{0:08b}'.format(y), end = "\n") #print mask for x x_mask=(1<<bits)-1 print (" mask ", '{0:08b}'.format(x_mask), end = "\n") x_mask=x_mask<<(posx-bits) print (" mask after bits sh...
f866e7faa043ee29e02086361033780aad0b8ca8
kevinelong/PM_2015_SUMMER
/StudentWork/JayMattingly/PMSchoolWork/Code_challenges/python_files/vendingmachine.py
3,608
3.734375
4
import time import webbrowser class Vending_machine(object): def __init__(self, soda=1.50, chips=1.10, candy=0.75, giftcard=5.00): #gives item selection and prices belonging to each self.selection_02 = soda #class starts with $5.00 in giftcard balance ...
3cac69a38adf359d7e9ea6c5ae85c51355b726df
oangel26/holbertonschool-higher_level_programming-1
/0x0A-python-inheritance/1-my_list.py
290
3.625
4
#!/usr/bin/python3 """ classes MyList """ class MyList(list): """ class MyList """ def print_sorted(self): """ this function copy list and print sorted values Args: self: Mylist """ print(sorted(self))
0d30d9c526e5a228e872a5baf398d7b95eb8e770
nixis-institute/practice
/python/days.py
362
4.125
4
d = input("enter day number ") day = int(d) if(day==1): print("monday") elif(day==2): print("tuesday") elif(day==3): print("wednesday") elif(day==4): print("thursday") elif(day==5): print("Friday") elif(day == 6): print("saturday") elif(day==7): print("sunday") else: ...
262ab7898832db0d0ad11aeb62bfc8dab1d7fcf0
NicolasQueiroga/Proj-1a-tecweb
/db/database.py
1,159
3.9375
4
import sqlite3 class Note: def __init__(self, id=None, title=None, content=''): self.id = id self.title = title self.content = content class Database: def __init__(self, db_name): self.conn = sqlite3.connect('db/' + db_name + '.db') self.conn.execute('CREATE TABLE IF N...
cabf37886ef1bf5b2537a0aca3cc147b59a8018a
cafenoctua/100knock2019
/yoshimura/chapter01/knock03.py
182
3.53125
4
s = "Now I need a drink, alcoholic of course, \ after the heavy lectures involving quantum mechanics." print([w[0] for w in s.split()]) # str.split() # リスト内包表記
6d454380bf1f1e67441e437e7f73f1c2b65aad2b
ByEug/PythonLab1
/PycharmProjects/lab1/task4.py
1,441
3.640625
4
import sys import argparse def create_parser(): _parser = argparse.ArgumentParser() _parser.add_argument('name', type=open) return _parser def merge_sort(numbers): if len(numbers) > 1: center_number = len(numbers) // 2 left_part = numbers[:center_number] right_part = numbers[...
6971476c02b049bf6be57f54cb7465815e99588c
nju04zq/algorithm_code
/medium/133_Clone_Graph/clone.py
2,534
3.5
4
class UndirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] class Solution: def get_node(self, val, tbl): if val in tbl: return tbl[val] else: node = UndirectedGraphNode(val) tbl[val] = node return node ...
2ed326e11aaf31933054da65b42906b7cae27ac2
JairBernal/Practica_de-_Python
/list.py
284
4.03125
4
#Metodos -> Listas List = [1, 2, 3, 4, 5] list_2 = [6,7,8,9] print(f"La lista posee {len(list)} elementos") list.append (6) list.insert (2, 3) list.extend([6, 7, 8]) list_3 = List + list_2 list.pop(3) list.remove(1) list.clear() list.reverse() list.sort(reverse = True) print (list)
6ae53e256d99c7dff75fa6cdb7d3183d64db776b
phani-1995/week2
/datastructures1/lists/common.py
235
3.703125
4
def common_lst(lst1,lst2): for i in lst1: for j in lst2: if (i==j): print(i,end="") lst1=["apple",3,4,7,6,8,"Pine apple",9,10,12] lst2=["orange",4,6,8,7,"Grapes",13,"apple"] common_lst(lst1,lst2)
8dcf6ad38dfac0bebb55f0fc2f7206968090982f
Balaji751/Must-Do-Coding
/Helloworld/largeusefun.py
112
3.890625
4
def find_max(lis): maxi=lis[0] for i in lis: if i>maxi: maxi=i print(maxi) find_max([1,4,3,2])
500747039389e2fa5812739364f381aac308c21c
ilpizzo84/tartu
/plots/plots.py
2,462
3.59375
4
from os import path from collections import Counter from wordcloud import WordCloud from scipy.misc import imread import matplotlib.pyplot as plt import numpy as np class Plots: """ A simple plot library for token or tag lists. Available methods: - word_cloud: plot a word cloud of input tokens/tags, e...
eae863583ef19653fabe9b0f20c3ba37dec3a4d0
tinyliewang/Python
/1.py
522
4.15625
4
#根据给定的年月日以数字形式打印出日期 months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] day_th = ['st','nd','rd']+17*['th']+['st','nd','rd']+7*['th']+['st'] year = input("year:") month = input("month:"...
a599d331ea73c192c11b03294b805e89d4976e85
DS-17/Intro_to_Python
/assignment_answers/A01_hello_world.py
267
4.25
4
""" Assignment 1 Write a short script that will get some information from the user, reformat the information and print it back to the terminal. """ # Possible Answer fav_movie = input("What is your favorite movie? ") print(f"Your favorite movie is: {fav_movie}.")
cb597b90eaddee4e5fdefba448c0bbd5ac1cd9b8
emanoelmlsilva/ExePythonBR
/Exe.Lista/EL.18.py
1,094
3.625
4
num = 1 cont=[0]*23 soma=0 per=[] while num != 0: s=0 num = int(input('Número do jogador (0=fim): ')) if num > 23: print('Informe um valor entre 1 e 23 ou 0 para sair!') elif num > 0: lista = list(range(1,24,1)) # lista = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23] for i in lista: if nu...
dc8f2810d38365f72e42b3e0bc39bf12d8f81f54
JhonathanAlejandro01/holberton-system_engineering-devops
/0x16-api_advanced/2-recurse.py
972
3.609375
4
#!/usr/bin/python3 """ function that queries the Reddit API and prints the titles of the first 10 hot posts listed for a given subreddit. """ import json import requests def recurse(subreddit, hot_list=[], after=""): """Return the first 10 hot posts listed for a given subreddit.""" if after is not "": ...
ddd9eacfee1499573fb1b7fc32ea28056a2ddccd
fede947/ohmyreport
/portinfo.py
601
3.65625
4
# -*- coding: utf-8 -*- import os class PortInfo: def __init__(self, port): self.port = port self.protocol = "" self.service = "" def add(self, protocol, service): self.protocol = protocol self.service = service def __lt__(self,other): return (int(self.por...