blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
56e0e4a1cbb8f8b2d53b4af17cb27a6f5d89a4b6 | ValentinaToro/programacion | /Tarea4.py | 879 | 3.9375 | 4 | #
#En el primero deberán demostrar las 4 operaciones aritméticas, además de la operación módulo
# definiendo variables e imprimiéndolas en cada paso, usando f-strings.
print ("Primero definiré la variable,")
valor_global = 6
x = valor_global
print(x)
print(type(x))
print ("luego realizaré las cuatro operaciones más el ... |
434f750a381721dc3b0201f6379783617de388e5 | RafaelDavisH/Simple_Python_Projects | /Turtle Race/turtle_race.py | 2,099 | 4.5625 | 5 | #!/bin/python3
from turtle import *
from random import randint
# === Build the Race Track
# write(0) # turtle draws track markings for the race
# forward(100) # turtle draw a line using the turtle
# write(5) # turtle draws track markings for the race
# writing all the numbers in between to create markings
# write... |
8e43eafecc87e72068201626ec08e0e6aed214da | franktank/py-practice | /goog/foobar/cake-is-not-a-lie.py | 572 | 3.734375 | 4 | """
Test cases
==========
Inputs:
(string) s = "abccbaabccba"
Output:
(int) 2
Inputs:
(string) s = "abcabcabcabc"
Output:
(int) 4
"""
abcabc
a -> bcabc
ab
if substring reduced to nothing -> return
1 +
else if not part of substring
res = 0
def answer(s):
res = 0
for i in range(1, len(s)):
... |
6d59e2545d1afb35ce89656443eabc58dad1d4ca | wmakaben/AdventOfCode | /AoC_19/d01.py | 470 | 3.65625 | 4 | file = open("input/d01.txt", 'r')
def getFuel(mass):
return (mass // 3) - 2
totalFuel = 0
for mass in file:
totalFuel = totalFuel + getFuel(int(mass))
# Test Case: 654
# totalFuel = getFuel(1969)
# Test Case: 33583
# totalFuel = getFuel(100756)
print(totalFuel)
# 3231941
# Part 2
file = open("input/d01.txt", 'r... |
63ff361f0be9a71aebf581d9116b753c1ac2d2b4 | mertkanyener/Exercises | /file_overlap.py | 430 | 3.671875 | 4 | def read(file):
result = []
with open(file, 'r') as open_file:
lines = open_file.read().splitlines()
for line in lines:
result.append(int(line))
return result
def overlapping(list_one, list_two):
result = []
for i in list_one:
if i in list_two:
resul... |
fb192db966e11a8b657655c6c1d32aeed86816eb | AnhellO/DAS_Sistemas | /Ene-Jun-2022/francisco-alan-menchaca-merino/practica-6/composite.py | 1,988 | 3.859375 | 4 | from abc import ABC, abstractmethod
class FileSystem(ABC):
"""The base Component class declares common operations
for both simple and complex objects of a composition"""
@abstractmethod
def string_rep(self, file):
pass
class File(FileSystem):
"""The leaf class represents the end objects... |
ce265bbaaf7d98d128e7a27552fa352f575719f8 | portugol/decode | /Algoritmos Traduzidos/Python/Algoritmos traduzidos[Filipe]/ex6.py | 380 | 3.9375 | 4 | imc = input('Digite o valor do IMC(Indice de Massa Corporal): ')
if int(imc)<20:
print('Abaixo do Peso')
elif int(imc)>=20 and int(imc) <=24:
print('Peso Ideal')
elif int(imc)>=25 and int(imc)<=39:
print('Excesso de Peso')
elif int(imc)>=30 and int(imc)<=39:
print('Obesidade')
elif int(imc)>39:
pri... |
3423b374ad7caac6ac092b49d036c0a560153810 | KKiim/Bachelor-Thesis-Leader-Follower-Analysis-in-Immersive-Analysis | /Python/Ana/compute_input.py | 745 | 3.5 | 4 | # compute_input.py
import sys
import json
import l_f_csv as lf # Local file
# Read data from stdin
def read_in():
lines = sys.stdin.readlines()
# Since our input would only be having one line,
# parse our JSON data from that
return json.loads(lines[0])
def main():
# get our data as an array fr... |
e4518cfdbcb296fd57a071c2634a48515e47378f | jack96harrison/PythonBeginner | /PythonPractice_Exercise7.py | 225 | 4.03125 | 4 | """
Take a variable of a list e.g a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Write one line of python that makes a new list with only the even elements
"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = a[1::2]
print(a)
print(b) |
c9052cdd2503b94a8d19d2fe47322ede0b3629b9 | pranavr11/school_scheduling | /realSchoolSchedule.py | 6,570 | 3.890625 | 4 | from datetime import datetime
'''
ERRORS TO BE FIXED WHEN I EVETUALLY REDO THIS a:
If the time is before school starts it registers next class as second blockNumber
You probably can't read this code anyway lol
'''
'''
1) Input what school day (A/B) it is today
2) Give me the name of my current class depending on the c... |
bc80f7d44bc17231af5990cbd5b786ec31911128 | vamazzuca/Mazzuca-MiniMax-Project | /Unbeatable Tic-Tac-Toe.py | 6,876 | 4.15625 | 4 |
# Initites the Tic Tac Toe Game
#Wriiten for Assignment 4 CMPUT 355 University of ALberta
# Written by Alex Mazzuca
def main():
ticTacToeGame()
return
# Runs Tic Tac Toe Game. Only the Human player can player X and plays against the ai O player
# Written by Alex Mazzuca
def ticTacToeGame():
... |
308b687ebf85ecb931656c0acd98c6b72f0899fc | mitamit/OW_Curso_Python | /diccionario.py | 801 | 4 | 4 | diccionario = {'a': True, 1: "esto es un string", (1,2): False} #las llaves son inmutables
#almacenar
diccionario['b'] = "nuevo string" #creamos clave valor
diccionario['a'] = False #si encuentra la llave actualiza sino crea
#obtener datos
valor = diccionario['a']
valor = diccionario.get('z', False) #sino encuentra z... |
c21001d0c6c3369692c4ca01d7256d2e7d18a6b8 | keltoom/Python_programs | /algeria-states-game/main.py | 1,105 | 3.921875 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("ALGERIA States")
image = "algeria_states_blank.gif"
screen.addshape(image)
turtle.shape(image)
# def get_mouse_click_coor(x,y):
# print(x, y)
#
# turtle.onscreenclick(get_mouse_click_coor)
data = pandas.read_csv("48_states.csv")
states = data.sta... |
c4c1a59329e38f93df04516d49e4723721d49268 | hyungook/python-basics | /100jun/04_test.py | 2,045 | 3.65625 | 4 | # while문
'''
# 10952
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
입력은 여러 개의 테스트 케이스로 이루어져 있다.
각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)
입력의 마지막에는 0 두 개가 들어온다.
'''
while True:
a,b = map(int,input().split())
if a == 0 and b == 0:
break
else:
print(a+b)
'''
# 10951
두 정수 A와 B... |
58ddd3560e1c090ae6f492ea9d3b73810b8e9eaf | Kwon1995-2/BC_Python | /chapter7/myModule.py | 312 | 3.984375 | 4 | # def sum(n):
# sum = 0
# for i in range(1, n + 1):
# sum += i
# return sum
# def power(x, n):
# prod = 1
# for i in range(1, n + 1):
# prod = prod * x
# return prod
# if __name__ == '__main__':
# print('{0}'.format(__name__))
# print(sum(5))
# print(power(5,2))
|
63d53595ccb1f9e58e4bbf34f0d88d885ad41698 | aiifabbf/leetcode-memo | /941.py | 1,160 | 3.8125 | 4 | """
判断是否存在一个 :math:`i, 0 < i < n - 1` 使得长度为n - 1的array满足
.. math::
\left\{\begin{aligned}
a_0 < a_1 < ... < a_i \\
a_i > a_{i + 1} > ... > a_{n - 1} \\
\end{aligned}\right.
直观上来说就是判断一个array里面的值从左往右是否形成了一个峰。
"""
from typing import *
class Solution:
def validMountainArray(self, A: List[in... |
15dbe3ed9061f88958789cf66972cd075aca2e42 | zichenchenzcc/Sudoku-Solver | /Sudoku Solver.py | 7,641 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 19:05:33 2020
@author: czc
"""
#The structure of the dic_up is:
#{Index,(Index before ranking,[(Sudoku coordinate),Index of chosen number in available number list,Condition,Length of available number list,Index of last step])}
import numpy as np
#Give... |
de3961e72a774b1e04fed0f7d073703d3911055d | CSA-CWW/Repository | /Repository.py | 1,050 | 3.828125 | 4 | #Cameron Watts#
#11 9 17#
#Comp Sci 2017#
somethingss = 2332958532982340982094803498423
def letter_count():
while True:
word=input("Wut word?").lower()
print ("")
letter = input("What letter to count?").lower()
count = 0
for x in word:
if x == letter:
... |
421673b18480123ade28ba68a0d35395f5c052c5 | momentum-cohort-2018-10/w2d3-pig-RDavis2005 | /pig.py | 2,520 | 3.984375 | 4 | import random
class Dice:
def __init__(self, side, number):
self.side = side
self.numbers = number
def __str__(self):
return "f{self.side}"
def __eq__(self, other):
return self.side == other.side
def roll(self):
"""rolls the dice and turns up a number """
... |
7b6ec29362d0001750f653ad56dbd655e2e4c761 | emergent/ProjectEuler | /Python/problem009.py | 773 | 3.65625 | 4 | #! /usr/bin/env python3
"""
Problem 9 - Project Euler
http://projecteuler.net/index.php?section=problems&id=9
"""
import math
def getPythagoreanTriplet(a):
for b in reversed(range(1, a)):
c = math.sqrt(a**2 - b**2)
if c.is_integer():
return (a, b, int(c))
else:
return (0, 0... |
296bda7e014db33834905ace5b3568a381bc7c39 | Tkod1/timepunch | /1.1.py | 1,288 | 3.828125 | 4 | import time
import sqlite3
print("Hello welcome to Time punch!")
time.sleep(1.5)
print("Are you a (n)New or (e)Existing user?")
member_choice = input()
def new_user():
try:
n_user_name = input("New Username: ")
n_user_password = input("New Password: ")
conn = sqlite3.connect('temp.db')
... |
08122b53866499c942667643633edd1c7d2f6a3a | tim-clifford/py-cipher | /src/dictionary.py | 2,788 | 4.03125 | 4 | '''
A few common functions for checking possible solutions
Functionality:
- Recursively check against a scrabble dictionary and list of one letter words and return a Boolean and the decrypted cipher
Sample Usage:
>>> from cipher import dictionary
>>> dictionary.filterIgnoreSpace(lambda x, a, b: a*(x - b), <affine ci... |
41f00355980f5802a34b200c699ae909771681c6 | kawai-yusuke/class_review | /b_2.py | 614 | 3.84375 | 4 | class Customer:
def __init__(self, first_name, family_name, age):
self.first_name = first_name
self.family_name = family_name
self.toshi = age
def full_name(self):
print(f"{self.first_name} {self.family_name}")
def age(self):
print(self.toshi)
ken = Customer(first... |
ddee3bbf33277c543808845ed85e97516414bd60 | stevecatt/digitalwk2 | /test.py | 536 | 4.03125 | 4 | class Address:
def __init__(self,street,city,state):
self.steet = street
self.city = city
self.state = state
class User:
def __init__(self,first_name, last_name):
self.first_name = first_name
self.last_name = last_name
# list of addresses
self.addresses =... |
0fbd26604402f1fc47d2e098dac76d5c97225d6d | gariepyt/cs325_project1 | /divide_conquer_example.py | 2,381 | 3.703125 | 4 | #divide and conquer solution for max subarray
#Written by Will Thomas
import time
import os
import csv
import sys
# Used for algorithm #3, returns larges sum found between two arrays
def maxMiddleSum(array, low, mid, high):
# Calculate max subarray on left side of current array
sum = 0
leftSum = 0... |
db7c76daddf6d8a95014419f4ebacca42955934e | Sepulveda25/python | /09-list/16-list-as-queues.py | 746 | 4.1875 | 4 | #Using Lists as Queues
from collections import deque
color_list = deque(["Red", "Blue", "Green", "Black"])
color_list.append("White") # White arrive
print(color_list)
# deque(['Red', 'Blue', 'Green', 'Black', 'White'])
color_list.append("Yellow") # Yellow arrive
print(color_list)
#deque(['Red', 'Blue', 'Green'... |
49558e140a3f48f8990fca8e0d49f1c932d9dc5b | JamieMagee/ProjectEuler | /python/041.py | 536 | 3.8125 | 4 | from itertools import permutations
def isprime(n):
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
r = int(n ** 0.5)
f = 5
while f <= r:
if n % f == 0:
return False
... |
a00661a69b53cdc1e59837c4344ed15b31732080 | jjmuesesq/ALGORITMOS_2018-1 | /LABORATORIOS/LAB1/punto 3/MatrizPython/MultiMatriz.py | 2,053 | 3.65625 | 4 | """
@author: Jairo
"""
import time
import sys
start_time = time.time()
# INICIALIZAR MATRIZ DE (nxm)
def inicializar_mtx(n, m):
tmp = []
for i in range (n):
tmp.append([0]*(m))
return tmp
# IMPRIMIR UNA MATRIZ
def print_mtx(m):
for i in range(len(m)):
print(m[i])
# MULTIPLICA ... |
a5aaf8ea18ddb682b06978c8e3114f2eeb319df4 | pranayagayitri/python-git-project | /main1.py | 62 | 3.640625 | 4 | m=5
n=6
if("n>m"):
print("n is big")
else:
print("m is big") |
52ab0c8139e4dfb80cf251cb4ed35efd1d56b498 | guohaoyuan/algorithms-for-work | /leetcode/高频面试/labuladong统计的高频面试题/268. 缺失数字 easy/missingNumber.py | 424 | 3.578125 | 4 | """
自身^自身=0
0^自身=自身
n是数组的length,我们初始化res = n
然后整个数组的index^数组每一个元素后^n
最后res剩下的数就是结果
"""
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
res = n
for i in range(n):
res ^= i ^ nums[i]
... |
70fd3daa46a392a692a6ef6900593af50a696f6b | diegojserrano/ISSD_Python | /Clase6/Equipo.py | 1,259 | 3.8125 | 4 | class Equipo:
def __init__(self, nombre):
self.nombre = nombre
self.jugados = 0
self.ganados = 0
self.empatados = 0
self.goles_recibidos = 0
self.goles_realizados = 0
def perdidos(self):
return self.jugados - self.ganados - self.empatados
def difere... |
5d25a05321907b3f9d81ca94a8efa6295a155ade | Alireza-Helali/Design-Patterns | /FactoryMethod.py | 1,573 | 4.5625 | 5 | """
Factory method:
factory method is a creational design pattern
that provides an interface for creating an object
in superclass but allows subclasses to alter the
type of objects that will be created. it's a simply
a method that creates an object.
"""
from enum import Enum
fro... |
dce37eab83f5abc61700f57ef16fa7daa4ea1cd4 | jpromanonet/facultad_Programacion_TallerIntegrador | /02_Ejercicios_Resueltos/ejercicio_02_07.py | 484 | 3.609375 | 4 | lista = []
contador = 0
palabra = ''
print('Ingrese 10 palabras de a una por vez \n')
while contador < 10 :
palabra = input('ingrese palabra : ')
lista.append(palabra)
contador = contador + 1
Ultimapalabra = input('ingrese una ultima palabra: ')
if lista.count(Ultimapalabra) == 0 :
print('La palabra... |
5a8644af6dcb7fec954922c7d74a3e7f4e1b209d | Deanhz/normal_works | /算法题/Leetcode/easy/Reverse_Integer.py | 1,104 | 3.96875 | 4 | '''
7.
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer.
Your function should return 0 when the reversed integer overflows.
'''
class Solution(object):
def reverse(self, x): # by me
'''
:type x: ... |
73ba13da44056d236c1cf7a3bb07380d7943d1f7 | snow-sam/Cadastro-e-Importa-o | /Database.py | 669 | 3.890625 | 4 | import sqlite3
# Função para criar o Banco de Dados
def createDB():
db = sqlite3.connect('Ativos.db')
cs = db.cursor()
cs.execute(""" CREATE TABLE ativos (
simbolo TEXT NOT NULL PRIMARY KEY,
nome TEXT NOT NULL,
habilitado NUMBER NOT NULL
)""")
cs.exe... |
1bae80075f9e9e6906fc93be608d1da664df5f2e | tuobulatuo/Leetcode | /src/ltree/uniqueBinarySearchTrees.py | 1,016 | 3.796875 | 4 | __author__ = 'hanxuan'
"""
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ ... |
bbe36d7093a69d701447be275c5e4d2c616bbcc7 | yvan674/minimal-mnist | /src/model/numpy_model.py | 2,679 | 3.90625 | 4 | """Numpy Model.
The model as a series of numpy operations.
"""
import numpy as np
class Linear:
def __init__(self, in_connections, out_connections):
"""A simple linear layer."""
self.weight = np.zeros([out_connections, in_connections])
self.bias = np.zeros([out_connections])
self.... |
354517a92eb55bcc4482385e085689ea816046f2 | holmes27/open_cv | /drawing_functions.py | 748 | 3.53125 | 4 | import cv2
import numpy as np
#img=cv2.imread('lena.jpg',1)
img=np.zeros([512,512,3],np.uint8)# creating black image using np zeros method -[ height,width,3] , data type
img=cv2.line(img,(0,0),(255,255),(147,44,94),6) # image,start, end,(b,g,r) ,thickness
img=cv2.arrowedLine(img,(255,0),(255,255),(255,0,94),6)
img=c... |
d54a08168bef837e896f97e093efc582278acd5f | gaolinagproject/open_watch | /ESP32_python_pro/workSpace/testScript.py | 1,359 | 3.5625 | 4 | """
import _thread
import time
def test3Thread(description,count):
print(description)
i = 0
while i < count:
print("nihao"+str(i))
i = i+1
time.sleep(2)
_thread.start_new_thread(test3Thread,("wfgz",5))
"""
"""
import machine
interruptsCounter = 0
totalInterruptsCounter = 0
timer = machine.Timer(... |
8ef292a851897bd2c28db8dad01509a151cad581 | staccato007/Spectrum-high | /PHpackage/input_.py | 857 | 3.640625 | 4 | def check_file_input_func(filepath):
#print('1 ', filepath)
filepath = repr(filepath) #转换为python字符串,忽略转义字符
#print('2 ', filepath)
filepath = filepath.replace('\\', '/') #替换反斜杠'\'
#print('3 ', filepath)
filepath = eval(filepath) #转换为普通字符串
#print('4 ', filepath)
filepath = filepath.rstrip(... |
6a8670f245dd6a02ff0ca60840ab467051f2d8bf | AthinaKyriakou/mrbox | /utils/path_util.py | 275 | 3.515625 | 4 | import os
def customize_path(folder_path, filename):
return os.path.join(folder_path, filename)
def remove_prefix(prefix, filepath):
prefix = customize_path(prefix, '')
if filepath.startswith(prefix):
return filepath[len(prefix):]
return filepath
|
dc06731bc314cab3b962b7007ed1549dc603b378 | taufikfathurahman/DS_python | /Linked List/linkedListDeletion1.py | 1,475 | 4.28125 | 4 | # Node class
class Node:
# Consructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the begining
def push(self, new_data):
new_node = Node... |
1adbc681c308152ce77ec354f0ea75ce2873cd16 | yunusemrebaloglu/pyornekleri | /ders2/ikincidersilkkonu.py | 2,853 | 4.25 | 4 | """
a = True
print(a)
#tru
print(type(a))
#bool
print(1<0)
#false
print(0==0)
#true
b = None
print(b)
#none
print("AB'=2018"=="sad")
#false
print("e">"w")
#alfabetik sıralama için yapılabilir.
print(True < False)
#false döner
print(1>0 and "Murat"=="Murat")
#true
print(1>2 and "Murat"=="Murat")
#false
print(1>2 or "M... |
55d26dd6175764751871a32f464bfe9115f20b73 | EstevamPonte/Python-Basico | /PythonExercicios/mundo1/ex013.py | 111 | 3.5625 | 4 | n1 = int(input('Digite o aumento: '))
n2 = (n1 * 15)/100
print('Seu aumeento vai ficar por {}'.format(n1 + n2)) |
3663027cdd48c3abf79e280cf043c8df6d510b2e | billzxy/8PuzzleSolver | /project1.py | 7,337 | 3.875 | 4 | import sys
from copy import deepcopy
DIRECTIONS=[{1:"R",3:"D"}, # A list of dictionary, index of the list is the position of zero on the puzzle(Because only zero on the puzzle
{0:"L",2:"R",4:"D"}, # is allowed to perform a move). The position of zero has only limited directions to move... |
42d37ae7e837cac8881e5041c972bcac0f825f98 | number09/atcoder | /abc077-a.py | 174 | 3.765625 | 4 | array1 = [a for a in input()]
array2 = [b for b in input()]
ar = [array1, array2]
r_array1 = array1[::-1]
if array2 == r_array1:
print("YES")
else:
print("NO")
|
bd1e95330e4c5e86328f3df9c99ac92ecc1a4d99 | vishsangale/codeKatas | /legacy_katas/data_structures/doubly_linked_list.py | 2,198 | 4.03125 | 4 | """Implementation of doubly linked list."""
import unittest
class DoublyLLNode(object):
def __init__(self, item, next=None, prev=None):
self.val = item
self.next = next
self.prev = prev
class DoublyLinkedList(object):
def __init__(self):
self.head = None
def find(self, ... |
d299e64f60410e0e5f5281e0386efe67d137ca7e | suyundukov/LIFAP1 | /TD/TD7/Code/Python/7.py | 539 | 3.546875 | 4 | #!/usr/bin/python
# Remplir un tableau avec les coefficients du triangle de Pascal
from math import factorial as fact
def combin(n, p):
res = int(fact(n) / (fact(p) * fact(n - p)))
return res
def triangle_pascal(tab):
for i in range(len(tab)):
for j in range(i + 1):
tab[i][j] = combi... |
7a10c9601276cef6fe9c4410d053991be34645bd | arthurDz/algorithm-studies | /leetcode/linked_list_cycle.py | 778 | 4.0625 | 4 | # Given a linked list, determine if it has a cycle in it.
# To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
# Example 1:
# Input: head = [3,2,0,-4], po... |
e9cec1dd84c6484febd89d91f9597d0e14ce4e3c | ms-shakil/RegExp | /regexp_compile.py | 399 | 3.734375 | 4 | import re
text = "This is line . Date is 2021/02/21. And theres is another date: 2021-03-21. The Third and final dae is 2022/05/22."
date = re.compile(r"\d{4}[-/]\d{2}[-/]\d{2}") # complile regexp
result = date.findall(text)
print(result)
### american number verifiction with using compile
num = "415-555-4242"
number =... |
1e9338b4e4f4504d4d5b0385ad072dc1c2b57f1a | amirhadi3/HackerRank | /9_stairCase.py | 185 | 3.96875 | 4 | def staircase(n):
for i in range(1, n + 1):
print(f'%{n - i}s' % '', end='')
for j in range(1, i + 1):
print('#', end='')
print()
staircase(6)
|
ca763d4c9ec8b153a7d3c7b7d912d63cd0ee8262 | aaron-goshine/python-scratch-pad | /workout/two_word_random_password.py | 1,124 | 4.15625 | 4 | ##
# Generate a password by Concatenating two random words.
# The password will be between 8 and characters, and each word
# will be at least three letters long.
#
from random import randrange
WORD_FILE = "/usr/share/dict/words"
# Read all of the words from the files,
# only keeping those that are between 3 and 7
# ... |
5061551680e1ab63fd3312fc27752a5841f007c7 | anmolsingh8823000/yobro | /imports.py | 553 | 3.828125 | 4 | import random
def prefRandOut(list):
#initialising sum variable
sum = 0
#calculating the sum cumulative priorities of
for row in list:
sum = sum + row[1] #calculating sum of priorities
row.append(sum) #calculating cumulative priorities
#getting random float between 0 and the sum
r = random.unifor... |
11bf41e58672f2b1e635270f7bee85e26c6b93fa | Sveto4ek/Python_hw | /Homework_02.py | 6,768 | 3.90625 | 4 | # 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки
# типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка
# можно не запрашивать у пользователя, а указать явно, в программе.
# my_list = [50, 'word', 4.6, [5, 9], {56, 22}, {'age': 10... |
f9762dcf16eacaf244f0159118e491e2f34c48a5 | yymin1022/CAU-Computational-Thinking-and-Problem-Solving-Assignment1 | /문제1.py | 505 | 3.65625 | 4 | while 1:
inputNum = int(input('숫자를 입력하세요 : '))
if inputNum == 0:
print('프로그램을 종료합니다.')
break
elif inputNum < 0:
# 입력된 값이 음수인 경우, -1을 곱해 그 절대값을 출력
print('입력된 숫자의 음수이며, 절대값은 %d입니다.' %(inputNum * -1))
elif inputNum > 0:
# 입력된 값이 양수인 경우, 그대로 출력
print('입력된 숫자... |
2600e284398562154ef53404819ed23a4f47a9d8 | adanfernandez/python-MUD | /src/command/Comprar.py | 2,027 | 3.875 | 4 | class Comprar_cura:
"""Compra de cura"""
def execute(self, jugador):
jugador.incrementar_objetos('cura')
precio_cura = list(filter(lambda x: isinstance(x, Cura), jugador.objetos_tienda))[0].precio
jugador.recargar_dinero(precio_cura * -1)
print("{} ha comprado una cura\n\n".forma... |
ba71984f70432bdc9e9d20da070d70129cf8aa9f | ryangillard/misc | /leetcode/365_water_and_jug_problem/365_water_and_jug_problem.py | 1,909 | 3.53125 | 4 | class Solution(object):
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
# Quick return
if x == z or y == z or x + y == z:
return True
# Find smaller and larger buckets
if x <=... |
38de7e22ef2f1867ffbf89d02124a0bb2aed9bcc | LeeKyuHyuk/leekyuhyuk.github.io-backup | /assets/file/2015-09-25-python_assignment3.py | 114 | 3.609375 | 4 | table = input()
num = 1
while num < 10:
print str(table) + ' x ' + str(num) + ' = ' + str(table * num)
num += 1
|
96bd8c15192f57c417e77e2c06e6775ab5c0b46f | jamwomsoo/Algorithm_prac | /dynamic_programming/백준/실버/피보나치함수_백준.py | 276 | 3.578125 | 4 | i# 메모리를 필요한만큼만....
def func(x):
one = [0,1]
zero = [1,0]
for i in range(2,x+1):
zero.append(zero[-1]+zero[-2])
one.append(one[-1]+one[-2])
print(zero[x],one[x])
for _ in range(int(input())):
n = int(input())
func(n) |
dd4801389db23386ced9b783b1e0f29db824be4b | yunussevin/Python | /input.py | 167 | 3.515625 | 4 | isim = input("İsminiz Nedir?\n",)
yaş = input("Yaşınızı öğrenebilir miyim?\n")
print("Merhaba", isim, end="!\n")
print("Demek", yaş,"yaşındasın...", end="!\n")
|
374d6260b906c523b6dae9fcb483af6924ea17b9 | cvam0000/hackerRank.pyhton.problems- | /listcomp.py | 336 | 3.9375 | 4 | x = int(input())
y = int(input())
z = int(input())
n = int(input())
list_in=[]
insert i e: Insert integer at position
.
print: Print the list.
remove e: Delete the first occurrence of integer
.
append e: Insert integer
at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Re... |
9d974a2303335e4416411a7b8f145edc5d7b7d21 | AmbujaAK/practice | /python/ShortestToChar.py | 1,069 | 3.671875 | 4 | def shortestToChar(S,C):
l = []
ci = S.find(C)
for i in range(len(S)):
print("string now is : " , S[i:])
print("find e : ",S[i:].find(C))
if i > ci and S[i:].find(C) >= ci :
ci = S[i:].find(C)
print('i :',i)
print("ci : ",ci)
ele = abs(ci-i... |
f9daa682a17957acae1dc1f69d7a41f0edffbf60 | symbooo/LeetCodeSymb | /demo/24.SwapNodesInPairs.py | 2,528 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
YES, WE CAN!
@Time : 2018/8/31 1:13
@Author : 兰兴宝 echolan@126.com
@File : 24.SwapNodesInPairs.py
@Site :
@Project : LeetCodeSymb
@Note : [describe how to use it]
"""
# Enjoy Your Code
class Solution:
"""
输入一个链表,每隔两个数交换一次。不允... |
2f245fc690bd54ab1d97ef095f3ced930a637f59 | samby5/dataengineering | /PreWork_python-ds-practice/27_titleize/titleize.py | 418 | 3.953125 | 4 | def titleize(phrase):
"""Return phrase in title case (each word capitalized).
>>> titleize('this is awesome')
'This Is Awesome'
>>> titleize('oNLy cAPITALIZe fIRSt')
'Only Capitalize First'
"""
nl = phrase.split(' ')
o=[]
for i in nl:
o.append(i[0].upper()+i[... |
ec12805c3627762025ed3061d16f3635af979057 | shaoqiongchan/Dynamic-Programming | /PriorityQueueDijkstra.py | 1,075 | 3.75 | 4 | import heapq
graph_dict = {'A': {'B': 5, 'C': 1},
'B': {'A': 5, 'C': 2, 'D': 1},
'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8},
'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6},
'E': {'C': 8, 'D': 3},
'F': {'D': 3},
}
def dijkstra(graph, s):... |
2ac1acf7deef80d25c68236d0f8fa9122793c9e5 | KellyPared/student_daniella | /main.py | 14,831 | 4.1875 | 4 | '''This is code written by a 6th grader. This student has had 4 weeks of coding. The assignment was to use:
loops, conditionals, input, f-strings and good variable names. There was no code limit.'''
while True:
title = "Life Simulator".center(50, "-")
print(title)
print("Welcome to life simulator.")
... |
4eb82d66e4db4a1defcc42b6e6493ac4d6a4639d | matias18233/practicas_python | /entregable_8/trabajo_final.py | 10,951 | 3.6875 | 4 | # Nombre: Fernando Matías
# Apellido: Cruz
# Comisión: 1
from random import randrange
# Permite obtener un número de ID único (en un rango que va del 0 al 100)
def obtenerIndice():
global productos
control = False
while control == False:
indice = randrange(100)
repetido = False
if ... |
37a9a2104ff27c590261f6461c175ae4e9923682 | cholu6768/Voting-Poll | /Voting_poll/voting.py | 1,782 | 3.796875 | 4 | import random
#These were some candidates in Mexico
candidates = ["AMLO", "Peña","Bronco","Calderon","Fox"]
school_1 = []
school_2 = []
school_3 = []
school_4 = []
school_5 = []
votes = []
#Inserting the votes in the lists of the schools
for vote in range(5):
num = random.randint(20, 100)
school_1... |
d0148659feed69b27869c2caaf5c70a1f763477e | rvrn2hdp/informatorio2020 | /FuncionesComp/ejemploclosure.py | 1,509 | 4.1875 | 4 | # Closures()
# Se utiliza para que una función genere dinámicamente otra función y que esta nueva función
# pueda acceder a las variables locales aun cuando la función haya terminado
# Se utiliza para evitar el uso de variables globales y proporcionan alguna forma de ocultar datos.
# Se usan en conjunto con los decora... |
ea0e43009430b046f9583c5fa7de128c949295a6 | TheDesTrucToRR/Hacktoberfest-2021 | /Python/find_the_number_of_ways.py | 1,124 | 3.8125 | 4 | '''
A man has money/coins in two different bags. He visits the market to buy some items.
Bag A has N coins and Bag B has M coins. The denominations of the money are given as
array elements in a[] and b[]. He can buy products only by paying an amount which is
an even number by choosing money from both the bags. The task... |
ac73f1d6234175f04e74dbab1f1d3cfa7636436a | Gabi240400/car-service | /Domain/ValidateCard.py | 4,203 | 3.5625 | 4 | from Domain.CardCustomer import Card
from Exceptions.InvalidCNP import InvalidCNPException
from Exceptions.CardError import InvalidCustomerCardException
class CustomerCardValidator:
@staticmethod
def validate_customer_card(customer_card: Card):
"""
Function verify if an object respect... |
bf18ea472fd33162217b398e605224d6c30a958c | EricKoegel/learningpython | /Test/com/PracticeWork/fibonacci_sequence.py | 345 | 4.09375 | 4 | '''
Created on Feb 29, 2016
@author: michael.f.koegel
The entire purpose of this project
is to perform the fibonacci
sequence and practice skills
'''
#n = input("Please enter the sequence 'nth' value: ")
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) +... |
3e72f1af030d335778211f22bea01b9451bc6e21 | EDDchris2017/IAPractica1_Lopez201504100 | /src/algoritmo/Finalizacion.py | 2,392 | 3.515625 | 4 | from statistics import mode
class Finalizacion:
def __init__(self):
self.porcentaje = 65 # Criterio de porcentaje ( Criterio 1)
self.maximo_gen = 700 # Maximo de generaciones ( Criterio 2)
def verificarCriterio(self, criterio, poblacion, generacion):
result = None
... |
0fb206e7e13d76ebc30180c0cc19381d9e582c28 | GMTrends/Python-Projects | /Python & PHP Files/Python/Read & Write file using SenseHat sensors/read_sensehat_data_random.py | 1,746 | 3.546875 | 4 | # read_sensehat_data_random.py
# sense_file.seek(0) <-- bytes of offset (location in the file)
# sense_file.tell() <-- location of the file pointer
# line_str = sense_file.readline() <-- reads one line at a time
from sense_hat import SenseHat
from time import sleep,time,ctime #ctime converts time to more readable for... |
7df01aea22a4b423b4ceb29e332234af5c733be1 | ravalrupalj/BrainTeasers | /Edabit/Sort_List_by_String_Length.py | 647 | 4.125 | 4 | #Sort a List by String Length
#Create a function that takes a list of strings and return a list, sorted from shortest to longest.
#All test cases contain lists with strings of different lengths, so you won't have to deal with multiple strings of the same length.
def sort_by_length(lst):
t= sorted(lst,key=len)
r... |
a0ae865182802ac5ab975a1dd228c349f7c76f0c | ngdeva99/Fulcrum | /Valid Parentheses.py | 517 | 3.78125 | 4 | class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
left = ['(', '{', '[']
right = [')', '}', ']']
stack = []
for letter in s:
if letter in left:
stack.append(letter)
elif letter in right:
... |
15b68baa72d48f6d0ddb25af69c33d5c5ea7033d | su-maxlee/Bioinfo09 | /W3/0705.py | 1,715 | 4.3125 | 4 | #! /usr/bin/env python
'''
#나중에 한번봐보자
a= 11
if (b:=a)>10:
print(f'the value of b is {b} and is greater than 10.')
'''
'''
#2 Variable my answer
import math
r=float(input('insert radius: '))
area= (r**2)*math.pi
print(f'The area of a circle with a radius of {r} is:',area)
'''
'''
#2 Variable t.answer
import math... |
cbf18b7f7e8c22c4806a613afb7ba33fe5576908 | pablot30/misiontic-2022 | /ciclo-1/cc_unaleño.py | 967 | 3.71875 | 4 | # Laboratorio de Pruebas - Semana 1-2
# Tema: Centro Comercial Unaleño
# Autor: Pablo Jose Torres Mojica
def get_product_details():
product_name = input()
unit_cost = abs(int(input()))
retail_price = abs(int(input())) # precio de venta al público
stock = abs(int(input()))
return {'Produ... |
e575a9a565a3eb2e683c92540b2f582c09578176 | aoeuidht/homework | /leetcode/313.SuperUglyNumber.py | 1,105 | 3.578125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
if not primes:
return 1
ugly_list = [1]
# in the heapq,... |
ba06bf292bed66a06a177cbf9318ce9becd6ffd8 | roblivesinottawa/OOP | /OOP/user_methods.py | 721 | 4 | 4 | # A User class with both instance attributes and instance methods
class User:
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def full_name(self):
return f"{self.first} {self.last}"
def country(self, origin):
return f"{self.first} is from {origin}"
def inter... |
f7932d6a7004798fd1192fe0c2bea962e36e9efc | Hassan-Farid/PyTech-Review | /Computer Vision/Image Processing using OpenCV/Image Gradients/Scharr Gradient.py | 543 | 3.53125 | 4 | import cv2
import numpy as np
#Reading image from the Images folder
img = cv2.imread('.\Images\grid.jpg')
#Configuring settings for applying Scharr gradient
ksize = -1
ddepth = -1
#Applying scharr gradient on the image
x_sobel = cv2.Sobel(img, ddepth, dx=1, dy=0, ksize=ksize)
y_sobel = cv2.Sobel(img, ddepth, dx=0, d... |
f494119893fbf022b5201d7a5cd039487e22a0b5 | asiftandel96/Object-Oriented-Programming | /Exception_Handling/Basics.py | 1,256 | 3.96875 | 4 | """Basic Example of Exception Handling"""
"""
class Ex_Operation:
def __init__(self, a, b):
try:
self.a = a
self.b = b
self.result = self.a / self.b
if self.result > 5:
print('The result is good')
elif self.result == 5:
... |
5a503a2b1f713f28b68ba168085101f89372deb5 | syeluru/MIS304 | /ExceptionHandler2.py | 1,155 | 3.9375 | 4 | # Program to process exceptions using functions
def main():
total_score = 0.0
scores_str = input("Enter numbers separated by spaces: ")
scores_list = scores_str.split()
print (scores_list)
try:
total_score = computeTotal(scores_list)
print (total_score)
except ValueError:
... |
f0737930d9272d721e8435b05000b2347c2c9fed | enriavil1/caculator | /calcultator.py | 3,712 | 3.84375 | 4 | from tkinter import *
root = Tk()
root.title("Calculator")
input_box = Entry(root, width = 50, borderwidth = 5)
input_box.grid(row = 0, column = 0, columnspan = 3, padx = 10, pady = 10)
def click(num):
box = input_box.get()
box += str(num)
input_box.delete(0, END)
input_box.insert(0, box)
def clear... |
9d9bdcb6531ce7275b14fc8b121440d38a12ee1b | craighillelson/daily_focus | /functions.py | 2,351 | 4 | 4 | """Functions."""
import csv
import datetime
from datetime import datetime
from datetime import (date,
timedelta)
import pyinputplus as pyip
target_date = date(2021, 8, 7)
todays_date = date.today()
date_tasks_to_add = {}
dates_tasks = {}
def days_out(num_days):
"""Find the date a given num... |
7458088428173f0761f53adc067d69e7e53b0fdb | nobodywhocares/hackerrank-hokum-py | /sorting.py | 12,211 | 4.4375 | 4 | def print_sorted(alg, a):
print(f"Printing {alg} Sorted Element List...")
for i in a:
print(i)
# Counting Sort:
#
# It is a sorting technique based on the keys i.e. objects are collected according to keys which are small integers.
# Counting sort calculates the number of occurrence of objects and stor... |
c83146bf42bfc3036eb59359f040e3526f46967c | RandoNandoz/computer-science-11 | /nestedloops.py | 472 | 4.09375 | 4 | """
Randy Zhu
11-03-2020
Nested loops
"""
# for index in range(1, 4):
# for length in range(-3, 0):
# print(index, length)
# last_number = 6
# for row in range(1, last_number):
# for column in range(1, row + 1):
# print(column, end=' ')
# print("")
# import turtle
# my_... |
0da57bb50cdf9f5ee91c4e3fd4fd64156b76283c | hejnal/code-retreat-prep | /testing-python/tests/test_sum_unittest.py | 248 | 3.65625 | 4 | #!/usr/bin/env python
import unittest
class TestSum(unittest.TestCase):
def testSum(self):
self.assertEqual(sum([1, 2, 3]), 6, "should be 6")
def testSumTuple(self):
self.assertEqual(sum((1, 2, 3)), 6, "should be 6") |
70d756f8c425c1a069b4b5b10c746c30e4124614 | GouravSardana/chaoss-microtask | /microtask3.py | 1,140 | 3.578125 | 4 | import urllib.request, json
import csv
#https://api.github.com/repos/aimacode/aima-python/contributors (know about the contributors)
d={} #save all the required name and contribution in dict. form
with urllib.request.urlopen("https://api.github.com/repos/aimacode/aima-python/contributors") as url:
#open the link us... |
6edd7fc99f8408acecdd7309b2416fa89027bfa1 | nvanalfen/SudokuPuzzle | /Box.py | 1,212 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 01:30:57 2018
@author: nvana
"""
# Class used to represent a single box on a Sudoku grid that holds one number
class Box:
def __init__(self):
self.solved = False
self.value = 0
self.remaining = 1
self.possibilities = se... |
6f9d33ee2df7ba91a628d7a288b0b7a9f29b0a04 | hwangse/python-A-to-Z | /3_variable_prac.py | 550 | 4.1875 | 4 | a=123.456789
print(int(a),float(a))
print()
b=3.14
b=str(b)
print(b,type(b))
b=int(float(b))
print(b,type(b))
b=float(b)
print(b,type(b))
print()
name,num,age=input("Enter 3 things : ").split()
print(name,num,age)
print()
age=int(age)
print("♥"*age)
print()
degree=float(input("본 프로그램은 섭씨를 화씨로 변환해주는 프로그램입니다\n\
변환하고 싶은 ... |
7d3fa79cb95f79e6a8795d1a5415b9d3bc504b04 | aswathysoman97/LuminarPython | /pythondjangojuneclass/dob.py | 124 | 3.65625 | 4 | dob=input("birth year dd-mm-yy: ")
byr=dob.split("-")
today=int(input("recent year:"))
age=(today-int (byr[2]))
print(age)
|
48df38223667323269642ed9cce27e3fcfc4d5e0 | Benature/Computational-Physics-Course-Code | /chp8/波动方程/二阶差分_波动_总矩阵.py | 1,743 | 3.5 | 4 | # 二阶差分格式解法,使用一个数组u保存所有计算步骤结果.
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import math
# %matplotlib notebook
# fixed parameters
c = 1.0 # speed of propagation, m/s
L = 1.0 # length of wire, m
# input parameters
alpha = 1.0 # 库兰特数
dx = 0.02
dt = 0.02
tmax = L/c*1.2
s... |
f396cc089d241ed29488b916faddee29ecd2ad81 | codernoobi/python | /Python/introduction/strings.py | 502 | 4.1875 | 4 | txt=" Hello, world"
print(len(txt)) #string length
x=txt[1] #character in the index
print(x)
x=txt[2:4] #substring
print(x)
print(txt.strip()) #trim spaces
print(txt.upper()) #to upper case
print(txt.lower()) #to lower case
print(txt.replace("H","j")) #to replace
print(txt.split("e")) #splits at e
txt = "H... |
9d7a87ef2ae41caa73e83ce764e01e5edaaeaca5 | krab1k/aoc2020 | /18/evaluate.py | 1,216 | 3.515625 | 4 | import string
def e(op, s, arg):
if op == '+':
s += arg
else:
s *= arg
return s
def evaluate_expression(expr):
s = None
op = None
arg = None
length = len(expr)
i = 0
while i < length:
c = expr[i]
i += 1
if c == ' ':
continue
... |
6a5ea6e155f1132b9b37096552b6ef469e2af6db | rekonin332/pGUi | /gui/GUI_Simple.py | 1,442 | 3.53125 | 4 | '''
Created on 2017年5月25日
@author: Todd
'''
import tkinter as tk
from tkinter import Menu
from tkinter import ttk # themed Tk
from textwrap import fill
from turtledemo.nim import Stick
#funtions
#exit GUI clearly
def _quit():
win.quit()
win.destroy()
exit()
win = tk.Tk()
win.title("Python Project... |
08780a9a9c1f8d9e0cf00a4e588766353c147d3b | Ryan-R-C/my_hundred_python_exercises | /Teoria/A21 2.py | 340 | 3.84375 | 4 | def somar(a=0,b=0,c=0):
s = a+b+c
return s
def par(n=0):
if n % 2 == 0:
return True
else:
return False
r1 = somar(3,2,5)
r2 = somar(2,2)
r3 = (6)
print(f"The results of the sums are {r1}, {r2} and {r3}.")
num = int(input("Type a num: "))
if par(num):
print("It's even!")
else:
... |
1dbe913d1d6b8d477f1d6c40ea37b2cd9b6cac0d | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/1f310aa87ffa4dfb92e4e614ac79f7a9.py | 371 | 3.765625 | 4 | # -*- coding: utf-8 -*
GENERAL_ANSWER = u'Whatever.'
QUESTION_ANSWER = u'Sure.'
YELL_ANSWER = u'Woah, chill out!'
EMPTY_ANSWER = u'Fine. Be that way!'
def hey(sentence):
if not sentence.strip():
return EMPTY_ANSWER
if sentence.isupper():
return YELL_ANSWER
if sentence.endswith('?'):
... |
b12285c6943c9db401b6fb7b646b4d1c330d1ea7 | sarathvad1811/ds_algo_prep | /basic_programs/number_reverse.py | 361 | 3.765625 | 4 | def num_reverse(num):
rev_num = 0
is_neg = num < 0
temp = num
mul = 1
if is_neg:
temp = abs(num)
mul = -1
while temp != 0:
rem = int(temp % 10)
rev_num = (rev_num * 10) + rem
# print(rem)
temp = int(temp / 10)
return mul * rev_num
print(nu... |
30d41c3f120bd72676e7f4bba528240413765457 | SaitejaP/InterviewBit | /arrays/maximum_unsorted_subarray.py | 1,505 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# You are given an array (zero indexed) of N non-negative integers, A0, A1, …, AN-1.
# Find the minimum sub array Al, Al+1, …, Ar so if we sort(in ascending order)
# that sub array, then the whole array should get sorted.
# If A is already sorted, output -1.
class Solution:
# @param A : li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.