blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
d964cce36c6600072f8196416904da84e8159928 | shagunvarma/plncc-new | /server.py | 503 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
print("Please enter the server names and sizes when prompted as such -> X:4, Y:2, Z:7")
input1 = input("SERVERS:")
servString = input1.split(',')
names = []
sizes = []
total = 0
for i in range(len(servString)):
servString[i] = servString[i].strip()
names.app... |
ceda3af5a3ecadbae312afa8ba7c84ccab31fdc1 | AmjadAlakrami/Fr-gor-sport- | /Python/kompendium/Kapitel 2/2,2.py | 152 | 3.578125 | 4 | a = float(input("Ange ett decimaltal:")) #skapa variabel a och sätta den som input
print (round(a)) #printa ut den som användaren matade in i input a
|
4855cda3231aa35555c52939d218d37d729454e2 | AmjadAlakrami/Fr-gor-sport- | /Python/kompendium/Kapitel 7/7,2.py | 936 | 3.9375 | 4 | MultiplikInput = int(input("välj en multiplikationstabell: ")) # anger multiplikationstabell
upprepning = 0
while True: # sätter while loopen på
upprepning = upprepning + 1 # lägger 1 på upprepning variabel
print(upprepning, "*" , MultiplikInput, "=", upprepning * MultiplikInput)
if (upprepning % 3 =... |
7bdeca3f85e80565653aa68814d7798b78cc8a96 | AmjadAlakrami/Fr-gor-sport- | /Python/kompendium/Kapitel 8/8,1.py | 664 | 3.84375 | 4 | #input variablar
enhet = input("ange enheten du vill omvandla till: ")
enhet2 = input("ange enheten du vill omvandla från: ")
sträckan = int(input("ange strcäkan : "))
# skapa en funktion
def km_till_miles (dist):
print (25 * "*")
print (sträckan, enhet2, " = ", dist * 1.609344, enhet)
print (25 * "*"... |
74de5cdefd5568319f637d3c840be0d69106bfc3 | cshintov/mynotes | /codes/fib.py | 459 | 3.796875 | 4 | def fib(n):
assert n > 0, "n should be positive integer"
if n <= 2:
return 1
return fib(n-1) + fib(n-2)
print fib(1), fib(2), fib(3)
# print fib(100)
def fib(n, fibtable={1: 1, 2: 1}):
assert n > 0, "n should be positive integer"
if not n in fibtable:
fibtable[n] = fib(n-1) + fib... |
b56ee7e56d542fcdfe1e75872c52b3750c86932a | leonardocaranti/AB2-DST_project | /Groundtrack/TAS_Data_reading.py | 1,639 | 3.671875 | 4 | #IMPORT MODULES
from matplotlib import pyplot as plt
def choose_dataset(filename):
#READ FILE AND CREATE LIST WITH DATA
r = open(filename,'r',encoding='utf-8', errors='replace')
data = []
for line in r.readlines(): #saves all data each line becomes a list
line = line.strip().strip('\n... |
ff208417a13daae0646f2b27f5f584988a031750 | TAYFUN-KAYA/Algorithms | /collatz asal (2).py | 502 | 3.546875 | 4 | def asalmı(n):
p=(n**1/2)//1
if(n==2):
return(1)
if(n==((n/2)//1)*2):
return(0)
i=3
while True:
if(n==((n/i)//1)*i):
return(0)
if(i<p):
i+=2
else:
return(1)
alsana[1]
for p in range(2,10000):
a[1]=1
c=1
k=p
w... |
37d82ccef3579a64064440911216fd11eb973fb3 | anojan-tme/TicketMasterExercise | /collatz.py | 479 | 3.75 | 4 | #!/usr/bin/python
def collatz(begin,listsize=1):
if begin == 1:
return listsize
elif begin % 2 == 0:
return collatz(begin/2,listsize+1)
else:
return collatz(3*begin + 1, listsize+1)
longestlength=0
longestproducer=0
for i in range(1,1000000):
... |
1fe8400523ef27f81df11baa71cded27f3d633b7 | linjorejoy/json-testcase-generator | /src/widgetclasses/MyLabel.py | 819 | 3.609375 | 4 | from tkinter import Label
from tkinter import NE
import tkinter.font as tkfont
from helpermodules.constants import DEF_LABEL_TEXT, PADX, PADY
from helpermodules.MyFonts import FONTS
class MyLabel(Label):
def __init__(
self,
parent,
controller,
text:str=DEF_LABEL_TEXT,
fo... |
d7ca1c96370b9ad7816eb1632b6f92b2c674e80f | YunPC/python-coding-study | /HJH/232_Implement_Queue_Using_Stacks/232_Implement_Queue_Using_Stacks.py | 1,107 | 3.875 | 4 | class MyQueue:
def __init__(self):
self.stack1 = []
def push(self, x: int) -> None:
self.stack1.append(x)
def pop(self) -> int:
if self.peek():
return self.stack1.pop(0)
return None
def peek(self) -> int:
if self.stack1:
return self.sta... |
03e81b5f844d8b14e24ab5b0a365bd667239f95c | JoaquinAO/Tareas-de-programacion-Universidad | /Tarea 06/Tarea 06.py | 1,195 | 3.90625 | 4 | mayor1 = -1
mayor2 = -1
menor = 1000000000000000
numerosImpares = 0
print('''Este programa comprara los números ingresados y encuentra:
- El menor número ingresado
- La suma de los números impares ingresados
- Los dos números mayores ingresados
''')
#Ciclo para poder ingresar los 50 números
for i in range(50):
... |
42d849e8a729f3fe92421609788efdcba2ffcea4 | LilyYC/legendary-train | /Python/Algorithm/encoding.py | 1,102 | 4.09375 | 4 | def get_hash_symbol_indices(s):
count = []
for i in range(len(s)):
if s[i] == '#':
count.append(i)
return count
def get_hash_symbol_indices1(s):
count = []
for i in range(len(s)):
count.append(s.find('#', i),)
return count[:-1]
def encode(message, encodings):
... |
be7a1dca1d705ff2c5068fcd059ffa80aaa4ffea | LilyYC/legendary-train | /Python/Algorithm/levels.py | 3,476 | 4.375 | 4 | """ levels
"""
from typing import List, Optional, Tuple
class BinarySearchTree:
"""Binary Search Tree class.
This class represents a binary tree satisfying the Binary Search Tree
property: for every node, its value is >= all items stored in its left
subtree, and <= all items stored in its right sub... |
b10e0a864c17a8e2822dc1486f15693f2dc300de | LilyYC/legendary-train | /Python/Algorithm/linked_list_v2.py | 12,969 | 4.28125 | 4 | """Lab 6: Linked List Exercises, Part 2
This module contains the code for a linked list implementation with two classes,
LinkedList and _Node.
"""
from typing import Optional, Callable, Iterator, Union
class _Node:
"""A node in a linked list.
Note that this is considered a "private class", one whi... |
938a3aedea08cfebd6897ad21e05bf9a08a9f791 | LilyYC/legendary-train | /Python/Algorithm/reverse.py | 220 | 4.0625 | 4 | #Algorithm1
def reverse(s):
""" (str) -> str
Return s reversed.
>>> reverse('hello')
'olleh'
"""
s_reversed = ''
for ch in s:
s_reversed = ch + s_reversed
return s_reversed |
84439b02257c96cd62c29bd8ba2af1ce6e357636 | LilyYC/legendary-train | /Programming-OOP/BlockGame/block.py | 18,262 | 4 | 4 | """Assignment 2 - Blocky
=== Module Description ===
This file contains the Block class, the main data structure used in the game.
"""
from typing import Optional, Tuple, List
import random
import math
from renderer import COLOUR_LIST, TEMPTING_TURQUOISE, BLACK, colour_name
HIGHLIGHT_COLOUR = TEMPTING_TURQUOISE
FRAM... |
fa339807d0377777541fd386710bfee0767f70f4 | sl2631/rwet | /hw3/hw3-binary.py | 2,122 | 3.8125 | 4 | #!/usr/bin/env python
from __future__ import print_function
import nltk
import nltk.tokenize
import random
import sys
from pprint import pprint
text_path = 'kipling.txt'
sample_size = int(sys.argv[1]) # first argument is sample size
text = open(text_path).read()
# both flat and nested will hold the entire poem
flat... |
ca5d0572cce759d00e3f0766cd7a90ff42b7094a | Folrig/TSP_Trucks | /my_time.py | 2,309 | 3.859375 | 4 | # James Spencer ID: 000486930
class Time:
# A static method to adjust the time string into human readable form
@staticmethod
def to_human_format(time):
time_list = time.split(' ')
time_str = str(time_list[0])
time_of_day = str.upper(time_list[1])
time_list = time_str.split... |
6e423f0f7678f06dd5de0e7235c4afa5295358e1 | apoorvasharma007/networks | /geolocationserver.py | 2,618 | 4.125 | 4 | #Apoorva Sharma
'''
In this program I have written a simple server script which will listen for a connection from a remote client. To locate the remote client I need his IP Address. When the server accepts a connection request by .accept() call, it returns a new socket descriptor for connecting to the client and ADDRE... |
ff61d50fd852f15e330f15dfcfc161352f12ae3e | Rajanandhini97/gitdemo | /ifloop.py | 629 | 3.75 | 4 | greeting = "Good Morning"
a = 45
if a < 50:
print("Condition matches")
print("Second line")
else:
print("Condition does not match")
print("if condition code is completed")
#for loop
obj = [3, 4, 5 ,6 ,7]
for i in obj:
print(i*2)
#sum of first five natural numbers
summation = 0
for j in range(1,6):
... |
41387c4fea47b93d7cee3ff83f3d687fa05ce470 | JoonasKuopiosta/TekninenHarkkaOikea | /newDataProcessing.py | 3,428 | 3.890625 | 4 | import plotly.graph_objects as go
#import numpy as np
# THL data comparison removed
SUSPECTIBLE = "S"
INFECTIOUS = "I"
RESISTANT = "R"
# - The length of these lists will be the number of the simulated days
# - The list will be filled with the number of the infected population on the
# day corresponding to the index ... |
5f4714836030508087ef347558ef03327751f3fe | Rishi-121/BestEnlist-Intership-Repo | /Day-13/Coffee-Machine-Program.py | 4,032 | 3.921875 | 4 | # Coffee Machine Problem
class coffeMachine:
# Initialize the Coffee Supplies
def __init__(self, water, milk, coffee, money):
self.water = water
self.milk = milk
self.coffee = coffee
self.money = money
# Check whether the resources are available or not
def checkResour... |
bbc57777424f696844f7e498b402b19df329f09b | marissabhavsar/dcfanalysis | /collectData.py | 3,129 | 3.515625 | 4 | import requests
from bs4 import BeautifulSoup
from csv import writer
def getTicker():
ticker = input("Enter Ticker: ").upper()
return ticker
#for each separate website link (3) have a function that collects necessary data and organizes it
#income statement: total revenue, net income (in drop down)
#cash f... |
d7cf71352e44c25f0847693cd6c0bd090f7badd8 | tanvir07-ops/python_oop | /app.py | 1,902 | 4.1875 | 4 | #person Class
class Person:
'''
This is a simple Class
'''
def __init__(self,name,email):
self.__name = name
self.__email = email
pass
def log(self):
print(self.__dict__)
@property
def name(self):
print(self.__name)
@name.setter
def nam... |
852e185bf96fab51cbd858c1c2609ddd5c2df74d | Neo-X/mobilemanipulation-tf2 | /softlearning/environments/gym/spaces/discrete_box.py | 4,613 | 3.53125 | 4 | import numpy as np
from collections import OrderedDict
from gym.spaces import Space
class DiscreteBox(Space):
"""
A discrete action space, but each dicrete action is parameterized by a [a, b]^d vector,
where d is a non-negative integer that can be different for each discrete action.
Each discrete a... |
1c2342cc83070a0c97cdfb7cad3d2c9dc07bb555 | victoribironke/prime-numbers | /Prime Number Checker.py | 388 | 3.8125 | 4 | import time
def checker(num):
lists = [x for x in range(num + 1)]
lists.remove(1)
lists.remove(num)
lists.remove(0)
if num == 1:
print("1 is not a prime number.")
else:
for i in lists:
if num % i == 0:
print(f"{num} is not a prime number.")
break
else:
print(f"{num} is a prime number.")
num... |
f115e160a4b906fb3c7eab0824c3596bdf5703d8 | ynagi2/atcoder | /abc166d.py | 349 | 3.5625 | 4 | def main():
x = int(input())
# 151 ** 5 - 150 ** 5 > 10 ** 9
# したがって,プラマイ151くらいで調べればいい
for a in range(-151, 151):
for b in range(-151, 151):
if a ** 5 - b ** 5 == x:
print("{} {}".format(a, b))
exit(0)
if __name__ == '__main__':
main() |
d374f93a7bcc43947b7a43561176c827c969246f | ynagi2/atcoder | /abc159c.py | 45 | 3.546875 | 4 | l = int(input())
a = float(l/3)
print(a**3) |
2de5328f0cd75c8f7bf933cec1d7d8e5f933c1cb | VB6Hobbyst7/contour_sorting | /interval_tree.py | 3,730 | 3.734375 | 4 | #!/usr/bin/env python3
"""An interval tree implementaion."""
class IntervalTree(object):
"""A python-based interval tree"""
def __init__(self):
self.segments = [] # references to arc, lines, etc.
self.left_sorted_contents = []
self.right_sorted_contents = []
self.left_child = ... |
63040350448959a4ab73534f0c6cb0e24823e7c9 | LyricBao/python-learning | /python2019/02/2.2.py | 936 | 3.984375 | 4 | #code practise
# DesMond
num1 = 9 + 2
print("add:%d" % num1)
num2 = 9 - 2
print("jian:%d" % num2)
num3 = 9 * 2
print("cheng:%d" % num3)
num4 = 9 / 2
print("chu:%d" % num4)
#取整
num5 = 9 // 2
print("取整除:%d" % num5)
#取余数
num6 = 9 % 2
print("取余数:%d" % num6)
#取次幂
num7 = 9 **2
print("取次幂:%d" % num7)
a = 7
b = 3
print("a =... |
7de6bad569c2cc46fcce4afe994b73ad1823746e | LyricBao/python-learning | /python2019/04/4.9.py | 541 | 4.09375 | 4 | # code learning practiced by desmond
# date 2019.11.16
'''
输入 一 行字 符, 分别统计出其中英文字母 、 空格、数字和其他字符的个数
'''
string = str(input("plz input ur string"))
print(string)
space = 0
letters = 0
else_str = 0
for i in string:
if i == " ":
space = space +1
elif i >= "A" and i <= "Z" or i >= "a" and i <= "z":
... |
df30cc6161e423207f3a74fde2916f7979123610 | LyricBao/python-learning | /python2019/02/2.6.py | 261 | 3.71875 | 4 | #code learning
# author Desmond
# date 2019.11.14
num1 = int(input("please input a int num"))
#change num
print("十进制:%d" % num1)
print("八进制: %s" %oct(num1))
print("十六进制(大写): %s" % hex(num1))
print("二进制:%s" % bin(num1)) |
8daa1759b80515be59cc5cb040a4df33639f5229 | LyricBao/python-learning | /python2019/05/5.7.py | 558 | 4.0625 | 4 | # code learning,practiced by desmond
# date 2019.11.18
'''
定义一个函数,该函数可接收一个list 作为参数,该函数用于去除list 中重复的元素。
'''
def list_remove(list1):
list_new = list({}.fromkeys(list1).keys())
return list_new
list_length = int(input("plz input the length of the list"))
list_origin = []
for i in range(list_length):
list_o... |
73db23e9d9ac554d7ff8d362fae57f04c679baf6 | LyricBao/python-learning | /python2019/04/4.5.py | 577 | 3.96875 | 4 | # 使用循环输 出空心菱形 。 例如用户输入 7 (用户输入偶数, 则提示不能打印 ), 输出如下结果:
height = int(input("plz input the height"))
if height % 2 == 0:
print("can not print")
else:
half_height = height // 2
print(half_height)
for i in range(half_height):
half_blank = " " *(int((2 * half_height -1-(2 * i + 1)/2)))
if i ==... |
126499da00ec87db4f0029f412b87a04a7f64209 | dnplkv/hw_15_Polyakov | /src/dfs.py | 3,281 | 3.5 | 4 | import matplotlib.pyplot as plt
time_values = []
def benchmark(func):
import time
def wrapper(a, *b):
start = time.time()
res = func(a, *b)
end = time.time()
print('[*] Время выполнения: {} секунд.'.format(end - start))
time_values.append(end - start)
return res... |
e0a587a9e4d445942d455891532a09453bd37101 | QSuperfly/AdventOfCode2020 | /Day 8.1/Day8.1Script.py | 1,950 | 3.59375 | 4 | import re
# Declare and assign some static information
example_filename = "Example.txt"
input_filename = "Input.txt"
output_filename = "Output.txt"
# Variables to use
accumulator = 0
jumps = 0
no_operation = 0
# Get list of lines from file input
def get_file_input():
with open(input_filename, 'r') as file:
... |
919514d2eadf79d4f171c3d5d1909d6a337e4211 | QSuperfly/AdventOfCode2020 | /Day 6.1/Day6.1Script.py | 623 | 3.59375 | 4 |
# Declare and assign some static information
example_filename = "Example.txt"
input_filename = "Input.txt"
output_filename = "Output.txt"
# Variables to use
sum_of_yes_answers = 0
yes_questions = []
# Read file and Loop through lines # More readable
for line in open(input_filename, 'r').readlines():
# print(line... |
54e94df46fafb57696135b46bc3a3585cbc0199e | shanqq/python_program_practice | /prime_no.py | 322 | 3.875 | 4 | n=int(input("Enter number upto which you want to find prime no."))
for i in range(2,n+1):
count=0
for j in range(2,(i//2)+1):
if i == 2:
print(i)
break
elif i%j == 0:
count=1
break
else:
pass
if count == 0:
print(i)
... |
62b6b0522ae2049299f6f0485f3f48fddfc45741 | RenaKunisaki/StarFoxAdventures | /modelviewer/gl/Geometry/ellipse.py | 13,860 | 4.25 | 4 | '''a pythonic Ellipse.
Super awesome.
'''
import math
from . import Point
from .line import Line, Segment
class Ellipse(object):
'''
Implements an ellipse in the XY plane with the supplied radii.
Returns a unit ellipse centered on the origin in the XY by default.
Usage:
>>> from Geometry impor... |
05d26ee9099bd817b665ff17b22dbb2d2fb3dc66 | RenaKunisaki/StarFoxAdventures | /modelviewer/gl/Geometry/triangle.py | 20,631 | 4.0625 | 4 | ''' a pythonic Triangle
'''
import math
import collections
import itertools
from . import Point, Segment, Circle
from .constants import Epsilon, Half_Pi, nearly_eq, Sqrt_3
from .exceptions import *
class Triangle(object):
'''a pythonic Triangle
Implements a Triangle object in the XY plane having three
n... |
631574b48da15331f564f48abfba61c69360e2b8 | charlesluch/Code | /Py4eSpec/01-Py4e/myCode/computePay.py | 966 | 4.34375 | 4 | # 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Award time-and-a-half for the hourly rate for all hours worked above 40 hours.
# Put the logic to do the computation of time-and-a-half in a function called computepay() and use the function to do the computation.
#... |
224a0428bfa61a020187e8f7ccc18d503761bd68 | elaverdiere1/100_days_code | /day1_name_generator.py | 419 | 4.5 | 4 | #1. Create a greeting for your program.
print("Welcome to Band Name Generator")
#2. Ask the user for the city that they grew up in.
city = input("what is the name of the city you grew up in?\n")
#3. Ask the user for the name of a pet.
pet = input("what is a name of a pet you owned?\n")
#4. Combine the name of their cit... |
e21a0ba032dce9c1b0e504b3455aa5fc8eb67f35 | elaverdiere1/100_days_code | /day_7_hangman/main.py | 939 | 4.03125 | 4 | import random
import hangman_words
import hangman_art
chosen_word = random.choice(hangman_words.word_list)
word_length = len(chosen_word)
end_of_game = False
lives = 6
print(hangman_art.logo)
#Create blank list
word_empty = ['_'] * len(chosen_word)
#checking for end condition
while lives != 0 and '_' in word_empty... |
f83db0c033dd36685bb40822d7b1595d17371429 | elaverdiere1/100_days_code | /day22_turtle_crossing/scoreboard.py | 522 | 3.5 | 4 | from turtle import Turtle
FONT = ("Courier", 24, "normal")
class Scoreboard(Turtle):
def __init__(self, score):
super().__init__()
self.penup()
self.color('black')
self.hideturtle()
self.update_score(score)
def update_score(self, score):
self.clear()
s... |
437f47c93ca4cbb99d874114653c33dd945a4efe | Minho0310/2020_programming | /0606/func14.py | 318 | 3.828125 | 4 | def pzn(num):
if num > 0:
tmp = 1
elif num == 0:
tmp=0
else:
tmp= -1
return tmp
while True:
n=int(input("정수:"))
r=pzn(n)
if r == 1:
print("양수")
else r == 0:
print("0")
break
else:
print("음수")
|
dd801077f61c38eaeaafa1a142b390767d98f1a0 | Minho0310/2020_programming | /0606/func10.py | 472 | 3.953125 | 4 | def calc(num1,num2,act="+"):
if act=="+":
res= num1 + num2
elif act=="-":
res= num1 - num2
elif act=="*":
res= num1 * num2
elif act=="/":
res== num1 / num2
else:
res== "잘못된 연산기호입니다."
return res
n1=int(input("첫번째 정수 입력:"))
n2=int(input("두번째... |
23a226d674a85fe3c59187889b8923e66b5ce8db | Minho0310/2020_programming | /0523/prob116.py | 157 | 3.53125 | 4 | a=input("시각을 입력하세요 ex,11:00처럼 : ")
b=int(a[3:])
if b==00:
print("정각입니다")
else:
print("정각이 아닙니다")
|
b528ffb5131ae37c8cc8fa9003c57f64de114d3d | Minho0310/2020_programming | /0523/prob114.py | 107 | 3.78125 | 4 | a=int(input("숫자를 입력하세요: "))
if 0<= a <= 255:
print(a+20)
else:
print('255')
|
53e34b4cd4330901f302b04b2dda92d59de5d5d7 | Minho0310/2020_programming | /0523/prob115.py | 109 | 3.78125 | 4 | a=int(input("숫자를 입력하세요: "))
if 0<= a <= 255:
print(a-20)
elif a<0:
print('0')
|
f7dd5377fe5800ef293a056b754ef4a9f53bc7e9 | theerthan/PyML | /Ch02/PS2-17.py | 1,156 | 3.796875 | 4 | from numpy import mean
from math import sqrt
def cov(x,y,pxy):
"""Covariance of a joint distribution
Defined as summation of x(i) times y(i) times P(X=x(i),Y=y(i)) over
mean(x) times mean(y)
"""
x_mean = mean(x)
y_mean = mean(y)
cov_l = [x[i]*y[j]*pxy[i][j] for i in range(len(x)) for j in r... |
be6ce0379bafed6cfa7e61d4a5fd0c58e21d03a5 | starhqy2/count_string_chars | /count_string_chars.py | 460 | 3.75 | 4 | def count_string_chars(string):
count = 0
pre_char = ''
last_index = 0
for char in string:
if char == pre_char:
continue
else:
for char_index in range(last_index, len(string)):
if char == string[char_index]:
count += 1
else:
print(char+":"+str(count)+' times')
count = 0... |
69f861a5ad27e6a98d002fa1435299fd1115a943 | nesterenko-a/Telegram-Bots | /for.py | 165 | 3.53125 | 4 | xren = ['1','2','3']
x1 = 0
for xro in xren:
#print(xro)
x1+=1
print("Привет" + str(x1))
spisok = list (range(1,10))
print(max(spisok))
print(min(spisok))
|
30addbf79b9a958ed30e2423068e3d9dc97423d3 | frozen-plasma/dp | /coinchange-numways.py | 642 | 3.578125 | 4 | '''
Given a value <amt>, if we want to make change for <amt> cents, and we have infinite supply of each of
<coins> = { S1, S2, .. , S<n>} valued coins, how many ways can we make the change?
'''
def coinchange(coins, n, amt):
table = [[0 for j in range(n)] for i in range(amt+1)]
for i in range(n):
table... |
18f45f9d7d12ee08eef96da8a0bb0bcd7ee6e5c8 | ravelosalama/Intermodal | /serial container validate.py | 1,595 | 3.625 | 4 |
# Programa para validar serial de contenedores segun digito de verificacion.
# Fuente del proceso y formulas:https://es.wikipedia.org/wiki/Contenedor#Identificaci%C3%B3n
# Codificado por:Jose Ravelo / Mayo 2020.
#Asignacion de valores sincronos de dos Tuplas para generar un diccionario.
k = ('A','B','C','D','E','F','... |
0f9a0fb12ef84bb9030da5923dede73292272c66 | tkuye/sorting-algos | /selection.py | 1,241 | 3.6875 | 4 | import random
arr = [9,8,7, 7,6, 4, 2,1, 2, 4]
arr1 = [9,8,7, 7,6, 4, 2,1, 2, 4]
arr2 = [9,8,7, 7,6, 4, 2,1, 2, 4]
for i in range(10000):
arr.append(i)
arr1.append(i)
arr2.append(i)
random.seed(1223434)
random.shuffle(arr)
random.shuffle(arr1)
random.shuffle(arr2)
def selection(arr):
iter_count = ... |
ad509e50ff2b34110ea233e89af0bc5963a1130d | kuncao0228/ComputerVision | /ComputerVisionCourseHays/projects/proj1/code/student_code.py | 3,788 | 4 | 4 | import numpy as np
def my_imfilter(image, filter):
"""
Apply a filter to an image. Return the filtered image.
Args
- image: numpy nd-array of dim (m, n, c)
- filter: numpy nd-array of dim (k, k)
Returns
- filtered_image: numpy nd-array of dim (m, n, c)
HINTS:
- You may not use any libraries that do... |
b8ce97f597c94894c7675f7c10a2e08df818a27d | YuyangL/TurbulenceMachineLearning | /Test/Test_VariableUpdate.py | 1,265 | 3.5625 | 4 | import numpy as np
def update(a):
# Has to be += to update internally, doesn't work with a = a + 10
a += 10
a = np.arange(5)
print('\nBefore internal update: {}'.format(a))
update(a)
print('\nAfter internal update: {}'.format(a))
print('\nAgain: ')
def update_lst(a):
a += [10]
b = [1,2,3]
print('\n... |
e9d8c713eb37309aa63f6f1d1fdd7bc36ae915d9 | danicon/Curso-IPE | /08Aula07-10/ex03.py | 268 | 3.6875 | 4 | Li = []
d=0
while d < 10:
p = int(input('Digite os números: '))
if d == 0 or p > Li[-1]:
Li.append(p)
else:
for x in range(5):
if p <= Li[x]:
Li.insert(x,p)
break
d+=1
print(Li[::-1]) |
b5f148f9cf697f331d2220a68655d3bccee253b7 | danicon/Curso-IPE | /02Aula02-09/ex025.py | 283 | 3.703125 | 4 | fumante = int(input('\n Quantos cigarros por dia você fuma? \n'))
anos = float(input('\n Quantos anos de fumante? \n'))
vida = (fumante * anos)-10
print('\n Você fuma {0} cigarros por dia e já é fumante a {1} anos. Você perdeu {2} dias de vida \n'.format(fumante, anos, vida)
) |
748de9fec7d6dc0ef3727e4fca5f0f9915b1b048 | danicon/Curso-IPE | /06Trabalhos/ex01.py | 978 | 3.921875 | 4 | # Faça uma solução lógica em Python para resolver a o problema do Pedro, que comprou um saco de ração com peso em quilos. Ele possui três gatos, para os quais fornece a quantidade de ração em gramas. A quantidade diária de ração fornecida para cada gato é sempre a mesma. Faça uma lógica que receba o peso do saco de raç... |
ec8b471106c4bb11a54340667c088413f8165720 | danicon/Curso-IPE | /02Aula02-09/ex024.py | 285 | 3.59375 | 4 | km = float(input('\n Quantos Km o carro percorreu? \n'))
dias = int(input('\n Quantos dias de uso do carro alugado? \n'))
alugado = (0.15 * km) + (60 * dias)
res = '\n O carro alugado por {0} dias, percorridos por {1} km/h. Totalizou em R${2} \n'.format(dias, km, alugado)
print(res) |
fbc111c2386d3c59baeade17f702b77c20135f48 | MachineLearningUCG2019/MachineLearning | /Ronald/Exam Machine Learning Ronald van Hal.py | 3,088 | 3.875 | 4 | # Question 1 A
print("\n------------\n")
from math import log2
list_probabilities = [[1/6, 1/6, 1/6, 1/6, 1/6, 1/6],
[1/2, 1/3, 1/4, 1/5, 1/6, 1/7],
[1/2, 1/4, 1/6, 1/8, 1/10],
[1/2, 1/2, 1/2, 1/2, 1/2, 1/2]]
list_entropies = []
for ... |
5f0d63a1d43b4024c86816bb8a543ce04f114841 | kk0walski/q-learning-game | /rl_ttt/game.py | 2,337 | 3.515625 | 4 | """
Tic-Tac-Toe game module
"""
import enum
class FieldStates(enum.Enum):
EMPTY_FIELD = ''
X_MARKER = 'X'
O_MARKER = 'O'
class GameStatus(enum.Enum):
PLAYING = 0
DRAW = 1
X_WIN = 2
O_WIN = 3
class TicTacToe(object):
BOARD_SIZE = 3
"""
BOARD:
-------------
| 0 | 1 |... |
4dac18607cd56bcfb0602aff4067ac38653e42ed | zhou-yuhan/UCB-CS61A-Structure-and-Interpretation-of-Computer-Programmes | /labs/lab01/lab01.py | 1,492 | 4.34375 | 4 | # -*- coding: utf-8 -*-
# @Author: 周裕涵 HumpreyChou
# @Date: 2021-01-16 00:07:56
# @Last Modified by: 周裕涵 HumpreyChou
# @Last Modified time: 2021-01-16 00:26:41
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
... |
6aaa550a577b8ede739d8e49dae3a95153e0e5af | NipunaMadhushan/HackerRank-Interview-Preparation-Kit | /Dynamic Programming/Max Array Sum.py | 434 | 3.578125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def maxSubsetSum(arr):
freq = [arr[0], max(arr[0], arr[1])]
for i, num in enumerate(arr[2:]):
freq.append(max(freq[-1], freq[-2]+num, freq[-2], num))
return freq[-1]
if __name__ == '__main__':
n = i... |
75f01328edbacb6a9070594d05f30430dc931da4 | NipunaMadhushan/HackerRank-Interview-Preparation-Kit | /Dictionaries And HashMaps/Two Strings.py | 430 | 3.546875 | 4 | def sub_seq(string_1, string_2):
set_1 = set(string_1)
set_2 = set(string_2)
com = set_1.intersection(set_2)
if len(com) > 0:
return "YES"
else:
return "NO"
if __name__ == '__main__':
T = int(input().strip())
for t in range(T):
string_1 = input().... |
2e6cd60b6581ea3156c9da725bda8a404279e680 | NipunaMadhushan/HackerRank-Interview-Preparation-Kit | /String Manipulation/Making Anagrams.py | 631 | 3.90625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the makeAnagram function below.
def makeAnagram(a, b):
set_a = set(a)
set_b = set(b)
set_all = list(set_a.intersection(set_b))
counts_a = [a.count(k1) for k1 in set_all]
counts_b = [b.count(k2) for k2 ... |
eae21eb755dba9c505452df254bbe06ec14e7686 | ashutoshaay26/BugFreeCode | /HackerRank/ProjectEuler/ProjectEuler 3.py | 277 | 3.921875 | 4 | import math
def prime(num):
last=-1
while(num%2==0):
last=2
num=num//2
s=int(math.sqrt(num))
for j in range(3,s+1):
while(num%j==0):
last=j
num=num//j
j+=2
if num>2:
last=num
return last
t=int(input())
for i in range(t):
n=int(input())
print(prime(n)) |
19cf17a89a70d701359461a155f7b309fcfe066d | alexandrumeterez/GeneDraw | /population.py | 1,363 | 3.5625 | 4 | from individual import Individual
from parameters import *
import random
class Population(object):
def __init__(self):
self.individuals = []
for _ in range(POPULATION_SIZE):
self.add_individual(Individual())
self.individuals.sort(key = lambda x: x.fitness, reverse = True)
... |
58ed8dab01458899e4032c016f814edcadc1f7b3 | dvukadinovic/python_vezbice | /uvod/petlje_fileovi_funkcije.py | 4,606 | 3.65625 | 4 | """
Skripta broj 2.
Rad sa petljama (for, while, if), ucitavanje i upisivanje u file kao i
definisanje funkcija.
azurirano: 18. mart 2018.
"""
# lista
l = [1, 5.3, 'Python3', False, 1.232e-2]
"""
for petlja - izvrsavamo neki niz operacija zadati broj puta
ili iteriramo po datom nizu
"""
# u prevodu: za svaki 'ele... |
57c74b19c1e6376c0ad739fffc0148edc4cdedc9 | tmhdgsn/mancmancala | /mancalapy/side.py | 159 | 3.8125 | 4 | from enum import Enum
class Side(Enum):
NORTH = 0
SOUTH = 1
def opposite(self):
return Side.SOUTH if self == Side.NORTH else Side.NORTH
|
958550fe1480b0a98e7aff8e4f50a7bb42210fde | johanvergeer/python-design-patterns | /python_design_patterns/solid/open_closed_principle_after.py | 456 | 4 | 4 | from abc import ABC, abstractmethod
class Weapon(ABC):
@abstractmethod
def use(self) -> None:
...
class Sword(Weapon):
def use(self) -> None:
print("Swinging the sword.")
class Bow(Weapon):
def use(self) -> None:
print("Shooting an arrow")
class Orc:
def attack(self, ... |
ae29a21711ea937a20c878e0057467882d404114 | mayraamc/uri-obi | /lista3-ex4.py | 344 | 3.5625 | 4 | # outro jeito de resolver isso ao invés de pedir a idade logo no começo
# é setando a idade com um numero > 0 para entrar no while
idade = int(input())
soma = 0
c = 0
media = 0
while idade > 0:
soma = soma + idade
c+=1
idade = int(input())
media = soma / c
print("{:.2f}".format(media))
... |
17613c914fcb8178d06420297c41dc3eb9255a63 | mayraamc/uri-obi | /lista1-ex2.py | 88 | 3.671875 | 4 | raio = float(input())
pi = 3.14159
area = (raio**2)*pi
print("A=%0.4f" %area)
|
5a04d826f43e3d6252778481e59f47413095563e | abrar-uddin/Pong | /pong.py | 3,162 | 3.578125 | 4 | import turtle
wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
# Player Score
score_a = 0
score_b = 0
# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape('square')
paddle_a.color('white')
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_... |
10833ee89d3954af317c8dce0ea6516481e24ca8 | pwr-kstasinski/Z03-24h | /Lab 4/z1.py | 344 | 3.515625 | 4 | # bez drzewa/slownika:
equation = input("Podaj rownanie: ")
try:
score = eval(equation)
print(equation + " = " + str(score))
except SyntaxError:
print("Blad skladniowy np. przy 9-")
except TypeError:
print("Blad typu np. przy 3(2-4)")
except NameError:
print("Nie nalezy uzywac liter oraz nieodp... |
e9bf7cb5f754b1efdea51bbc15ff568f7c150275 | enriquesleon/polycube | /polycube/pieces.py | 278 | 3.734375 | 4 | from collections import namedtuple
import numpy
class Piece:
cubes = set()
def get_cube_from_coord(self,line):
line_parts = line.split(',')
if len(line_parts) is not 3:
raise ValueError('Line not in proper format')
cube = [int(x) for x in line_parts]
return cube
|
590463ad832f16841bcdd9647d73520383e2a61f | joostrijneveld/Euler-Project | /Python/problem63.py | 309 | 3.640625 | 4 | import math
def diglen(n):
return len(str(n))
def main():
count = 0
for i in range(100):
for j in range(100):
n = pow(i,j)
if diglen(n) == j:
print "j = " + str(j) + " LEN= " + str(diglen(n)) + "Result: " + str(pow(i,j))
count = count + 1
print count
if __name__ == "__main__":
main() |
93deec49c711a9d64230d38e3731f55211100ed8 | James-Burgess/computerScience | /sort/sort.py | 367 | 3.734375 | 4 | from random import randint
n = [randint(0,250) for x in range (100)]
print("Un-ordered List:\n" + str(n))
def sorter(myList):
i = c = 0
while (i != (len(myList)-1)):
c += 1
if myList[i] > myList[i+1]:
myList[i], myList[i+1] = myList[i+1], myList[i]; i=0
elif: i += 1
return(str(myList),str(c))
print("Orde... |
2deafcba29cdb13047f9cf3de2ea4268e883eb30 | James-Burgess/computerScience | /seb/seb.py | 362 | 3.71875 | 4 | import turtle
from random import randint
wn = turtle.Screen()
wn.colormode(255)
boo = turtle.Turtle()
boo.speed(0)
wn.bgcolor("black")
boo.shape("turtle")
def circle():
for i in range(180):
boo.fd(5)
boo.rt(2)
for j in range(36):
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
boo.pencolor((r, g,... |
06e63fdb111f701c47a606d6d5a43a4b78c3097c | maisun13/CS112-Spring2012 | /day7.py | 148 | 3.625 | 4 | #!/usr/bin/env python
num1 = raw_input("enter a number")
num2 = raw_input("enter a number")
num1 = int(num1)
num2 = int(num2)
print num1 + num2
|
af498ed1f73cf8bb7335062fd492b3b0e60078cd | maisun13/CS112-Spring2012 | /day4.py | 180 | 3.796875 | 4 | #!/usr/bin/env python
count=0
while count <=0:
count=raw_input("Count down from what: ")
count=int(count)
while count>0:
print count
count-=1
print "Blastoff!"
|
8920e0e349788434a2e08945369c6ce2679611aa | maisun13/CS112-Spring2012 | /day8-2.py | 190 | 3.765625 | 4 | #!/usr/bin/env python
def ftoc(temp):
cent = temp - 32
cent *= 5
cent /= 9
return cent
num = int(raw_input("enetr a temperature in F: "))
print "in C that is: ", ftoc(num)
|
af00e2bef697738d35db5a43d777b4d52f0936e7 | hackrmann/learn_python | /list_comprehension.py | 496 | 3.734375 | 4 | def func(p):
p = p*10
return p
hey = ["meow","bow"]
hey2="hello".join(hey)
print(hey2)
for i in range(1,21,2):
print(i,end=" ")
print()
dr = range(1,20)
x=[]
print(range(1,20),dr)
for i in dr:
print(i,end=" ")
x.append(i)
print()
print(dr,x)
x2 = [func(p) for p in x]
print(x2)
print(x)
alph = ['a','... |
96d06cd3f3cd1a0419fe71b476f3dad70e96213f | hackrmann/learn_python | /rock_paper_scissors.py | 857 | 3.96875 | 4 | a = input("Enter player 1's choice: ")
b = input("Enter player 2's choice: ")
if a and b:
if a=='rock':
if b=='paper':
print("player 2 wins")
elif b=='scissors':
print('player 1 wins')
elif b=='rock':
print('draw')
else:
print('invalid ... |
63255fc4a557ec1e8debf8a32b31e55af94a58ae | sasvageangelss1/Img_ | /zhengzebiaodashi.py | 7,846 | 3.59375 | 4 | #coding=utf-8
import re
'''
正则表达式进行格式验证,比如登陆的用户名和密码
'''
# 正则表达式如何制定规则
# compile,制作正则表达式的函数
pattern = re.compile('\w?')
# print(pattern)
print(type(pattern))
# match,只从字符串的开头进行匹配
pattern = re.compile('\d') #规则:一个数字
strs1 = 'abc'
strs2 = '1a'
print(re.match(pattern, strs1)) #查看匹配结果,要用group
print(re.match(pattern, s... |
b92d753d2923d658e1ad1ea9fa2aca21788d052e | LucianoCassarini/Tripletes | /main.py | 3,553 | 3.734375 | 4 |
#===========================Auxiliares=================================
#devuelve nombre del usuario
def name(line):
posicion = line.find(",")
return line[0:posicion]
#devuelve página visitada
def pag(line):
posicion1 = line.find(",")
aux = line[(posicion1+1):]
pos2 = aux.find(",")
return aux... |
133e01b486a36ec2384206c648c640895d8fcb70 | oreanroy/learn_modules | /lpyHardway/curious/copyex.py | 406 | 3.796875 | 4 | import copy as cop
l1 = [1, 2, 3, 4]
# soft copy
l2 = cop.copy(l1)
# deep copy
l3 = cop.deepcopy(l1)
print (l2)
print (l3)
print ("The effect of soft copy")
l1[1] = 8
print("this is l1 after l2's alternation ")
print(l1)
print("this is l2 after alternaion")
print(l2)
print("The effect of hard copy")
l1[2] = 8
p... |
ff04e09c94fd3aab93b2df448f829af5edc6c69c | vishnuak15/py_ws | /8.py | 158 | 3.5 | 4 | import random as rn
lst = []
for i in range(1,101):
if i % 3 == 0 and i % 6 == 0 and not i % 9 ==0:
lst.append(rn.randint(1,1000))
print(lst) |
ca577b0b16bfc26dd5d2a8cb294ae8ad13de5162 | haru-256/ExpertPython3_Source | /chapter5/instance_counting.py | 931 | 3.703125 | 4 | from random import randint
class InstanceCountingClass:
instances_created = 0
def __new__(cls, *args, **kwargs):
print('__new__() called with:', cls, args, kwargs)
instance = super().__new__(cls)
instance.number = cls.instances_created
cls.instances_created += 1
retur... |
35cdd73e77bcaeb3b9addd2a63317f5314d7e8f1 | haru-256/ExpertPython3_Source | /chapter15/async_cooperative_wait.py | 730 | 3.875 | 4 | """
「非同期プログラミング」の節で登場するサンプルコード
ブロックする命令の呼び出し時にイベントループの制御を解放し、2つのコルーチンを協調的に動作させる。
"""
import random
import asyncio
async def waiter(name):
for _ in range(4):
time_to_sleep = random.randint(1, 3) / 4
await asyncio.sleep(time_to_sleep)
print(f"{name} は {time_to_sleep} 秒待ちました")
async def ma... |
f861a0d32f7f3169b44a4d49ebba770b18012f4a | dona126/Python-Programming | /Basics/conditionals.py | 521 | 4.28125 | 4 | #Use of if,elif and else statements.
#Example 1
age=int(input("Enter age:"))
if(age>18):
print("Hey, i can vote!")
elif(age==0):
print(":)")
else:
print("I can't vote.")
#Example 2
score =float( input("Enter Score: "))
if score>=0.0 and score<=1.0:
if( score >= 0.9):
print("A Grade")
elif( score... |
acb20a11f7ea9c0c258726621c975bdf1b3e1f98 | dona126/Python-Programming | /Practice/valleyCount.py | 694 | 4.5 | 4 | # A hiker moves a step UP or a step DOWN. Start and end at sea level.
# Mountain- start with step UP and end with step DOWN.
# Valley- start with step DOWN and end with step UP.
# Find number of valleys walked through.
# Uses;
# U for UP
# D for DOWN
#Input:
#path="U D D D U D U U"
#Output:1
#
def valleyCount(pat... |
3c129f05ed93c53bcccd3fbc60a8c211a37ab71d | bagreen/Random-Python | /Recipes.py | 5,419 | 3.640625 | 4 | from typing import List
import argparse
import decimal
import random
def process_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-r', help='Picks out random recipes to try', action='store_true')
parser.add_argument('-m', help='Manually pick out recipes to try', action='store_true')
... |
056906462a8243798e225e915cccba7a53d33c02 | VANTABC/section4 | /4-6-3.py | 405 | 3.59375 | 4 | import pandas as pd
import numpy as np
#랜덤으로 DataFrame 생성
#df = pd.DataFrame(np.random.randint(0,100,size=(100,4)), columns=['ONE', 'TWO','THREE', 'FOUR'])
df = pd.DataFrame(np.random.randn(100,4), columns=['ONE', 'TWO','THREE', 'FOUR'])
print(df)
df.to_excel("C:\python\\section4\\result_s2.xlsx", index=False)
df.to_... |
2e221fb6f03c13aa5ebf7c90483923ec5e635224 | VANTABC/section4 | /4-7-4.py | 295 | 3.75 | 4 | import matplotlib.pyplot as plt
#리스트 범위(x축)
x = list(range(0, 256))
print(x)
#리스트 범위(y축)
y = [v*v for v in x]
#for v in x:
# y.append(v*v)
print(y)
#차트 설정(x에 인덱스, y에 컬럼을 넣으면 차트 완성)
plt.plot(x,y,'bo')
#차트 실행
plt.show()
|
48749c888290aa6bfc65e12325ce43684f648b8d | jaycer95/holbertonschool-interview | /0x00-lockboxes/0-lockboxes.py | 417 | 3.640625 | 4 | #!/usr/bin/python3
""" Lockboxes """
import numpy as np
def canUnlockAll(boxes):
"""Determine if all the boxes can be opened"""
if boxes[0] == []:
return False
list = [0]
for i in range(len(boxes)):
for j in boxes[i]:
if j not in list and j < len(boxes) and j != i:
... |
82fba875bbd4c0af1b3834912842f4c057b12d77 | kaviarasankk/the-coding-interview | /problems/missing-number/missing-number.py | 179 | 3.796875 | 4 | def missing_number(l):
non_missing = sum([i for i in range(1,len(l)+2)])
missing = sum([i for i in l])
return non_missing - missing
print missing_number([1,2,3,4,6])
|
31c114bff52bcfe0ca5c9cc5bf951ff266efd639 | msipola/CBM101 | /K_Mathematical_Modeling/Section 3/solutionExercise1.py | 1,188 | 4.375 | 4 | from IPython.display import display, Latex
print("First, we expand the expression of the random variable of which we want to compute the expectation value:")
display(Latex('$ (N-<N>)^2 = N^2-2*N*<N>+<N>^2$'))
print("because <N> is just a number.")
print("")
print("Then we compute the expectation value of the sum o... |
58e0e832d357e72fd87872aae15c0985972bdb8a | steingrd/euler | /problem4.py | 525 | 3.96875 | 4 | #!/usr/bin/env python
# Copyright (c) 2008 by Steingrim Dovland <steingrd@ifi.uio.no>
from euler import palindrome
# A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 * 99.
#
# Find the largest palindrome made from the product of two 3-d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.