blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
184bd819730beb12eb00b27747fd2b6bd750cc1d | parkerbxyz/exercism | /python/triangle/triangle.py | 1,329 | 4.40625 | 4 | """Determine if a triangle is equilateral, isosceles, or scalene."""
from typing import List
def is_triangle(sides: List[int]) -> bool:
"""Return True if the given side lengths form a triangle."""
return (len(sides) == 3 # has three side lengths
and all(s > 0 for s in sides) # all side lengths ... |
75e7bc7f0bede911108f223d399f92acfa41c2c2 | parkerbxyz/exercism | /python/resistor-color/resistor_color.py | 477 | 3.828125 | 4 | from typing import Dict, List
COLOR_CODE: Dict[str, int] = {
'black': 0,
'brown': 1,
'red': 2,
'orange': 3,
'yellow': 4,
'green': 5,
'blue': 6,
'violet': 7,
'grey': 8,
'white': 9
}
def color_code(color: str) -> int:
"""Return the significant digit of a given color."""
... |
ab8f58d583d3ce0efd7e1941e0a0e753f0c73d24 | parkerbxyz/exercism | /python/bank-account/bank_account.py | 1,310 | 3.65625 | 4 | from dataclasses import dataclass
from threading import Lock
@dataclass
class BankAccount:
active: bool = False
balance: int = 0
lock: object = Lock()
def get_balance(self):
with self.lock:
if not self.active:
raise ValueError("Cannot get balance of closed account.... |
d83b6c9fbc8b4e0cdcbd4a88b53beeabfa7775f1 | NehaKaranjkar/IIoT_RBCCPS | /model_2/ScreenPrinter.py | 7,132 | 3.578125 | 4 | # ScreenPrinter.py
#
# The ScreenPrinter performs printing, one PCB at a time.
# Each PCB consumes a certain amount of solder and adhesive
# and incurs a certain amount of delay.
# When the solder or adhesive levels falls below a certain threshold,
# a human operator is informed and the printing is paused
#... |
40b3393b01e45e121264850a96ad4767fa0cb896 | victoriasof/python-codility-lessons | /Lesson 10.Prime and composite numbers/count_factors.py | 1,010 | 3.953125 | 4 | """
A positive integer D is a factor of a positive integer N
if there exists an integer M such that N = D * M.
For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4).
Write a function:
def solution(N)
that, given a positive integer N, returns the number of its factors.
For... |
5a61c1b6758c024562538dfa839357209fb7652a | victoriasof/python-codility-lessons | /Lesson 06.Sorting/max_product_of_three.py | 1,310 | 4.4375 | 4 | """
A non-empty array A consisting of N integers is given.
...
For example, array A such that:
A[0] = -3
A[1] = 1
A[2] = 2
A[3] = -2
A[4] = 5
A[5] = 6
contains the following example triplets:
...
(1, 2, 4), product is 1 * 2 * 5 = 10
(2, 4, 5), product is 2 * 5 * 6 = 60
Your goal... |
849dd7199eb1fa7d9c4c5720518fae14a71e2f67 | victoriasof/python-codility-lessons | /Lesson 14.Binary search algorithm/nailing_planks.py | 5,459 | 3.921875 | 4 | """
You are given two non-empty arrays A and B consisting of N integers.
These arrays represent N planks.
More precisely, A[K] is the start and B[K] the end of the K-th plank.
Next, you are given a non-empty array C consisting of M integers.
This array represents M nails.
More precisely, C[I] is the position where... |
de0e99551f4931d6b4b04dfef0d4c53f6b6f35e8 | victoriasof/python-codility-lessons | /Lesson 04.Counting Elements/missing_integer.py | 670 | 3.71875 | 4 | """
This is a demo task.
Write a function:
def solution(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0)
that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
...
Wri... |
5c67cb772cdce2e00d8b013012bd139d53c596f4 | Menda0/python-fundamentals-12-2020 | /session6_inheritance.py | 894 | 4.03125 | 4 |
## Use animal class
## Super class
class Animal:
def __init__(self, name, type):
# print("Animal", name, "of type", type, "was created")
self.name = name
self.type = type
def noise(self):
return "Animal does not do noise"
def walks(self):
return "Animal does not ... |
bf15a39f2c623d6913d3e7681c51ae9e8d3b6139 | sharmila1999/Data_Structures_and_Algorithms | /Route planner/Route planner.py | 1,397 | 3.859375 | 4 | import math
from queue import PriorityQueue
#I used the idea in here- https://dbader.org/blog/priority-queues-in-python
#let the initial point be x
#let the destination point be y
@doc module 'shortest_path'
def shortest_path(graph, x, y):
pathQueue = PriorityQueue()
pathQueue.put(start, 0)
pre... |
b5898f18011a032ca1f7eb352d5bd41992dd611b | saurabhjain17/Polygon-area-calcultor_freecodecamp | /shape_calculator.py | 1,062 | 3.8125 | 4 | class Rectangle:
def __init__(self,width,height):
self.width=width
self.height=height
def __str__(self):
return f"Rectangle(width={self.width}, height={self.height})"
def set_width(self,width):
self.width=width
def set_height(self,height):
self.height=height
def get_area(self):
re... |
f6ea38ffb882805c6ffdee2b3487e8e88bc2d171 | penaguerrero/Ly_alpha | /src/OB_stars3.py | 12,045 | 3.75 | 4 | import numpy
import string
import table
import copy
from spectrum import spectrum
from spectrum import pyplot
'''
This program produces a table of temperatures and EQWs of O and B stars from the textfiles with the selected wavelength range: 1100 - 1300 A
from Pollux and Tlusty, respectively.
'''
def ec_VG93(Teff):
... |
7efb7b05da2bde215234ee985e0d3505bfa3b0ca | GuganA/Simple_Calculator_using_Python_tkinter | /calc.py | 3,447 | 3.90625 | 4 | from tkinter import *
from math import *
cal=Tk()
cal.title("Calulator")
cal.iconbitmap("E:\python demo\Python Tkinter demo\calculator\c.ico")
cal.configure(bg="#333333")
e=Entry(cal, width=30,borderwidth=2,font=("Calibri",15))
e.grid(row=0,column=0,columnspan=3,padx=10,pady=20,ipady=5)
def click(num):
n=e.get()
... |
65f2528c2e15fe8bb8eac9d1eb487ddc3273a6b1 | ewalldo/URI-OnlineJudge-Problems | /Mathematics/1323 - Feynman/main.py | 159 | 3.78125 | 4 | value = int(input())
while(value != 0):
total_squares = 0
for i in range(value + 1):
total_squares += (i * i)
print(total_squares)
value = int(input())
|
880cb36b1bd070712319da2d3d13f446a6d0d78d | ewalldo/URI-OnlineJudge-Problems | /Strings/1237 - Compare Substring/main.py | 498 | 3.890625 | 4 | def find_longest_substring(string_a, string_b):
substr_len = min(map(len, (string_a, string_b)))
if len(string_a) > len(string_b):
string_a, string_b = string_b, string_a
for char in range(substr_len, 0, -1):
for idx in range(0, len(string_a) - char + 1):
if string_a[idx:idx+char] in string_b:
return char... |
cb10a8032ffe5e407523576d8aa9a77868ba6fbb | ewalldo/URI-OnlineJudge-Problems | /Beginner/1164 - Perfect Number/main.py | 329 | 3.609375 | 4 | aux = input()
name = int(aux)
for i in range(name):
aux = input()
value = int(aux)
if value == 1:
print("1 nao eh perfeito")
continue
soma = 1
for j in range(2, int(value / 2) + 1):
if value % j == 0:
soma += j
if soma == value:
print("%d eh perfeito" % (value))
else:
print("%d nao eh perfeito" % ... |
f6b9139a7ce61c7829352374cf9d3c2cd877de6b | ewalldo/URI-OnlineJudge-Problems | /Beginner/1132 - Multiples of 13/main.py | 205 | 3.734375 | 4 | aux = input()
x1 = int(aux)
aux = input()
x2 = int(aux)
if x1 > x2:
temp = x2
x2 = x1
x1 = temp
if x1 == x2:
print(0)
soma = 0
for i in range(x1, x2 + 1):
if i % 13 != 0:
soma += i
print(soma)
|
064c6e7e350807bc6fe5ef214633e8e0ae012fe4 | ewalldo/URI-OnlineJudge-Problems | /Beginner/3037 - Playing Darts by Distance/main.py | 415 | 3.671875 | 4 | n_cases = int(input())
for x in range(n_cases):
joao_score = 0
for j in range(3):
score, distance = map(int, input().split(' '))
joao_score += (score * distance)
maria_score = 0
for j in range(3):
score, distance = map(int, input().split(' '))
maria_score += (score * distance)
if maria_score > joao_sc... |
632c1b90fe589a0cef8a8cc3279c1acee0b87191 | ewalldo/URI-OnlineJudge-Problems | /Beginner/1165 - Prime Number/main.py | 319 | 3.53125 | 4 | aux = input()
name = int(aux)
for i in range(name):
aux = input()
value = int(aux)
if value == 1:
print("1 nao eh primo")
continue
flag = 0
for j in range(2, int(value / 2) + 1):
if value % j == 0:
print("%d nao eh primo" % (value))
flag = 1
break
if flag == 0:
print("%d eh primo" % (value))
|
160c2bc26fa3c25b49858b65946313c9da999c53 | ewalldo/URI-OnlineJudge-Problems | /Strings/2023 - The Last Good Kid/main.py | 176 | 3.578125 | 4 | current_lower = input()
while True:
try:
name = input()
if name.lower() > current_lower.lower():
current_lower = name
except EOFError:
print(current_lower)
break |
4523e25e83af143cbdde4d5564a20d2e1ae37e83 | ewalldo/URI-OnlineJudge-Problems | /Beginner/2653 - Dijkstra/main.py | 196 | 3.546875 | 4 | dict_jewel = {}
while True:
try:
value = str(input())
if value not in dict_jewel:
dict_jewel[value] = 0
else:
dict_jewel[value] += 1
except EOFError:
print(len(dict_jewel))
break |
be595942351f2d2a63f1daacaf18c0859895ac74 | ewalldo/URI-OnlineJudge-Problems | /Beginner/1759 - Ho Ho Ho/main.py | 119 | 3.90625 | 4 | aux = input()
value = int(aux)
for i in range(value):
if i == value - 1:
print("Ho!")
else:
print("Ho ", end='') |
ebdc5f7dae48b6a0271d9c5065b6c4f1be4ed506 | ewalldo/URI-OnlineJudge-Problems | /Mathematics/1555 - Functions/main.py | 634 | 3.765625 | 4 | def Rafael_function(x, y):
return(((3*x)**2) + (y**2))
def Beto_function(x, y):
return((2*(x**2)) + ((5*y)**2))
def Carlos_function(x, y):
return((-100 * x) + (y**3))
n_cases = int(input())
for _ in range(n_cases):
x, y = map(int, input().split(' '))
Rafael_value = Rafael_function(x, y)
Beto_value = Beto_fun... |
19c718a5cbaa31dd3ef0f2a4fa54fe5d39f37125 | ewalldo/URI-OnlineJudge-Problems | /Beginner/1847 - Welcome to the Winter!/main.py | 427 | 3.609375 | 4 | a, b, c = [int(x) for x in input().split()]
if a > b and b <= c:
print(":)")
elif a < b and b >= c:
print(":(")
elif a < b and b < c and (b - a > c - b):
print(":(")
elif a < b and b < c and (b - a <= c - b):
print(":)")
elif a > b and b > c and (a - b > b - c):
print(":)")
elif a > b and b > c and (a - b <= b - ... |
e8fc4b7cc6ac1d1e7f085cb58f6532a8034a819c | ewalldo/URI-OnlineJudge-Problems | /AD-HOC/1546 - Feedback/main.py | 290 | 3.53125 | 4 | n_input = int(input())
for i in range(n_input):
n_cases = int(input())
for j in range(n_cases):
feedback = int(input())
if feedback == 1:
print("Rolien")
elif feedback == 2:
print("Naej")
elif feedback == 3:
print("Elehcim")
elif feedback == 4:
print("Odranoel")
|
2515f23c792c855f551f1065b51f08e5585a0616 | ewalldo/URI-OnlineJudge-Problems | /Beginner/1146 - Growing Sequences/main.py | 178 | 3.703125 | 4 | while True:
aux = input()
value = int(aux)
if value == 0:
break
for i in range(1, value + 1):
if i != value:
print("%d " % (i), end='')
else:
print("%d" % (i))
|
de8c7d1d6f933c750a011e74970e4b53c4e5f62a | ewalldo/URI-OnlineJudge-Problems | /Beginner/2544 - Kage Bunshin no Jutsu/main.py | 170 | 3.6875 | 4 | while True:
try:
aux = input()
value = int(aux)
count = 0
while value != 0:
value = int(value / 2)
count += 1
print(count - 1)
except EOFError:
break |
86e0868add18cd6a109132e5022f2ebc62b078d3 | ewalldo/URI-OnlineJudge-Problems | /Beginner/1142 - PUM/main.py | 137 | 3.5625 | 4 | aux = input()
num = int(aux)
p = 1
for i in range(num):
for j in range(3):
print("%d " % (p), end='')
p += 1
print("PUM")
p += 1
|
e44a4d3144e33d674000daa2c95c31da76980e19 | williancae/JogoDeMultiplicacao | /principal.py | 3,392 | 3.671875 | 4 |
import random # importando biblioteca que gera numeros aleatorios
import datetime
# Dicionario de formatação de texto
colors = {'white': '\033[30m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'purple': '\033[35m',
'cyan': '\0... |
d06fb854f049aab99c48b3e380795c5cb516dab9 | stahlgazer/cs-module-project-algorithms | /eating_cookies/eating_cookies.py | 1,237 | 4.0625 | 4 | '''
Input: an integer
Returns: an integer
'''
# def eating_cookies(n):
# # Your code here
# if n == 0:
# return 1
# elif n < 0:
# return 0
# else:
# return eating_cookies(n-1) + eating_cookies(n-2) + eating_cookies(n-3)
def eating_cookies(n, cache=None):
print(n)
# base ... |
f8aa26a8e3388eb18b01af49740355045f5fd593 | caitanojunior/python | /Coursera/semana6/jogo_nim.py | 3,173 | 4.0625 | 4 | def computador_escolhe_jogada(n, m):
peçasRestantes = n % (m + 1)
if peçasRestantes > 0 and peçasRestantes <= m:
jogada = peçasRestantes
else:
jogada = m
if jogada == 1:
print()
print("O computador tirou uma peça")
else:
print()
print("O computador tir... |
1aac502f9515c154310ee9856c5ba5a8e250cfb4 | caitanojunior/python | /Coursera/semana7/fatoresPrimos.py | 590 | 4 | 4 | def fatorPrimo():
n = int(input("Digite um número inteiro maior que 1: "))
fator = 2
multiplicidade = 0
while(n > 1):
while n % fator == 0:
multiplicidade = multiplicidade + 1
n = n / fator
if (multiplicidade > 0):
print("No fator", fator, "a multipli... |
84e77710d9bf0c626b5a4dab47fbdde2b088b781 | caitanojunior/python | /Coursera/semana8/maior_elemento.py | 250 | 3.984375 | 4 | # funcão recebe uma lista e retorna um inteiro com o maior valor
def maior_elemento(l):
lista = l
new_lista = list(lista)
new_lista.sort()
return new_lista[-1]
lista = [2,9,38,8,6,10,15] #lista exemplo
print(maior_elemento(lista)) |
f405a1dd2b437107d248354ca37874aab15fb696 | marcelinofavilla/URI | /1018.py | 884 | 3.5625 | 4 | A = int( input() )
print(A)
if A >= 100:
B = int(A/100)
A = A-B*100
print(B,"nota(s) de R$ 100,00")
else:
print(0,"nota(s) de R$ 100,00")
if A >= 50:
B = int(A/50)
A = A-B*50
print(B,"nota(s) de R$ 50,00")
else:
print(0,"nota(s) de R$ 50,00")
if A >= 20:
B = int(A/20)
A =... |
8e5fe2823bcdfce6d02abc1a688c82fe165f86c9 | MaksimVlasenko2006/git_python | /lesson 2/15.py | 70 | 3.75 | 4 | a=float(input("number"))
if a>15:
print(a+7)
else:
print(a-5)
|
40deceaf6d3f933265cfaa814cb4d892fff1cee1 | MaksimVlasenko2006/git_python | /lesson 2/13.py | 134 | 3.953125 | 4 | import math
a=float(input("a="))
if a>0:
print(math.sqrt(a),math.sqrt(a)*-1)
elif a==0:
print("x=",a)
else:
print("EROR")
|
41b6a3ae00a794da9c2b049aeeccdc8bebb2f7a7 | browerd0686/CTI110 | /P4HW2_PoundsKilos_DarriusBrower.py | 387 | 3.640625 | 4 | #Pounds to Kilos Table Excercise
#July 7, 2019
#CTI-110 Pounds to Kilos Table
#Darrius Brower
#
#Create table with headings Pounds, Kilograms
#Enter Pounds and convert kilos
#kg = lb/2.2046
#Calculate
#
#Print the table headings.
print('Pounds\tKilograms')
print('-------------------')
for lb in range(100... |
613f6bd4c1f00d29f49e24ed449dc88ea00b952e | jamesros161/alieninvader | /background.py | 619 | 3.515625 | 4 | import pygame
class Background():
def __init__(self, screen):
"""Initialize the background and set its starting position"""
self.screen = screen
# Load the background and get its rect.
self.image = pygame.image.load('images/background.jpg')
self.rect = self.image... |
f38b8876c64014427a6b751e1d1bafe825993b0a | TomParkinson95/Retro-Adventure-Game | /adventure_game_main.py | 6,898 | 3.984375 | 4 | import time
import random
# Prints a message and gives a time delay.
def print_pause(msg):
time.sleep(1.5)
print(msg)
# Prints the intro and begins the main part of the game.
def intro(items, enemy_name, weapon):
print_pause("You find yourself in a foggy forest, late at night.")
print_pause(f"There ... |
d6a73492eafe4686e2f64f14dc007d362444df00 | charlotte-zhuang/heap-experiments | /util/pairingheap.py | 4,215 | 4 | 4 | #!/usr/bin/env python3.9
import math
class HeapNode:
"""A node in a pairing heap.
Attributes:
key (int): The key value stored by this node. Guaranteed to be less
than or equal to all keys in this subheap.
left (HeapNode or None): The child of the node.
right (HeapNode or ... |
cbc55bbd2862e5860aeab01eec71c23c571a9c02 | eshthakkar/object-orientation | /assessment.py | 5,427 | 4.46875 | 4 | """
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
Object orientation provides the following 3 design benefits:
1. Abstraction - The ability for us to use functions without worrying what is inside it. Hides the details
... |
6177bd65f2bba366c0b2e1b047b15c799a58686a | fifajan/py-stuff | /interview_test_tasks/browser_vendor/final/task_1/connected_areas.py | 5,901 | 4.4375 | 4 | """
Task description:
Suppose you have rectangular area of size M x N. On each field you have
0 or 1. Your task is to design algorithm and write Python function for
marking the largest 8-connected area of ones. Fields from the largest area
should have the value 2.
|1|0|1|0|1| |2|0|2|0|1|
|1|1|1|0|0| => |2|2|2|0|0|... |
11d861a056cd63df6956c0cd2e34fb221f9f3e32 | fifajan/py-stuff | /interview_test_tasks/big_data_startup/priority_queue.py | 2,249 | 4.09375 | 4 | #! /usr/bin/python
class PriorityQueue(object):
"""My attempt to implement a priority queue.
http://www.cs.cmu.edu/~adamchik/15-121/lectures/Binary%20Heaps/heaps.html
resource was used for heap implementation details reference.
"""
def __init__(self):
# 'all heap (binary tree) layers ... |
8170aae317fc59e1740f14f813c4116cde129a01 | fifajan/py-stuff | /solvers/triangle_angles_by_sides.py | 628 | 4.03125 | 4 | from math import acos, degrees
def angles(a, b, c):
sides = ((a, b, c), (b, c, a), (c, a, b))
if not all([a + b > c for a, b, c in sides]):
return [0, 0, 0]
angle = lambda t: round(
degrees(acos(float(t[1]**2 + t[2]**2 - t[0]**2) / (2 * t[1] * t[2]))))
return sorted(map(angle, sides))
... |
2433a9c94f491153af3d422f94672b84bb93b59a | fifajan/py-stuff | /solvers/almost_palindrome.py | 757 | 4.15625 | 4 | #! /usr/bin/python
def is_almost_palindrome(word):
"""Checks if string is an 'almost' (1 character miss) palindrome."""
mid = len(word) / 2
l, r = word[:mid], word[mid:]
r = r[::-1] # reverse
if l == r:
return True
else: # not a true palindrome
diff = 0
for i in range(mi... |
16d1917bc369a81a4cecb35d3089c9eb2329bd82 | fifajan/py-stuff | /algorithms/graphs/search_test.py | 813 | 3.890625 | 4 | #! /usr/bin/python
'''
we have a directed graph:
(1) <-> (2) -> (3) -> (4)
| |
v v
(5) -> (6)
you should implement a function (and some classes or
data structures if it is necessary) to return a path
from any node to any other. It thould r... |
585241f1f8b947a20687993efb6bf7bbb7585940 | fifajan/py-stuff | /algorithms/misc/bin_neg2_base.py | 572 | 3.9375 | 4 | #! /usr/bin/python
'''
Tools for (-2) base binary system.
'''
def get_number_neg2(bits):
return sum(b * ((-2)**i) for i, b in enumerate(bits))
def get_bits_neg2(number):
result = []
while number:
remainder = number % -2
number /= -2
if remainder < 0:
remainder += 2
... |
e6b47a5b36f5fd2b4d6d0d242d84ce7601f59ec2 | Aparecida-Silva/MiniTeste-3_Bim | /Questão2.py | 1,775 | 4.46875 | 4 | # Importação do módulo random, precisamos fazer isso para podermos utilizar as funçôes do modelo em questão
import random
# A função seed serve para inicializar o gerador de números aleatórios.
random.seed()
# Sortear um número de 1 à 10
sorteio = random.randint(1,10)
# Uma váriável para mostrar ao computador por onde ... |
25b432df10b1a47eab5e45c1bcf9838f8aff2539 | shivendrd/OneNeuron | /utils/model.py | 2,085 | 3.703125 | 4 | import os
import joblib
import numpy as np
import pandas as pd
class Perceptron:
"""
creating a Perceptron class
"""
def __init__(self,eta,epochs):
self.weights = np.random.randn(3)
print(f"initial weights before training: \n{self.weights}")
self.eta = eta
... |
82b9f868af54ff1aaf74f0d41104c0575b45c423 | altroy2554/DB | /20210807/htmlpandas.py | 1,950 | 3.671875 | 4 | import pandas as pd
date = input("알고싶은 날을 입력하시오(2021-01-01)").split('-')
URL = f"https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=cur&date={date[0]}{date[1]}{date[2]}"
date = pd.read_html(URL)
#print(date[0])
#print(date[0]) #0은 데이터
#print(date[1]) #data에 대한 정보 요약
df = date[0]
#print(df.hea... |
f55b145dd6a21e68c946e0a4c5f113cb94c072d8 | janertl/sequence-jacobian | /src/sequence_jacobian/utilities/misc.py | 5,204 | 3.828125 | 4 | """Assorted other utilities"""
import numpy as np
import scipy.linalg
from numba import njit, guvectorize
def make_tuple(x):
"""If not tuple or list, make into tuple with one element.
Wrapping with this allows user to write, e.g.:
"return r" rather than "return (r,)"
"policy='a'" rather than "policy... |
a8f1fabe9f32bd55c816f61f0579f580a109bf2a | janertl/sequence-jacobian | /src/sequence_jacobian/blocks/support/parent.py | 2,775 | 3.671875 | 4 | from copy import deepcopy
class Parent:
# see tests in test_parent_block.py
def __init__(self, blocks, name=None):
# dict from names to immediate kid blocks themselves
# dict from descendants to the names of kid blocks through which to access them
# "descendants" of a block include its... |
a93c173b85b71b2941ab69d2a73c9c40b3587da1 | IkDev08/Coffe_Machine.py | /Problems/The Louvre/task.py | 323 | 4 | 4 | class Painting:
museum = "the Louvre"
def __init__(self, artist, title, year):
self.artist = artist
self.title = title
self.year = year
painting = Painting(input(), input(), input())
print('"{1}" by {0} ({2}) hangs in the Louvre.'.format(painting.title, painting.artist, painting.year... |
32d2eaa5648cc8985b48a2dd484d8879d4e9f0be | adityasunny1189/Python | /PYTHON/turtle graphics/turtle1.py | 281 | 3.6875 | 4 | from turtle import *
import time
import random
import math
colors = ["red", "green", "yellow", "black", "purple", "violet"]
for i in range(10):
color(colors[i % len(colors)])
fillcolor("pink")
shape("turtle")
forward(500)
right(500)
forward(500)
right(500)
time.sleep(10) |
3ec07bf47c31a6056d759181bc8a2396974d61d7 | dbuts/randomPiCalc | /main.py | 767 | 3.640625 | 4 | from math import *
from random import randint
def calcPi():
factor = 0
prime = 0
N = 1000
def cofactor(x,y):
if x%2 == 0 and y%2 ==0:
return True
if x > y:
z = x
else:
z = y
for i in range (3, int(z/2), 2):
if x%i == 0 and y%i == 0:
return True
return False
for i in range(0,N):
x = ... |
f11c93e0fec2d3515815cf055a2328bba43fdda7 | raehik/dotfiles | /TODO/scripts-old/old/play-old.py | 3,447 | 3.640625 | 4 | #!/usr/bin/env python3
#
# Short description of the program/script's operation/function.
#
import sys
import argparse
import subprocess
import os
FILENAME = sys.argv[0]
class ArgumentParserUsage(argparse.ArgumentParser):
"""Argparse override to print usage to stderr on argument error."""
def error(self, mess... |
8a45ee5ff229795656a67486bf1120e6fb6c2fac | dlwns147/Projects | /python/piglatin.py | 85 | 3.625 | 4 | pig = input("input : ")
piglatin = pig[1:]+pig[0]+'ay'
print("piglatin :", piglatin)
|
9d9f0f589180039a4c8f84ef6c9460740438cfa0 | dlwns147/Projects | /python/기말4.py | 355 | 3.59375 | 4 | idols = {'A' : (5.6, 9.5), 'B' : (9.1, 9.2), 'C' : (4.3, 3.2), "D" : (9.7, 8.9)}
idol = input("누구의 결과가 궁금하세요? : ")
if idols[idol][0] >= 9.0 and idols[idol][1] >= 9.0 :
print("자동 진출 입니다.")
elif idols[idol][0] < 5.0 and idols[idol][1] < 5.0 :
print("탈락 입니다.")
else :
print("선발전 입니다.")
|
2fffeea50ca1124a1693ee0d888969fd2e229c12 | dlwns147/Projects | /python/q11-16.py | 920 | 3.796875 | 4 | def avg(scores) :
scores_sum = 0
for score in scores :
scores_sum += score
return scores_sum / len(scores)
def highest(scores) :
highest_score = scores[0]
for score in scores :
if highest_score < score :
highest_score = score
return highest_score
def lowest(scores) ... |
9d534392e3f622867234bab43c7c46c9a5ac3cf7 | kushagragarwal2443/Minimizer_Jellyfish | /BC_Dist/bc_distance_computation.py | 1,070 | 3.8125 | 4 | import sys
def fasta_parser(filename):
fasta = {}
with open(filename) as file_one:
for line in file_one:
line = line.strip()
if not line:
continue
if line.startswith(">"):
active_sequence_name = int(line[1:])
continue... |
47720d42938e68ad058215753ae4d1d55d17aa41 | fpeterek/VirginEuropeApp | /VirginEurope/util.py | 612 | 3.671875 | 4 | import re
from datetime import datetime
class InvalidAirportException(Exception):
pass
__airport_re = re.compile('([A-Z]{4}[)])$')
__classes = ['business', 'economy', 'first']
def parse_airport(query: str) -> str:
if not __airport_re.search(query):
raise InvalidAirportException('Invalid airport')
... |
63807a7d67d973c77d2bad758cb731c2fc6421f0 | nschampions2004/pf4e | /8.5Assignment/SummarizingAddresses.py | 490 | 3.890625 | 4 | fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
vals = list()
for line in fh:
if not line.startswith("From") : continue
if line.startswith("From:") : continue
else:
line = line.rstrip()
vals.append(line)
ems = list()
for liners in va... |
4f40cf8654f3f2d8b42ae21b24dd84ef23500b7e | alinedsoares/PythonMundo2 | /ex036.py | 715 | 3.734375 | 4 | valor_casa = float(input('Qual o valor do imóvel? R$ '))
salario_comprador = float(input('Qual o valor do seu salário mensal? R$ '))
prazo_anos = int(input('Em quantos anos você pretende pagar o imóvel? '))
prestacao_mensal = valor_casa / (prazo_anos * 12)
limite_prestacao = salario_comprador * 0.30
if prestac... |
19f5013620cbafb99606a95cbf00a4404e42e7bb | jckett/Weather-API | /weather.py | 6,912 | 4.1875 | 4 | """File:ChuKetterer_12.1.py
Name: Joi Chu-Ketterer
Date: 5/30/19
Course: DSC510 - Introduction to Programming
Desc: This program calculates retrieves temperatures using 'OpenWeatherApp' API based on where the user's input for location.
Usage: The user will indicate if they want to find the weather using a city name, or... |
9f21cdc765f12172464ea89b5fb1e34af867c9c5 | hcwhwang/ttbb | /t.py | 178 | 3.65625 | 4 | wList = ['c','d']
word = 'a_b_c'
word.split("_")
print word.split("_")[0]
#word = word[len(word.split("_")[0])+1:]
print word
if not any( w in word for w in wList): print 'test'
|
da796f60e35e7c635415c4fc76a053322465fffb | bariscalis/Guess-Game | /GuessGame.py | 4,461 | 3.96875 | 4 | import tkinter as tk
import random
import tkinter.messagebox
i = 1
conum = True
# Function for getting random number and for second game clear entry and label
def rand():
global i # It is used for guessing number and as process bar
global conum # It is used for clearing and starting again ... |
d422824d0bfed2b92888402a80127ef9ed7221cc | ellaliu815/Unittest-HTML-report-generation | /testsample.py | 1,296 | 4.09375 | 4 | #这是一种简单的线性测试,非模块化测试,从main开始依次运行
import unittest
from function import *
class TestFunc(unittest.TestCase):
# 继承自unittest.TestCase
# 重写TestCase的setUp()、tearDown()方法:在每个测试方法执行前以及执行后各执行一次
def setUp(self):
print("do something before test : prepare environment")
def tearDown(self):
... |
5cb89f74505ea7930bc0d48a9457764cb5960ae8 | tombresson/AdventOfCode-2017 | /Day6-Part1andPart2.py | 953 | 3.71875 | 4 | import copy
data = [10, 3, 15, 10, 5, 15, 5, 15, 9, 2, 5, 8, 5, 2, 3, 6]
# data = [0, 2, 7, 0]
history = []
repeated_set = False
redistribution_count = 0
repeated_index = 0
while (not repeated_set):
# Check if set has been seen before
for element in history:
if(element == data):
repeated... |
a1aaf913c4f598b442b1959eaaea8edc6184a3da | VirinchiRallabhandi/GalaxyModels | /Miscellaneous plotting.py | 19,099 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 14:46:35 2018
Good luck if you're trying to understand this module
@author: Virinchi Rallabhandi
"""
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
from mpl_toolkits import mplot3d
"""Gives the circular... |
40de5832b11c95afcb01becf6973f56e593e2fae | vivekhub/NSEEvents | /common/parse_datetime.py | 2,291 | 3.671875 | 4 | #/usr/bin/python
"""
Simple robust time and date parsing.
Note: Follows the Australian standard, dd/mm/yyyy.
Americans should replace '%d %m %Y' with '%m %d %Y' and '%d %m %y' with '%m %d %y' below.
Routines will either
- return a date or time
- return None if the string is emp... |
1b6c30b2c36121b11bb2ca4e53d99bf4b78b24fd | yell/python-utils | /utils/stats_utils.py | 472 | 3.578125 | 4 | import numpy as np
def make_ecdf(z):
"""
Examples
--------
>>> z = np.array([0.01, 0.16, 0.24, 0.68, 0.79])
>>> ecdf = make_ecdf(z)
>>> x = np.linspace(0., 1., 11, endpoint=True)
>>> print x
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
>>> print ecdf(x)
[0. 0.2 0.4 0.6 0.6 0.... |
caf2e5ab166e3ace43c2fd523aae682ad13910c0 | yell/python-utils | /utils/numerical_utils.py | 2,761 | 3.640625 | 4 | import numpy as np
from scipy.linalg import expm
from scipy.misc import logsumexp as scipy_logsumexp
def log_sum_exp(x, axis=None, keepdims=False):
"""
Compute log(sum(exp(x))) in a numerically stable way.
Examples
--------
>>> x = np.arange(10)
>>> np.log(np.sum(np.exp(x))) #doctest: +ELLIP... |
e9155963542c0338f2e00c360ebb229b888acae0 | saikrishnan255/extracting-business-insights | /code.py | 6,061 | 4 | 4 | # --------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv(path)
def visual_summary(type_, df, col):
df[col].plot(kind = type_)
plt.show()
"""Summarize the Data using Visual Method.
This function accepts the type of visualization, the data frame ... |
a07978ef95e0d4b7936235bde2953eaf1b70829d | Bolotovalana/homework | /task9_2.py | 262 | 4.15625 | 4 | # 2. Написатьпрограмму,котораяпроверяет,начинаетсялистрокас данного символа, используя lambda функцию.
word = "ello"
b = list(filter(lambda word: "h" == word[0], word))
print(b)
|
3a13ebbe41726650648273d01f29e0768dfe5e13 | Bolotovalana/homework | /homework_12_3.py | 401 | 4.40625 | 4 | # 3. Написать генератор, который будет принимать на вход имя файла
# и генерировать построчно(т.е yield каждой строки).
def read_file(file_name):
for row in open(file_name, "r"):
yield row
str_row = read_file("file.txt")
print(str_row.__next__())
print(str_row.__next__())
print(str_row.__next__()) |
79e5da8534999ae074d255dfc7b1a87a9582209c | Bolotovalana/homework | /task_3.3.py | 439 | 4.25 | 4 | # Ввести строку. Если длина строки больше 10 символов, то создать новую
# строку с 3 восклицательными знаками в конце ('!!!') и вывести на экран.
# Если меньше 10, то вывести на экран второй символ строки
a = input()
if len(a) > 10:
print(a + "!!!")
elif len(a) <= 10:
print(a[1]) |
fca8f57af312d0270dd0be1a11d7e528f6674e48 | Saint129/SaintAvitFoka_DAT129 | /saint_binary.py | 1,710 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 16:12:05 2020
@author: Avit_
"""
'''
Python 2 - DAT 129
Week 1: 09/02/2020
Module 1: Icon Manipulation
Assignment: Create a program in Python that uses looping
and Basic Data Structures to display customized 10x10 Student
icons in various scales and ori... |
ab79a627815b176d80b6948febd85f7f19f1b2f4 | developiaa/python-study | /copy.py | 1,039 | 3.59375 | 4 | import copy
a = [1, 2, 3]
b = a
# shallow copy - 메모리 주소값이 복사되어 같은 값이 출력됨
print(id(a))
print(id(b))
c = [[1, 2, 3], [4, 5, 6]]
d = c[:]
# 슬라이싱을 통해 할당하는 경우 새로운 id가 부여되며, 서로 영향을 받지 않음
# 그러나 이러한 슬라이싱 또한 얕은 복사에 해당
# mutable 객체 안에 mutable 객체인 경우 문제가 된다.
# id(c) , id(d) 값은 다르지만 내부의 객체 id(c[0]), id(d[0])은 같다
print(id(c))
pr... |
0648f625a633ed488f900b09f44777fa744b9253 | isdenis/python | /lesson4/task_4.py | 613 | 3.6875 | 4 | import random
a = int(input("Введите начальную цифру для генерации: "))
b = int(input("Введите последнюю цифру для генерации: "))
c = int(input("Введите количество цифру в списке: "))
first_list = [random.randint(a, b) for i in range(c)]
result_list = [i for i in first_list if first_list.count(i) == 1]
print(f"Сгене... |
ca0c98322e93f8ea23732f4875698b72d0efae6d | isdenis/python | /lesson2/task_4.py | 219 | 3.6875 | 4 | word = input("Введите несколько слов: ")
word_split = word.split()
word_split_limit = []
for a in word_split:
word_split_limit.append(a[:10])
for b in enumerate(word_split_limit):
print(b)
|
8c6840922c5b71363c99407d709e00109a39c7da | isdenis/python | /lesson1/task_1.py | 629 | 4.1875 | 4 | print("Привет. Давай будем умножать и делить")
a = int(input("Введите 1 для умножения или 2 для деления: "))
if a == 1:
print("Отлично, ты выбрал умножение.")
if a == 2:
print("Отлично, ты выбрал деление.")
b = int(input("Введи первую цифру: "))
print(f"Ты выбрал {b}")
c = int(input("Введи вторую цифру: "))
p... |
12729c2241a2f049658b1e27feb13951e6e9865f | isdenis/python | /lesson1/task_4.py | 200 | 3.90625 | 4 | number = int(input("Введи целое положительное число: "))
max = 0
while number > 0:
i = number % 10
number = number // 10
if i > max:
max = i
print(max)
|
d012ac175f4de5976a1b2cafa08f71c3f77e0929 | maxily1/Quadratic-Algorithm | /algorithm.py | 1,746 | 4 | 4 | '''
Project Name: Quadratic Cipher
Project Description: My first try of making an algorithm all by myself.
Author: Max Iliouchenko
Date of Project Start: 23/02/2021
Date of Project End: N/A
'''
# Importing required modules
import math
# Choose whether it's going to be a file or just a message to input... |
ce045cd93c56ce5fc31d7264d30d2667a6181a1c | lcwadle/AI-FreeFlow | /FlowFree.py | 12,630 | 3.65625 | 4 | from random import randint, shuffle
import sys
class Node:
def __init__(self, row, col, value):
self.row = row
self.col = col
self.value = value
self.startValue = False
self.availableColors = []
class Puzzle:
# Variables: Nodes in the puzzle
# Domain: List of starti... |
3088504b14bdb4dab6df4e366a8abead4f184db2 | WenRich666/learn-note | /python/第六章 字典/user.py | 542 | 3.5625 | 4 | # user_0 = {
# "username":"efermi",
# "first":"enrico",
# "last":"fermi",
# }
# for key,value in user_0.items():
# print("\nKey:" + key)
# print("Value:" + value)
# a = list(range(1,9))
#
# for i in range(1,len(a),2):
# print(a[i],end = " | ")
#
# b = a[0:len(a):2]
# print(b)
... |
5e924c8c23e6564068f98a83bb79f35a51c4eacd | WenRich666/learn-note | /python/第四章 操作列表/squares.py | 312 | 3.953125 | 4 | squares = []
for value in range(1,11):
squares.append(value ** 2)
print(squares)
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
cubes = [value ** 3 for value in range(1,11)]
print(cubes)
a = [value for value in range(1,102) if value % 3 ==0]
print(a) |
9c36e2eedfe221b46cc8ee716eef536b9f74f9a3 | WenRich666/learn-note | /视频第九章/c2.py | 685 | 3.671875 | 4 | class Student():
name = " qiyue"
age = 0
sum = 0
def __init__(self,name,age):
self.name = name
self.age = age
self.__score = 0
self.__class__.sum += 1
print(self.name + "今年" + str(self.age) + ",他喜欢做作业")
def do_homework(self):
print("do homework")
... |
45d23c7a5e326d88ad09f31d5b4496ba857c2d2a | GonzSanch/CodeWars | /6kyu/Unique in Order/unique_in_order.py | 322 | 3.84375 | 4 | #! /usr/bin/env python3
def unique_in_order(iterable):
index = 1
new_list = []
if len(iterable) == 0:
return new_list
new_list.append(iterable[0])
while index < len(iterable):
if (iterable[index] != new_list[len(new_list) - 1]):
new_list.append(iterable[index])
index += 1
return new_lis... |
8fe28af1745e2ce4109807b806701039ac224d1d | UnknownUser991/Modelo | /p06_P2.py | 106 | 3.78125 | 4 | n = int(input("Numero N?"))
i = 2
while i < n:
if n /i == n //i :
break
i += 1
print(i) |
ce6ad9206f194607dbaab6185365fae885f32a5e | jqb1/Hangman-game | /Hangman.py | 635 | 3.65625 | 4 | from Draw import Draw
from Input import Input
import argparse
def Main():
print("Hello in a simple hangman game")
level_parser = argparse.ArgumentParser(description="Choosing level")
level_parser.add_argument('lvl', default=1, help="1-easy, other-hard , default - easy", type=int)
level_parser.add_arg... |
f83bda5e971913bd4c42a2f39adf0749af7296c8 | xvzhifeng/python | /python从零到数据可视化/unit3/unit3_5.py | 150 | 3.53125 | 4 |
if __name__ == "__main__":
list = ["iphone", "sasung", "oppen", "iphone x"]
list1 = [i for i in list if "iphone" in i]
print (list1) |
ca00390a9df56bbc85eff8ca21c97cdf6b2543df | xvzhifeng/python | /python_极客项目/wanghuachi/spiro.py | 3,989 | 3.78125 | 4 | """
@Author:sumu
@Date:2020-01-03 14:58
@Email:xvzhifeng@126.com
"""
import math
import turtle
from math import gcd
import fractions
class Spiro:
#construtor
def __init__(self,xc,yc,col,R,r,l):
#create the turtle object
self.t = turtle.Turtle()
# set the cursor shape
... |
198637e3fbe0db1f464db3c5d7fc35dd0dff5954 | xvzhifeng/python | /python从零到数据可视化/unit3/unit3_4.py | 242 | 3.546875 | 4 |
if __name__ == "__main__":
s = "i love good food"
# 结果无序
s2 = ''.join(list(set([i for i in s])))
print(s2)
# 结果有序
dic = {}.fromkeys([i for i in s])
print(dic)
print(''.join(dic.keys())) |
9254768e10b27ba1b888919642610d0c6bb5a3fb | itry1997/python_work_ol | /7-5电影票.py | 262 | 4.09375 | 4 | prompt = "Please enter your age.\n"
prompt += "Enter 'quit' when you finished."
while True:
age = input(prompt)
if age == "quit":
break
elif int(age) <= 3:
print("Free")
elif 3<int(age)<12:
print("10 dallers")
elif int(age)>12:
print("15 dallers")
|
1ac9fa9f1986ae644816eaa9776369a99ce30963 | itry1997/python_work_ol | /4-11你的披萨和我的披萨.py | 383 | 3.765625 | 4 | my_pizzas=['New York style','Chicago style','Thick style']
friend_pizzas=my_pizzas[:]
my_pizzas.append('Cracker and Thin style')
friend_pizzas.append('stufffed')
print(my_pizzas)
print(friend_pizzas)
print("\nMy favourite pizzas are:")
for my_pizza in my_pizzas:
print(my_pizza)
print("\nMy friend's favourite pizzas ... |
ed56544e4ba713012068e1d22cf8c1be0fcb1ff1 | itry1997/python_work_ol | /conditional_test.py | 512 | 3.703125 | 4 | message1='Python'
message2='python'
print(message1==message2)
print(message1.lower()==message2.lower())
number1=27
number2=36
print(number1==number2)
print(number1>=number2)
print(number1<=number2)
print('\n')
print(number1<30 and number2>30)
print(number1>30 and number2>30)
print(number1>30 or number2>30)
print(numb... |
57eafad4eb02efa1ab67c2b5fa2677fdadb17673 | itry1997/python_work_ol | /favourite_languages(1).py | 388 | 3.90625 | 4 | # -*- coding: UTF-8 -*-
from collections import OrderedDict
favourite_languages = OrderedDict()
favourite_languages['jen'] = 'python'
favourite_languages['sarch'] = 'c'
favourite_languages['edward'] = 'ruby'
favourite_languages['phil'] = 'python'
for name,language in favourite_languages.items():
print(name.title... |
5e5bf9a2a14dc6f0451e581f5fcfb70e5d126e97 | itry1997/python_work_ol | /6-9喜欢的地方.py | 269 | 3.5 | 4 | favourite_pleases = {
'cuiwie': ['liaocheng','jinan'],
'liuxuan': ['jinan','linyi','liaocheng'],
'xijinping': ['beijing'],
}
for name, pleases in favourite_pleases.items():
print(name.title() + ": ")
for please in pleases:
print(please.title())
print("\n")
|
9bbf42aae446a240923f00399103c1f854539cca | yingkexu/pythongame | /NN2N3.py | 326 | 3.765625 | 4 | def add0(a, b):
return a + b
def times0(a,b):
return a * b
def divide0(a,b):
return a / b
print('input n')
n = int(input())
print('input n2')
n2 = int(input())
print('input n3')
n3 = int(input())
print('input n4')
n4 = int(input())
asonsum = add0(n,n2)
ssum = times0(n3,asonsum)
print(divide0(ssum... |
13a0cadb850e07650c7aa5866dc0904905f7996e | yingkexu/pythongame | /hangman.py | 5,128 | 3.609375 | 4 | import random
def get_list():
return ['''
+----+
!
!
!
===
===''','''
+----+
0 !
!
!
===
===''','''
+----+
0 !
! !
!
===
===''','''
+----+
0 !
/! !
!
===
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.