blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c2cdaaf5f6e92f390b2d1ab35b052f1ad48c334a | susieir/advent_of_code_2020 | /day3part2.py | 1,377 | 3.765625 | 4 | import math
def main(file, step_right, step_down):
# Open file and read into forest
with open(file, 'r') as fp:
forest = fp.read()
# Return width
width = forest.find("\n")
# Create a forest with no line breaks
forest = forest.replace("\n", "")
# Find height of fore... |
9caf8e76a3a63bbea630962c41437d62a48bd572 | Runn1ngW1ld/Domaca-naloga-10 | /Guess game.py | 398 | 3.65625 | 4 | from random import randint
intro = "Ugani skrit stevilo med 1 in 10"
print intro
def main():
while True:
secret = randint(1, 10)
guess = int(raw_input("Vpisi skrito stevilo: "))
if guess == secret:
print "Bravo stevilka je pravilna :)"
else:
print "Stevil... |
bd1cffe7412ec3c2be6e923c5480b859ac0ed989 | karlabelazcos/Ejercicios-Python-Guia-de-examen- | /Ejercicio9. Acumulado.py | 558 | 3.75 | 4 | acumulado=int(0)
numero=str("")
#Un bucle while permite repetir la ejecución de un grupo de instrucciones mientras se cumpla una condición
#(es decir, mientras la condición tenga el valor True).
while True:
numero=input("Dame un numero entero: ")
if numero=="":
#(Break) ,nos permite salir de adentro de un cicl... |
91d5feec5179301980e29615403ee969adf32330 | Zheng-Li01/Python_Excersise | /Day1/5.py | 2,044 | 3.734375 | 4 | ## 41.0 举例说明 Try except else finally 的相关意义 TrY\Except\Else 没有捕获到异常,执行else 语句. Try/Except/Finally 不管是否捕获到异常, 都执行Finally 与举报
## 42.0 Python 中交换两个数值
## 啊,b = 3,4 A,B = B,A
## 43.0 Zip() 的用法
## zip() 函数在运算时,会以一个或者多个序列(可迭代对象) 作为参数,返回一个元组的列表, 同时将这些序列中并排的元素配对;zip() 参数可以接受任何类型的序列, 同时也可以有两个以上的参数; 当传入的参数长度不同时
## zip 能够自动以... |
11d26c20d3c2d4c38b2c306f1f05c7f700111e55 | vt0311/python | /ch4/7dict.py | 503 | 3.78125 | 4 | '''
Created on 2017. 10. 19.
@author: acorn
'''
''' 순서 없고 '''
dict1 = {'john':25, 'jane':26}
print(dict1)
print(type(dict1))
print(dict1['john'])
dict1['john'] = 27
print(dict1)
print("length : ", len(dict1))
print(())
#v8, v9 = dict1
'''
print(v8)
print(dict1(v8))
print(v9)
print(dict1(v9))
'''
dict2 = {'john... |
c6e9008ccd5a68db4da8811083607005ea5210bf | ErickRDev/ufrj-ai-othello_player | /noobnoob_player.py | 17,190 | 3.59375 | 4 | class NoobNoob:
"""
Simulates an inteligent player
"""
import time
import copy
from models.move import Move
def __init__(self, color):
"""
Constructor.
"""
self.DEBUG_FLAG = False
self.color = color
self.opponent_color = "o" if sel... |
9309ead951070f482f006fcd6d453a5f76ba9b24 | Mauricio1xtra/python | /python_django/project/calculo_imc.py | 826 | 4.03125 | 4 | nome = input("Qual o seu nome?\n")
idade = input("Qual a sua idade?\n")
altura = input("Qual a sua altura?\n")
peso = input("Qual o seu peso?\n")
idade = int(idade)
altura = float(altura)
peso = float(peso)
imc = peso / (altura **2)
ano_atual = 2021
ano_nasc = ano_atual - idade
print(f'{nome} tem {idade} anos, {altu... |
6af51a556a534b2bf74149f8263f5708d13b5c49 | yazdanimehrdad1/CodingDojo-pythonStack | /assignments/python loops predict.py | 63 | 3.59375 | 4 | #1
for i in range(1, 10, 1):
print(i)
# prints 1 through 9
|
e2b16b0847efaca364ad5e2e45d031a874be8d45 | tuckerbrooks/COS125HW1 | /hw1c.py | 303 | 3.71875 | 4 | # File: hw1b.py
# Author: Tucker Brooks
# Date: September 14, 2019
# Section: 1001
# E-mail: tucker.brooks@maine.edu
# Description:
# Get the sum of 10 numbers
# Collaboration:
# N/A
x = 0
total = 0
while (x < 10):
value = input("Enter a value: ")
total = total + int(value)
x = x + 1
print ("The sum is:", ... |
dc0ea6ece7d6d6f44a52485f9741248335a6f514 | gchacaltana/python_snippets | /01_multiple_assignments.py | 639 | 4.4375 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# Declaración y asignación múltiple de variables.
x ,y, z = 2, 3, 5
# x = 2
# y = 3
# z = 5
print(f"\n1ra Asignacion")
print(f"x = {x} \ty = {y}\tz = {z}")
# Devuelve: 2 3 5
print(f"\n2da Asignacion")
print(f"y, x = x, z")
y, x = x, z
# y = x
# x = z
print(f"x = {x} \... |
681b457c04be0bbf4699535760ccd0c7a6e00dfe | rkalz/CS355 | /hw3_pokerhands.py | 2,843 | 3.65625 | 4 | # Rofael Aleezada
# January 29 2018
# Pokerhands Program, CS 355
# A program that simulates several instances in a poker game
from random import shuffle
from multiprocessing import Process
# Creates a player with a hand that can draw cards from the top of a deck
class Player:
hand = None
def __init__(self):... |
536e518b933fbc3a81ab05162f4719d26c564a49 | xavierohan/movie_recom | /RecommNet/RecommNet.py | 3,541 | 3.734375 | 4 | import pandas as pd
import numpy as np
pathname = '/Users/xavierthomas/Desktop/the-movies-dataset'
df_movies = pd.read_csv(pathname + '/' + 'df_large.csv')
df_ratings = pd.read_csv(pathname + '/' + 'd_large.csv')
ratings = pd.read_csv(pathname + '/' + 'ratings_small.csv')
del df_movies['overview']
# df_movies.head()
... |
c5ec9fe5a423e13519cf51b3f4bca441e923363b | jweiwu/ucom-python | /lab36.py | 562 | 3.53125 | 4 | import itertools
a1 = list('pqr')
a2 = list('ABCDE')
a3 = list('5678')
c1 = itertools.chain(a1, a2, a3)
print type(c1)
for c in c1:
print c,
print
print "again..."
for c in c1:
print c,
print
c2 = itertools.chain(a1, a2, a3)
l1 = [c for c in c2]
for l in l1:
print l,
print "\nagain...\n"
for l in l1:
... |
c49459825e7ba927ac0e1907aac3bb34a3300db9 | nisamk/Hello-world | /hackerrank/common child.py~ | 428 | 3.6875 | 4 | str1,str2 =input(),input()
matrix = [[0]*(len(str2)+1) for i in range(len(str1)+1)]
for i in range(len(str1)+1):
for j in range(len(str2)+1):
if i == 0 or j == 0:
matrix[i][j] = 0
elif str1[i-1] == str2[j-1]:
matrix[i][j] = matrix[i-1][j-1]+1
e... |
bf4c424b501e6736f47cff2382896a2c5190c2fe | tonper19/PythonDemos | /beyond_the_basics/03.closures_an_decorators/demo05_function_factories_raise_to_any_number.py | 634 | 4.59375 | 5 | """ """
def raise_to(exponent):
def raise_to_exponent(x):
return pow(x, exponent)
return raise_to_exponent
if __name__ == "__main__":
# the parameter exponent will be a closure with the value of 2
square = raise_to(2)
# and here is the proof:
print(square.__closure__)
# and now, whe... |
79cce00c5afcbd2c1a77b4d3164d51a452cb796e | pengyuhou/git_test1 | /leetcode/49. 字母异位词分组.py | 438 | 3.703125 | 4 | class Solution(object):
def groupAnagrams(self, strs):
a = {}
for s in strs:
ret = sorted(s)
res = ''.join(ret)
if res not in a.keys():
a[res] = [s]
else:
a[res].append(s)
ret = [i for i in a.values()]
re... |
a97f76817a4a1b5b0779f854a74df83bf5d1ca81 | therohitsingh/Top300DSACode | /Dynamic Programming/fibonacci-dp.py | 144 | 3.6875 | 4 | def fib(n):
f = [0,1]
for i in range(2,n+1):
f.append(f[i-1]+f[i-2])
return f[n]
n = int(input())
print(fib(n))
|
85cc8af0e80530cf7ea03907d23a5aca234e1221 | inki-hong/python-fast | /func.py | 143 | 3.859375 | 4 | def cube(n):
c = n * n * n
return c
result = cube(5)
print(result)
for x in range(100, 110):
result = cube(x)
print(result)
|
44ce4c0b69e186bff6b5cf3d3bb5cab35aa3813b | jduerbig/random-files | /hangman2.py | 344 | 4.21875 | 4 | #how tp change a string into a list
myString = "Arizona"
mysteryWord = list(myString)
print(mysteryWord)
guessList = []
#how to make a list using underscores for characters
for letter in mysteryWord:
guessList.append("_")
print(guessList)
# how to replace a specific index in a list
guessList[3] = "z"... |
bafaeeca05cca931623d3b1f93c01fd728c57b2f | wjymath/leetcode_python | /415.add_strings/add_strings.py | 945 | 3.5 | 4 | class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if len(num1) == 0:
return num2
if len(num2) == 0:
return num1
if len(num2) > len(num1):
num1, num2 = num2,... |
fca0385fa12f88d026ffec5fa70fea1043be5bb6 | perfectyuan/neural-network | /02-neural-network.py | 757 | 3.671875 | 4 | #创建一个神经网络类
class neuralNetwork :
#initialise the neural network
def __init__(self,inputnodes,hiddiennotes,outputnodes,learningrate):
#set number of nodes in each input,hidden,output layer
self.inodes = inputnodes
self.hnodes = hiddiennotes
self.onodes = outputnodes
... |
81dc55eb9417199fbf3e3e7d87a0906c7820c717 | zhangxiatlq/pythonDemo | /classDemo/classSimple.py | 800 | 3.78125 | 4 | class Employee:
'所有哦员工的基类'
empCount = 0
def __init__(self,name,age):
self.name = name
self.age = age
Employee.empCount +=1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmplyee(self):
print("Name:",self.name," age:",self... |
46abb35ce255285b9a3dd65aaca5fb51f567ccd1 | ambosing/PlayGround | /Python/Problem Solving/BOJ/boj11729.py | 242 | 3.796875 | 4 | def hanoi(h, a, b, c, res):
if h < 1:
return
hanoi(h - 1, a, c, b, res)
res.append((a, c))
hanoi(h - 1, b, a, c, res)
n = int(input())
lst = []
hanoi(n, 1, 2, 3, lst)
print(len(lst))
for i, j in lst:
print(i, j)
|
29e0cf91cbb6387e96042ea623508453655665fb | abbykahler/Python | /algo/functions_basic_II.py | 794 | 3.921875 | 4 | # 1 Countdown
# num = 5
# def countdown(num):
# new_list = []
# for x in range(num,-1,-1):
# new_list.append(x)
# return new_list
# print(countdown(5))
# 2 Print and Return
# list=[1,2]
# def print_return(list):
# print (list[0])
# return list[1]
# print (print_return(1,2))
# 3 First... |
1af92bbf191f005bc17d0b9f113c5fa87486ab4b | KonstantinKlepikov/scikit-fda | /examples/plot_clustering.py | 7,201 | 4.1875 | 4 | """
Clustering
==========
In this example, the use of the clustering plot methods is shown applied to the
Canadian Weather dataset. K-Means and Fuzzy K-Means algorithms are employed to
calculate the results plotted.
"""
# Author: Amanda Hernando Bernabé
# License: MIT
# sphinx_gallery_thumbnail_number = 6
import ma... |
9e91d29f86091554855d989ca871a66b09c7e123 | LuizFelipeBG/CV-Python | /Mundo 2/ex61.py | 269 | 3.75 | 4 | n1 = int(input('primeiro termo da PA: '))
r = int(input('Razão da PA: '))
ter = n1
c = 1
to = 0
r1 = 10
while r1 != 0:
to = to + r1
while c <= to:
print('{} >'.format(ter),end=' ')
ter += r
c += 1
r1 =int(input('Mais números? '))
|
dd81d79c64a90c6e5eb6a3c888df73f99d72348e | Joelma-Avelino/curso-em-video-python | /desafio/desafio13.py | 214 | 3.78125 | 4 | valor = float(input('Qual valor do seu salario atual? '))
vaumento = valor * 0.15
nvalor = valor + vaumento
print ('O seu atual salario de {} com aumento de 15% R${} fica por R${}'.format(valor, vaumento, nvalor))
|
6776e26844e55e831a01e0c5d5a63c0a352c99a9 | Dheeraj1998/code2flow | /code2flow/__main__.py | 766 | 3.5 | 4 | import code2flow
from code2flow import flowchart_generator
import sys
def main():
arguments = [argument for argument in sys.argv[1:] if not argument.startswith("-")]
#options = [option for option in sys.argv[1:] if option.startswith("-")]
if(len(arguments) == 0):
print("A python module / CLI comm... |
f90d1fa61cabc649258cec1ccb80fdec91702ce0 | baocogn/self-learning | /big_o_coding/Blue_13/Schoolwork/exam4.py | 906 | 3.953125 | 4 | # Phone List
class TrieNode:
def __init__(self):
self.count_leaf = 0
self.child = dict()
self.pre_check = False
class Trie:
def __init__(self):
self.root = TrieNode()
def add_word(self, s):
cur = self.root
flag = True
for c in s:
if c n... |
c763ccca1b984a69753ca163410587b96af2909a | zenginbusraa/flatten-reverse | /main.py | 421 | 3.859375 | 4 | def flatten(list1):
if len(list1)== 0:
return list1
if isinstance(list1[0],list):
return flatten(list1[0]) + flatten(list1[1:])
return list1[:1] + flatten(list1[1:])
def reverse2(liste):
rlist = []
for x in liste:
x.reverse()
rlist.append(x)
rlist.reverse()
return rlist
pr... |
5758478dfd2c70bde878b61898595aa16d458033 | karolramos/aprendendo_pitonha | /console_blackjack.py | 3,156 | 4.09375 | 4 | ############### Our Blackjack House Rules #####################
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace can count as 11 or 1.
## Use the following list as the deck of cards:
## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
## The cards in ... |
c86e94c4a0bde15280bfb8cbc8c94e265d1e917c | marcusorefice/-studying-python3 | /Exe045.py | 905 | 3.84375 | 4 | '''Crie um programa que faça o computador jogar Jokenpê com você.'''
from random import randint
j = int(input('Você quer: \n[1] PEDRA \U0000270A \n[2] PAPEL \U0000270B \n[3] TESOURA \U0000270C \n'))
print('-'*30)
r = int(randint(1, 3))
if j == 1 and r == 3:
print(f'VOCÊ GANHOU! O computador colocou TESOURA\... |
558334e31b01cf66421685c2d2b5a31eac8d29ca | jenniferyhwu/CS50-psets | /pset6/sentimental/mario/more/mario.py | 379 | 3.984375 | 4 |
while True:
height = int(input("Height: "))
if (height > 0 and height < 24):
break
for y in range(0, height):
for space in range(0, height - (y + 1)):
print(" ", end="")
for x in range(0, y + 1):
print("#", end="")
print(" ", end="")
print(" ", end="")
for x in... |
4f8e05b85325605d48f47f8ef25dcc17c6189d30 | rioadinugraha/1st-year | /pascal.py | 577 | 3.6875 | 4 | def pascal_triangle(n):
print([1])
print([1,1])
pascal = [0,0,0]
prevLine = [1,1]
for k in range (3,n+1):
for i in range(0,k):
if i == 0:
value = prevLine[i]
pascal[i] = value
elif i == k-1:
value = 1
pas... |
4936f793e739edfcca551a44524e2e452fb94bf7 | Anshul1196/leetcode | /solutions/121.py | 766 | 4 | 4 | """
Solution for Algorithms #121: Best Time to Buy and Sell Stock.
- N: Number of prices
- Space Complexity: O(1)
- Time Complexity: O(N)
Runtime: 32 ms, faster than 99.07% of Python3 online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 13.9 MB, less than 60.94% of Python3 online submissions ... |
f892388a9ae5298df6c185703b59c3cce04b1290 | GdubyaSDSU/Networks-Coursework | /TCPserver.py | 1,386 | 3.53125 | 4 | #!/usr/bin/python
# Gary Williams
# CS 576
# Prog 1 Due 2/26/17
# This is a basic server TCP socket connection.
# It connects to the localhost and specified port
# and listens for packets with a max 256 characters.
# The string is encoded by changing each character
# to the next character in the ASCII table... |
3a1acb7dd6b015ef336e13bd087ebd594ba5091f | forvaishali/PythonProjects | /quizGame/quiz_game.py | 955 | 4.125 | 4 | print("Welcome to my computer game")
playing = input("Do you want to play? ")
if playing.lower() != "yes":
quit()
print("Okay, Lets Play :)")
score = 0
answer = input("What does CPU stand for? ") # space after question important
if answer.lower() == "central processing unit":
print("Correct")
score += 1
e... |
d71e59d09dafffea5821431675b599a9c9bf5400 | Parzival-Wade/Unit-conversion | /unitconverter.py | 1,219 | 4.15625 | 4 | import pandas
user_input=input("What do you want to convert?[Distance or Time] ")
user_input_for_col=user_input+":unit"
user_input_list=user_input+":value"
data= pandas.read_csv('conversion_table.csv', index_col=user_input_for_col)
data_dict=data.to_dict()
conversions_list=data_dict[user_input_list]
def val... |
386ad990148de8693700e5046db9c8da11938ee8 | divae/keepcodingLearnPython | /functions/map_filter_reduce.py | 677 | 3.78125 | 4 | from functools import reduce
list_values = [1,2,-1,15,9]
def double(x):
return x*2
list_double_values = map(double,list_values)
list_double_values1 = map(lambda x: x * 2 ,list_values)
def is_pair(x):
return x % 2 == 0
list_pairs_values = filter(is_pair, list_values)
list_pairs_values = filter(lambda x: x %... |
2b253469bd6b88202743b9c894ee6d65ce3fd637 | gabriellaec/desoft-analise-exercicios | /backup/user_061/ch26_2019_03_13_21_37_32_553158.py | 232 | 3.65625 | 4 | dias = int(input("DIAS"))
horas = int(input("HORAS"))
minutos = int(input("MINUTOS"))
segundos = int(input("SEGUNDOS"))
dias = dias*24*60*60
horas = horas*60*60
minutos = minutos*60
a = dias + horas + minutos + segundos
print(a)
|
0efad27f73b67b3d3f30c5f084e3c5d618a663be | manthalkaramol/Demo | /PythonPrograms/assignment_operator2.py | 166 | 3.78125 | 4 | a=b=c=1
print (a,b,c)
a=2
c=0
print (a,b,c)
print (a and b)
print (a and c)
print (b or c)
list = [1,2,4,5,7,8,10,16]
print (a not in list)
if a in list:
print (a)
|
13a853bfd298ef7beaa826d4b41d6d0f7a3586f8 | AhmedSadaqa/Qvirt | /my_django_app/customer/Myqueue.py | 1,471 | 3.578125 | 4 | try: from Queue import Queue, Full, Empty
except: from queue import Queue, Full, Empty
from datetime import datetime
class MyQueue(Queue):
"Wrapper around Queue that discards old items instead of blocking."
def __init__(self, maxsize=10):
assert type(maxsize) is int, "maxsize should be an integer"
... |
ee7c4082046ab8166f446c211a6d7ca00082dc12 | tawfiqul27/python_code | /13_built_in_functions.py | 2,052 | 4.0625 | 4 | #### Numeric built-in functions
x = '47'
y = int(x)
z = float(x)
# y = abs(x) for absolute value
# y = divmod(x, 3) for devision modulus value
# y = complex(x, 32) this is for complex number. And will print 47 + 32j
### https://docs.python.org/3/library/functions.html
# this list all the built-in numeric... |
5ceb4afeb691dbfd31eb9b01d0fe46283b815509 | abhishekguptapune/DataScience | /Label_Encoding_or_Ordinal_Encoding.py | 630 | 3.5 | 4 | #Label Encoding or Ordinal Encoding
import category_encoders as ce
import pandas as pd
train_df=pd.DataFrame({'Degree':
['High school','Masters','Diploma','Bachelors','Bachelors','Masters','Phd','High school','High school']
})
#Original data
train_df
print(train_df)
# create object of Ordinalencoding
en... |
f29bff36d0153c454488d7bdf40bc7cfa932d3a9 | ak-ashwin/leet_code | /12_balancedStringSplit.py | 2,054 | 3.671875 | 4 | from typing import List
from collections import Counter
# Example 1:
#
# Input: s = "RLRRLLRLRL"
# Output: 4
# Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
# Example 2:
#
# Input: s = "RLLLLRRRLR"
# Output: 3
# Explanation: s can be split into "RL", "L... |
02b0d0931164c92791f443282d14e90a9c19e703 | VanillaTiger/adventofcode2020 | /exercise_9/exercise_9.py | 1,192 | 3.578125 | 4 | with open('exercise_9_all.txt', 'r') as file:
input_data = file.readlines()
input_data = [int(m[:-1]) for m in input_data]
print("input_data=",input_data)
preamble = 25
def verify_data(number, previous_data):
length = len(previous_data)
sumita = [previous_data[x] + previous_data[y] for x in range(0, le... |
9bcb3e98ee3a0f9d3ea0dd3ffdf808faf918dda5 | jbizzlefoshizzle/Financial_Analysis-and-Voter_Results | /Python Script for Bank Data/main.py | 2,056 | 3.875 | 4 | # Declarations
import os
import csv
#NEED THIS TO CALCULATE DIFFERENCES BETWEEN MONTHS
import numpy as np
# Defining max and min functions
# -------------------------------------
def max(array, n):
max = array[0]
for i in range (1, n):
if array[i] > max:
max = array[i]
return... |
a29fbfbfba7a113e31e99405eeb4ecd3fd7ebc2b | liuleee/python_base | /day02/08-continue和break.py | 1,357 | 3.796875 | 4 | # -*- coding:utf-8 -*-
#continue结束本次循环,然后可以继续下次循环,整个循环不一定结束
#break:跳出当前循环,当前循环执行结束
#continue和Break不能单独使用,只能在循环语句中使用
# num = 1
# while num < 6:
# print(num)
# if num == 2:
# num += 1
# #执行continue结束本次循环,continue后面的代码不会执行
# continue
# num += 1
# else:
# print('循环数据结束')
num = 1... |
a28fdb5ad4eded15b0b26da363660e9c1aeaf54f | suhao16/CSEScompetitiveprogramming | /introductory_problems/missing_number.py | 310 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#------------------------------*
# Author: Arijit Dasgupta |
# Email: arijit.dg@hotmail.com |
#------------------------------*
len_line = int(input())
sum_line = len_line*(len_line+1)//2
line = [int(x) for x in input().split()]
missing_num = sum_line - sum(line)
print(... |
a41cb795150f5c76b92f1d8a3163f3d9374b3db6 | Pinto18/travis_example | /checkPrime.py | 281 | 3.890625 | 4 | import math
def check(num):
isPrime = False
if num <= 1:
return isPrime
for index in range(2, math.ceil(math.sqrt(num))):
isPrime = True
if num % index == 0:
isPrime = False
return isPrime
return isPrime
|
f3a976f2af9e53a3f392b4a3c30c9be5f390bc68 | raginikk/Leetcode_May_Challenge | /FloodFill.py | 582 | 3.515625 | 4 | def FillPixel(image,r,c,prevC,newC):
if( r<0 or r>=len(image) or c<0 or c>=len(image[0]) or image[r][c]==newC or image[r][c]!=prevC):
return
image[r][c]=newC
FillPixel(image,r+1,c,prevC,newC)
FillPixel(image,r-1,c,prevC,newC)
FillPixel(image,r,c+1,prevC,newC)
FillPixel(image,r,c-1,p... |
2b6e00de5bb7207a01264950c32d4f8af8f4653f | LeslieK/JOBPREP | /Exercises.py | 4,339 | 4.03125 | 4 | def fib(n):
'''find fibonacci number of n'''
def helper(a, b, count):
if count == 0:
return b
else:
return helper(a + b, a, count - 1)
return helper(1, 0, n)
def sum(list):
'''add the integers in a list'''
num_elements = len(list)
def sum_iter(acc, count):
'''sum the itegers in a list'''
if list ... |
8fbc6adfeb4f97dafb955053e337dede71ed8935 | trolly0305/LeetCode | /Algorithms/0143 Reorder List.py | 1,406 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def split(self, node):
prev = None
slow = fast = node
while fast and fast.next:
prev = slow
slow = slow... |
87a67ef786c2ce9b996a04152b4b42aedd4dc523 | DanDaMan23/CardGames | /deck_of_cards.py | 1,707 | 3.8125 | 4 | import random
class Card:
def __init__(self, suit, value):
suits = ("hearts", "diamonds", "clubs", "spades")
values = [str(i) for i in range(1, 14)]
values[0] = "A"
values[12] = "K"
values[11] = "Q"
values[10] = "J"
values = tuple(values)
... |
018824e3c25b018d9330e956ecc0cf682cab32d5 | layroyc/python01 | /lx.py | 12,126 | 4.03125 | 4 | #输入函数:
'''
输入函数:
input() 没有参数输出的是一个空白行
input(“提示信息”)
input接收到的都是字符串类型
eval(input("")) 接收到数据的实际数据类型
'''
#a = input("请输入一个整数:")
#print(a)
#输出函数
'''
输出函数:
print()
一次输出多个内容:
1.用逗号链接 不限制数据类型 多个数据之间逗号分隔
2.用加号连接 只能拼接字符串类型的数据
3.格式化输出 print(“格式化输出符号” % (变量名1,变量名2.......))
字符串 %s 整数 %d 浮点数 %f 百分... |
84addc37d4ea68d0ce44ad103db892947917fbb4 | KarlYapBuller/Quiz-Quest-game-Assesment-Ncea-Level-1-Programming-Karl-Yap | /07_Statement_Decorator_v1.py | 964 | 4.1875 | 4 | #Statement Decorator component version 1
#Statement generator
#The statement generator funcrion decorates the statements in the Quiz Quest Game
def statement_generator(statement, decoration):
#The sides of the statement on each side is three of the decorations
sides = decoration * 3
#The sides of the sta... |
2ef6f24403f232b3876423645aa63dd5abbfc81f | sg45905/Artificial_Intelligence | /Tower-of-Hanoi/priority.py | 1,285 | 3.796875 | 4 | import heapq
import itertools
# Create a priority queue
class PQ:
def __init__(self):
self.pq = []
self.entry_finder = {}
self.REMOVED = -1
self.counter = itertools.count()
self.size = 0
self.numAdded = 0
# update the queue and priorities
def update(self,gam... |
ed8b03aa8d813b943c8a37be564711d023c07feb | kakru/puzzles | /leetcode/037_sudoku_solver.py | 3,541 | 3.65625 | 4 | #/usr/bin/env python3
import unittest
class Solution: # 2364ms
EMPTY = "."
def isValidSudoku(self, board):
seen = []
for i, row in enumerate(board):
for j, digit in enumerate(row):
if digit != '.':
# seen.append((i, digit)) # numbers in rows ar... |
293b090732ce5cdb3ac0d626228bdc8360bc6133 | linchangyi/LeecodeInterview | /07partition.py | 1,764 | 3.625 | 4 | '''
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
'''
class Solution:
def __init__(self):
self.s = None
self.PMatrix = None
self.res = []
def _init_palindrome_matrix(self):
s = self.s
length = len(s)
... |
9851595fc43e11cfcc62e6e63e357e38e6904049 | AnacondaFeng/AnacondaFeng | /class_S/test_decorator3.py | 790 | 3.703125 | 4 |
# 带参数的装饰器
def log(name=None):
def decorator(func):
def wrapper():
print('{0}.start..'.format(name))
func()
print('{0}.end..'.format(name))
return wrapper
return decorator
# 执行方法带参数的装饰器
def log2(name=None):
def decorator(func):
def wrapper(*args, ... |
6050ad32082015b2e60d46fbd0a37114bcf4eb95 | tguterres/projectpython | /aulas/aula04.py | 204 | 3.796875 | 4 | #Exercício Aluguel de Carros
d = int(input('Quantos dias o carro foi alugado? '))
km = float(input('Quantos kilometros foram rodados? '))
v = (d*60) + (km * 0.15)
print('O valor do aluguel é: R${:.2f}'.format(v))
|
268ebc13b3e9ea7ce7995bf64bd03a08c6552376 | PabloYepes27/holbertonschool-higher_level_programming | /0x0A-python-inheritance/10-square.py | 831 | 4.34375 | 4 | #!/usr/bin/python3
"""[Write a class Square that inherits
from Rectangle (9-rectangle.py):]"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""[class square from class Rectangle]
Arguments:
Rectangle {[class]} -- [parent class]
"""
def __init__(self, size):
... |
0973ce6f2fc911c16ff244509b19351539da0a1b | sharingplay/Introduccion-a-la-programacion | /Python/Recursion de Pila/Listas/listaInverso.py | 447 | 3.984375 | 4 | """Desarrolle un programa que recibe como parametro una lista y la regresa en
orden invertido"""
def listaInverso (lista):
if isinstance (lista,list):
return inverso(lista)
else:
return "Error"
def inverso (lista): #suma el primer numero de la derecha y manda los demas
if lista == []... |
d927685e2a7421e4c98334c64b76d7b512366558 | CoderFemi/AlgorithmsDataStructures | /practice_challenges/python/decent_number.py | 1,078 | 4 | 4 | def decentNumber(num_digits) -> int:
"""Form a decent number from input digits"""
def check_decent(num_threes):
remainder = num_digits - num_threes
if remainder % 3 == 0 and remainder > -1:
decent_num = int(("5" * remainder) + ("3" * num_threes))
return decent_num
d... |
7f587fd5a9c455f70125e25766da38091a06310f | chloe-wong/pythonchallenges | /GC45.py | 79 | 3.6875 | 4 | char = input()
if len(char) == 1:
print("Char")
else:
print("Not char") |
ee99669514af63fc9837021b60e9274b210d5449 | acaciooneto/cursoemvideo | /ex_videos/ex-082.py | 538 | 3.703125 | 4 | principal = []
pares = []
impares = []
while True:
continuar = ' '
principal.append(int(input('Digite um número: ')))
while continuar not in 'SN':
continuar = str(input('Você deseja continuar? [S/N]: ')).strip().upper()[0]
if continuar == 'N':
break
for elemento in principal:
if elem... |
6ef893ea3efb34dd92cf606ece9b70f27bc98d8c | AmrutaBhujbal09/Basic_Programs_Aarray_In_C | /PYTHON/Global_Variables.py | 696 | 3.96875 | 4 |
"""def f():
print(s)
s="m in def f()"
print(s)
return "helo world"
global s
s="NAMASTE INDIA!!!"
t=f()
print(t)
OUTPUT:
UnboundLocalError: local variable 's' referenced before assignment
MEANING OF THIS ERROR IS THAT IF ANY VARIABLE declared inside a function ... |
2f71e971076ade95b1b2377b5f870436c416ad1e | eVoRisk/Python | /prime.py | 967 | 4.15625 | 4 | __author__ = 'eVomeR'
# import only sqrt from math package
from math import sqrt
# prime test function
def isPrime(number):
for index in range(2, int(sqrt(number)) + 1):
if number % index == 0:
return False
return True
# read the input from console
isNumber = False
while isNumber <> True... |
5fb265dbd3602eb8f8fa214e1b4cc16f342078cb | DShmunk/h3_homework | /calc_grid.py | 2,098 | 3.890625 | 4 | from tkinter import *
from tkinter import messagebox
from tkinter import ttk
# для добычи корня
import math
root = Tk()
root.title("Calculator")
# сотворение ввода
calc_entry = Entry(root, width = 44)
calc_entry.grid(row=0, column=0, columnspan=4, sticky=N+S+W+E)
# сотворение кнопок
bttn_list = [
"(",... |
bff0cc5f0193a703a676ba8f8febdd330d403e12 | Voron07137/PythonTutor | /ch4/l46.py | 284 | 3.65625 | 4 | import copy
A = [[10, 20], [[30, 40], [50, 60]]]
B = copy.deepcopy(A)
print("Список A", A)
print("Список B", B)
print("Выполняются команды A[0][1] = 0 и A[1][1][1] = 0.")
A[0][1] = 0
A[1][1][1] = 0
print("Список A", A)
print("Список B", B)
|
d6f1d6b6da6d64924c850b5a2653b0ef70ea4390 | vaibhavboliya/DSA-Programming-Problems | /Geeksforgeeks/02 Array/Alternate positive and negative numbers.py | 1,697 | 4.125 | 4 | # URL : https://practice.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos1401/0/
# Given an unsorted array Arr of N positive and negative numbers. Your task is to create an array of alternate positive and negative numbers without changing the relative order of positive and negative numbers.
# Note: Array sh... |
7f3a8e59b07b3034014727c02a683f274b1fc67b | meliatiya24/Python_Code | /p1.py | 912 | 3.75 | 4 | data1=[None]*2
for i in range(2):
data1[i]=[None]*2
for x in range(2):
for y in range(2):
data1[x][y]=int(input());
print(data1)
data2=[None]*2
for i in range(2):
data2[i]=[None]*2
for x in range(2):
for y in range(2):
data2[x][y]=int(input());
print(data2)
a=data2[0][0]
b=(data2[0][1]... |
81d7e839bd92cf916b66467430c0e96628c42954 | Kabir12401/FIT1008 | /Interview Prac 2/army.py | 10,241 | 4.09375 | 4 | """
The below is created for the creation of an army elements. It has the Soldier, Archer and cavalry classes that inherit from a
a fighter class with the abstract method defend.
"""
__author__ = "Ashwin Sarith"
# implemented classes and their methods below here
from abc import ABC, abstractmethod
from queue_adt ... |
3880ab2d6db8654b6ce78de9611f65325caa54be | eldss-classwork/Python-for-Everybody-Specialization | /Accessing Web Data/Extracting-Data-JSON.py | 753 | 4.21875 | 4 | # Evan Douglass
# Extracting Data from JSON
# This program reads JSON from a webpage and finds information about
# comment counts. The webpage used for this assignment (Coursera) is:
# http://py4e-data.dr-chuck.net/comments_40264.json
import json
from urllib.request import urlopen
import ssl
# ignore SSL ... |
74115da0fccba79782d46f2db625afd53a8893bb | srdecny/diasys | /hw1/minDistUtil/tests.py | 1,110 | 3.578125 | 4 | from levenshtein import Levenshtein
from io import StringIO
import unittest
class TestBasicFunctionality(unittest.TestCase):
def test_example(self):
examples = {
("", "") : 0,
("a a a", "a a a") : 0,
("a b", "a a a") : 1,
("a b c a", "a a a") : 1,
... |
d28652293f4e6fb7ca5b6bc0e4d865576ebe82e8 | SarthakVerma26/291197dailycommit | /binarysearch.py | 579 | 4.03125 | 4 | def binarySearch(numbers, low, high, x):
if (high >= low):
mid = low + (high - low)//2
if (numbers[mid] == x):
return mid
elif (numbers[mid] > x):
return binarySearch(numbers, low, mid-1, x)
else:
return binarySearch(numbers, mid+1, high, x)
el... |
9aeb1b699083a0d041e3f919dcf6cc11d6967fd9 | chandthash/nppy | /Minor Projects/removing vowels.py | 547 | 4.34375 | 4 | def remove_vowels(strings):
'''Remove vowels from the word given by the user'''
try:
if not str(strings).isalpha(): # If the given value is integer
strings = str(strings)
new_word = ''
for letter in strings:
if letter not in 'aeiou':
... |
9b92b8cd82319f62364bbdd52e913078f3495603 | wesley74alexander/PY4E | /json_parser_1.py | 1,075 | 4.125 | 4 | #In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The program will
#prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON
#data, compute the sum of the numbers in the file and enter the sum be... |
92f5c20828b7488e0d1a5de7b93e070c18efb0fe | miguel-aguilar/trabajo09.aguilar.arroyo | /arroyo/libreria.py | 15,283 | 3.71875 | 4 | #EJERCICIO NUMERO 1
#EN ESTE EJERCICIO PEDIREMOS EL DNI DE LA PERONAS
#NO DEBE SER DIFERENTE DE UN NUMERO Y NO SOBREPASAR LOS 8 DIGITOS,
def pedir_dni(dni):
if (len(str(dni)) != 8):
mensa="el DNI es falso"
return mensa
else:
return dni
##################################################... |
988bcf77a3294e7a26291219539f10177266e3a1 | midi0/python | /CodingDojang/Unit 26/26.6.py | 290 | 3.734375 | 4 | '''
세트 표현식 사용하기
a = {i for i in 'apple'} #중복되는 p는 하나만 요소로 들어간다
표현식과 if 조건문 사용
a = {i for i in 'pineapple' if i not in 'apl'} # e i n이 요소로 들어감
'''
a = {i for i in 'pineapple' if i not in 'apl'}
print(a) |
c9065d4530057f993572c6cd3dd335a747f245d7 | tydhoang/CSE-143 | /N-Gram Language Models/Training_Token_Initialization.py | 3,769 | 3.609375 | 4 | # @author Tyler Hoang
# CSE-143
# Training_Token_Initialization.py program that finds the frequency of all tokens in the training data. Words that occur less than 3 times are replaced
# with <UNK> tokens. Dev and test data set are then analyzed for OOV vocab and subsequently replaced with <UNK> tokens. This data is out... |
1c793073240fb3059830981ebaccd22555902641 | Joeffison/coding_challenges | /challenges/spoj/nsteps/nsteps_v001.py | 475 | 3.5625 | 4 | #!/usr/bin/env python3
import fileinput
import sys
if sys.version_info[0] >= 3:
map = lambda func, l: [func(i) for i in l]
else:
range = xrange
if __name__ == '__main__':
f_in = fileinput.input()
n_test_cases = int(f_in.readline())
for i in range(n_test_cases):
x, y = map(int, f_in.readline().split())
... |
75b7ba38d4cba1f2233a5b263623ff31c08771c0 | aneeshdurg/dotfiles | /.quotes.py | 2,081 | 3.546875 | 4 | #! /usr/bin/python3
from random import randint
import os
_, columns = os.popen('stty size', 'r').read().split()
columns = int(columns)
def fitColumn(final, s):
if len(s) < columns:
final.append(s)
else:
c = columns
while c>=0 and s[c] != ' ':
c-=1
if c < 0:
... |
61947b62db459cbe3644338e33eff61f0aff8e6c | zhangdavids/workspace | /Daily/180507.py | 631 | 3.734375 | 4 |
# 哈夫曼算法
from heapq import heapify, heappush, heappop
from itertools import count
def huffman(seq, frq):
num = count()
print(num)
trees = list(zip(frq, num, seq))
print(trees)
heapify(trees)
while len(trees) > 1:
fa, _, a = heappop(trees)
fb, _, b = heappop(trees)
n = ... |
6c8d2634de6b7c13f4c7dbf94f0ffdad7362ff8c | jntushar/leetcode | /30-Day LeetCoding Challenge/Maximum Subarray.py | 370 | 3.859375 | 4 | """
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
"""
"""---SOLUTION---"""
class Solution:
def maxSubArray(self, nums):
T=[0]*len(nums)
T[0]=nums[0]
for i in range(1,len(nums)):
T[i]=... |
954eec135fd979cec4bb3aa59c98cfcc307258d3 | TREMOUILLEThomas/ex-68 | /ex 68 (3).py | 401 | 3.96875 | 4 | from turtle import *
def triangle(a):
begin_fill()
for i in range (3):
forward(a)
left(120)
end_fill()
def tritri(a):
for i in range(3):
triangle(a)
left(90)
up()
forward(a/2)
right(90)
forward(a/6)
down()
a=a*(2/3)
... |
d875656e721146c25dae984c847498ea7a59bb9d | jatinrajani/Principles-of-Computing | /rockpaperlizard.py | 2,645 | 4.25 | 4 | # Rock-paper-scissors-lizard-Spock template
import random
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
def name_to_number(name):
... |
fddc71038001b4de9eb1013bdb7f4a3aadfe6def | Tofitk/TextMinesweeper | /main.py | 1,046 | 3.9375 | 4 | from classes import board_class, tile_class
from functions import functions
height = int(input("give the height of the playing board (max 10): "))
lenght = int(input("give the lenght of the playing board (max 10): "))
max_mines = str((height * lenght) - 1)
mines = int(input("give the amount of mines you want (ma... |
9f38ccbe3335dc8ac4dba611f0b81d72e2a6c8e9 | lawrenceh123/data-challenges | /data-science-400/04-NumericData.py | 7,580 | 3.53125 | 4 | """
L04 Assignment: Numeric Data
Dataset: Credit Approval Data from UCI Machine Learning Repository
Operations: assign column names, impute and assign median values for missing numeric values,
replace outliers (with median values), create a histogram and a scatterplot, determine the standard deviation of all numeri... |
f19b2d5f2efcef610edc572f99603ea1f3e54347 | Iven022/TD3_Iven_Henna | /main.py | 1,075 | 4.25 | 4 |
from addTwoInt import add
from mulTwolnt import mul
x="a"
while((x=="a") or (x=="q") or (x=="b")):
print("For Addition of two numbers press < a > ")
print("For multiplacation press < m > ")
print("For both calculations press < b > ")
print("To quit press < q > ")
x=input("Enter desired process ")
if ((x=="a") o... |
509dc153042e70bc17b917a7495f86f6409c5234 | mucahidyazar/python | /worksheets/09-advance/exercises/harf-kac-kez.py | 423 | 3.578125 | 4 | print("""
QUESTION:
Elinizde uzunca bir string olsun.
"ProgramlamaÖdeviİleriSeviyeVeriYapılarıveObjeleripynb"
Bu string içindeki harflerin frekansını (bir harfin kaç defa geçtiği) bulmaya çalışın.
""")
newString = "ProgramlamaÖdeviİleriSeviyeVeriYapılarıveObjeleripynb"
newList = dict()
for x in newString... |
d52bd6d4dd90e10832ce8aa446fd8c9c7cb30c0a | srajeevan/Python-apps | /Misc/function.py | 162 | 3.625 | 4 | def hello(name):
print('Hey '+ name)
hello('Roy')
hello('Alice')
def plusOne(num):
print(num + 1)
plusOne(5)
for i in range(0, 10, 2):
print(i)
|
6ef5f64f0b6061be957d71c7b41ae2289ecb8693 | kamalkorede/MIT-6.001 | /6.00a/ps2a.py | 4,564 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 31 20:45:00 2017
@author: KAMALDEEN
"""
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
""" # inFile: file
inFile = open(WORDLIST_FILENAME, 'r')... |
14e8eff740778825d49784a77dfc77960763d812 | Jelly-yeah/Study | /小写大写 判断.py | 114 | 3.5625 | 4 | pan = input()
def pan(a):
if ord(a)>=97:
return "大写"
else:
return "小写"
|
9f57906df9e4615f1d8f5297c9fb1cd0e225b544 | ishantk/Enc2019B | /venv/Session20E.py | 775 | 3.84375 | 4 | class BaningException(Exception):
pass
print(">> Banking Started")
accBalance = 10000
minBalance = 2000
attempts = 0
def withdraw(amount):
global accBalance
global minBalance
global attempts
accBalance = accBalance - amount
if accBalance > minBalance:
print("Withdrawl Finished!! New B... |
ba79b4f345ab83931d8fb1e64c844715b4259c22 | toastdriven/euler | /jason/problem-005.py | 164 | 3.765625 | 4 | #!/usr/bin/env python
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
def lcm(a, b) :
return a * b / gcd(a, b)
print reduce(lcm, range(1,21)) |
a327e96d8090b1017478764680dcdd3cf9de89a6 | spearfish/python-crash-course | /example/16.1.2_print_header/highs_lows.py | 365 | 3.75 | 4 | #!/usr/bin/env python3
import csv
fname = 'sitka_weather_07-2014.csv'
with open(fname) as f :
# create a reader object
reader = csv.reader(f)
# next function calls reader.__next__, which returns a line and move the pointer to the next line
header_row = next(reader)
for index, header in enumerate... |
1ea7b71be476e782b004ca82bd5c2ec050aec769 | sana25052001/FSD | /data structure.py | 301 | 4 | 4 | from enum import Enum
class Country(Enum):
Africa = 93
Asia = 355
America = 213
Antarctica = 376
Europe = 244
Paris = 672
print('\nMember name: {}'.format(Country.Paris.name))
print('Member value: {}'.format(Country.Paris.value))
Output:
Member name: Paris
Member value: 672
|
a65c26564f84ee38ec382cc2b7a34cb56c30d2c3 | harmansehmbi/Project10 | /practice10j.py | 261 | 3.890625 | 4 | class CA:
num = 101
def __init__(self):
self.a = 102
def show(self):
print("num is: ", self.num)
# we can also use
print("num is: ", CA.num) # class name
print("num is: ", ca.num)
ca = CA()
ca.show()
|
034989642e0474b3e8fb52b4cdf0015288455d93 | HaydenInEdinburgh/LintCode | /547_intersection_of_two_arrays.py | 1,027 | 3.84375 | 4 | class Solution:
"""
@param nums1: an integer array
@param nums2: an integer array
@return: an integer array
"""
def intersection(self, nums1, nums2):
# write your code here
if not nums1 or not nums2:
return []
p1, p2 = 0, 0
intersection = []
nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.