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 |
|---|---|---|---|---|---|---|
0bb687e8e8af5de27e6a4d7fb3c64d32e902fe42 | toufiq007/Python-Tutorial-For-Beginners | /chapter seven/exercise1.py | 1,024 | 4.1875 | 4 |
# def cube_func(x):
# cube_dic = dict()
# for i in x:
# num = i**3
# number_dic = {
# i : num
# }
# cube_dic.update(number_dic)
# return cube_dic
# number = list(range(1,10))
# print(cube_func(number))
# make a function that function take a single... |
4dfd57b5c9eb6bd23c64a32839c568cb9264f4e7 | toufiq007/Python-Tutorial-For-Beginners | /chapter seven/word_counter.py | 495 | 3.6875 | 4 |
# make a letter counter
# def word_counter(words):
# counter = {}
# for char in words:
# counter[char] = words.count(char)
# return counter
# print(word_counter('limonnn'))
# def word_counter(x):
# counter = {}
# for i in x:
# counter[i] = x.count(i)
# return counter
# p... |
e624a05600178ddc779ed8f0c552380ad76b6d7e | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/enumerate_func.py | 584 | 4.34375 | 4 |
# we use emumerate function with for loop to tract the position of our item
# item in iterable
# how we can use without enumerate function
# names = ['limon','toufiq','mostafiz','salman','tamim']
# pos = 0
# for i in names:
# # print(f' {pos} --> {i} ')
# pos += 1
# show the output on below
# 0-->... |
4dc27bfcc459e5a66e85c8cd84027676b72d82cf | toufiq007/Python-Tutorial-For-Beginners | /chapter five/exercise3.py | 733 | 4.21875 | 4 |
names = ['abc','def','ghi']
# make the reverse in every list item
def reverse_list(x):
reverse_item = []
for i in range(len(names)):
pop_items = names.pop()
reverse_item.append(pop_items)
return reverse_item
print(reverse_list(names))
words = ['abc','def','ghi']
def reverse... |
02cf61ee3cd2d18ec19a04d54cfe74b61f4a4f71 | toufiq007/Python-Tutorial-For-Beginners | /chapter ten/dic_comprehension_if_else.py | 407 | 3.90625 | 4 |
# dictionary comprehension with if else
# d = {i:i**2 for i in range(1,10)}
# print(d)
odd_even = {i:('even' if i%2==0 else 'odd') for i in range(1,11)}
print(odd_even)
# print(odd_even)
another_list = {-i**2 if i%2!=0 else i**2 for i in range(1,10)}
# print(another_list)
# ltr = dict(another_list)
# print(ltr)... |
2a8bfa39319e57711315bbb2f5d4f59725e8a562 | moniquejro/Python | /ex015.py | 382 | 3.734375 | 4 | #Esse programa vai receber a quantidade de dias
#e a quilometragem rodada com o carro alugado.
#Vai ser calculado o preço a ser pago, sabendo que
#R$60 o dia e R$0,015 por quilometro rodado.
dias = int(input('Quantos dias o carro ficou alugado? '))
km = float(input('Quantos KM rodados? '))
pago = (dias * 60) + (km * 0... |
6f23a27a7834f82724704b9d6e43d17b455c757f | moniquejro/Python | /ex068a.py | 808 | 3.640625 | 4 | from random import randint
v = 0
while True:
player = int(input("Vamos brincar de par ou ímpar? Escolha um número! -> "))
pc = randint(0, 10)
total = player + pc
tipo = ' '
while tipo not in "PI":
tipo = str(input('Você quer par ou ímpar? [P/I] ')).strip().upper()[0]
print(f'Você jog... |
975a74acb8bdcb222d0d626d600c35d42edd01d5 | moniquejro/Python | /ex040.py | 658 | 3.625 | 4 | #AQui vamos analisar uma nota e ver se o aluna(o) foi aprovada(o)
import time #importar calendario, data e etc
print('<>'*25)
n1 = float(input('\033[1mPrimeira nota --->>>\033[m'))
n2 = float(input('\033[1mSegunda nota --->>>\033[m'))
m = (n1+n2)/2
print('PROCESSANDO...')
time.sleep(3) #suspense
if m < 5.0:
print(... |
658f8fc72ece4d389477cfa0a6d2fd333f311a22 | moniquejro/Python | /ex047.py | 283 | 3.984375 | 4 | for c in range (0,51, 2):
print(c, end= '-') #sequencia na mesma linha
print('acabou')
#a forma acima é um programa mais curto e que faz a mesma coisa que o de baixo
#outra forma
for c in range(1, 51):
if c % 2 == 0:
print(c, end=' ')
print('Acabou')
|
ce4e82081492bbe9a93029c6821932f3200a8c9c | moniquejro/Python | /ex037.py | 613 | 4 | 4 | num = int(input('Digite um numero inteiro: '))
print('''Escolha uma das bases para conversão:
[ 1 ] BINÁRIO
[ 2 ] OCTAL
[ 3 ] HEXADECIMAL''')
opcao = int(input('Digite sua opção -> '))
#O Python já tem bibliotecas especificas para conversão, como abaixo:
if opcao == 1:
print('{} convertido para BINÁRIO é igual a ... |
47136c8503821ae3786a3abf960a8882652868ed | amueller/word_cloud | /examples/emoji.py | 2,207 | 3.53125 | 4 | #!/usr/bin/env python
"""
Emoji Example
===============
A simple example that shows how to include emoji. Note that this example does not seem to work on OS X, but does
work correctly in Ubuntu.
There are 3 important steps to follow to include emoji:
1) Read the text input with io.open instead of the built in open. ... |
d4766717aced674e37560ab47bde3c454eec534a | rickardotavares/2021_1_desenv_web_1 | /exercicios_alunos/Paulo Barcelos/Exercicios Apostila 10.03.2021 A.py | 753 | 3.828125 | 4 | ##Cálculo de comissão de vendas do produto X
##Regra de negócio:
##Se vendedor vendeu mais de 20 produtos: valor da venda * 5%
##Se vendedor vendeu mais de 50 produtos: valor da venda * 7.5%
##Se vendedor vendeu mais de 100 produtos: valor da venda * 10%
##Se vendedor vendeu mais de 500 produtos: valor da venda * ... |
67e2f7dc244460ee00277b386c96a097e807e872 | rickardotavares/2021_1_desenv_web_1 | /exercicios_alunos/Olacy Rodrigues/Atividade_Treino_P1.py | 5,272 | 3.859375 | 4 | #1) Desenvolva um código utilizando a linguagem de programação Python para:
#• Construir uma classe para executar cálculos de distância entre pontos.
#• Atributos: dicionário com indicação de pontos cartesianos
#• Métodos: apensar pontos a uma lista; executar cálculo da distância euclidiana e de manhattan;
#===... |
4196d7314070170fb0b20d45c99a811a2e8ab542 | rickardotavares/2021_1_desenv_web_1 | /exercicios_sala/heranca/heranca3.py | 900 | 3.734375 | 4 | class Livro:
def __init__(self, titulo, autor, paginas, preco):
self._titulo = titulo
self._autor = autor
self._paginas = paginas
self._preco = preco
class Revista:
def __init__(self, titulo, editora, preco, periodo):
self._titulo = titulo
self._editora = editor... |
72adc1cbbe2c6b07248cbab3b4d930ce0c4b6499 | rickardotavares/2021_1_desenv_web_1 | /exercicios_alunos/Paulo Barcelos/Exercícios em Aula 03.03.2021.py | 865 | 3.90625 | 4 | print ('Olá, Mundo!')
class MeuMundo:
def _init_(self):
_nome = nome
def set_nome(self, nome):
self._nome = nome
def get_nome(self):
return self._nome
variavel = 9.50
print(variavel)
print(type(variavel))
variavel = 'Maria Torres'
print(variavel)
print(type(var... |
c4ae4f625efe037b7146fa15a7292ee649f2662d | rickardotavares/2021_1_desenv_web_1 | /exercicios_sala/python_intro.py | 815 | 3.6875 | 4 | # x = 37/12
# y = 'Olá'
# z = True
# print(x)
# print('{:.2f}, {}, {}'.format(x, y, z))
# x = 37//12
# print(x)
# x = 37%12
# print(x)
# a = 2
# print(type(a))
# b = 5
# print(b is a)
# # print(a)
# # b = 5
# a += b
# print(a)
# exp = 9 ** (1/2)
# print(exp)
# cesta_frutas = ['maça', 'pera', 'uva']
# print('ma... |
34756c465cc380fb391a3fa1f1e5dba80f7fed9d | evennia/evennia | /evennia/contrib/base_systems/unixcommand/unixcommand.py | 9,979 | 3.546875 | 4 | """
Unix-like Command style parent
Evennia contribution, Vincent Le Geoff 2017
This module contains a command class that allows for unix-style command syntax in-game, using
--options, positional arguments and stuff like -n 10 etc similarly to a unix command. It might not
the best syntax for the average player but can... |
69fdac873c920b006f2c3047c400653920016b74 | ashi422/Cavill-TheSmartCalculator | /raw/calc.py | 472 | 3.90625 | 4 | print{'''
1. addition
2. subtraction
3. multiplication
4. division
'''
}
x=int(input("Enter your choice : "))
y=int(input("Enter first number : "))
z=int(input("Enter second number : "))
if x==1:
a=y+z
print("answer = ",a)
elif x==2:
a=y-z
print("answer = ",a)
elif x==3:
a=y*z... |
5f315312bd69e641c68e4cee7a221585428746b1 | GTBAE-dev/PythonBasics | /Chapter5. 조건문과 반복문.py | 1,651 | 3.578125 | 4 | ''' 5-1. if 문 '''
# if문 : 조건 실행명령문
a = "AA"
b = "BB"
if a == "CC" : # if 조건에 해당하는 실행문
print("a = AA")
elif b == "CC" : # elif 조건에 해당하는 실행문(여러개 설정 가능)
print("b = BB")
else : # 모두 해당되지 않을 때의 실행문
print("c = CC")
''' 5-2. for 문 '''
# for 문 : 다양한 객체 집합을 이용한 반복문
for i in [0, 1, 2, 3, 4] : # i : 리스트 내 객체 순서대로 입력
... |
60d1a977c8ce981a08dcb7be8a7455b5eb586cab | GTBAE-dev/PythonBasics | /etc_zip_library.py | 497 | 3.90625 | 4 | # zip : 여러 list 내 객체를 index 별로 튜플 형태로 묶는 작업
lst_big = ["AA", "BB", "CC"]
lst_small = ["aa", "bb", "cc"]
print(zip(lst_big, lst_small))
print(list(zip(lst_big, lst_small))) # 리스트로 감싸줘야 zip 으로 합친 리스트 확인 가능
# *을 통해 리스트 내 여러 튜플 객체를 index 별로 분리
lst_zip = [('AA', 'aa'), ('BB', 'bb'), ('CC', 'cc')]
print(list(zip(*lst_zip)))... |
7e8012a1c96c6380fc254dd57631e69e66422310 | ezgiigucuyener/RomaniaProblem | /RomaniaMap.py | 2,957 | 4.0625 | 4 | from collections import deque
# Class to represent a graph object
class Graph:
# Constructor
def __init__(self, edges, x, N):
self.adjList = [[] for _ in range(3 * N)]
# add edges to the undirected graph
for (v, u, weight) in edges:
# create two vertices v+N and v+2*N if the weight
# of edge is 3x. ... |
05cceb9f3fe21532a2e8ac23210b609a31b5b790 | GeekyTim/Pinspiring | /code/clockring.py | 3,621 | 3.84375 | 4 | import threading
import time
from datetime import datetime
from time import sleep
import led_config
class ClockRing(threading.Thread):
"""
This clock works with RasPiO InsPiRing Circle
This 12-hour clock script takes the time from the system
and breaks it down into hours minutes and decimal seconds.... |
69c421335ca141bb637d1429edf2d6a97839b82b | kizs3515/shingu_1 | /10.06엑셀/else.py | 127 | 3.6875 | 4 | for i in range(10):
print i,
else:
print "EOP"
a = 0
while a < 10:
print a,
a += 1
else:
print "EOP"
|
c3f0cca2a570aff94b58b4d58f8ff4085364d23c | kizs3515/shingu_1 | /10.13일 파이썬/구구단.py | 568 | 3.796875 | 4 | #-*-coding:utf-8-*-
print "구구단 몇단을 계산할까요(1~9)?"
x=1
while(x<>0):
x=int(raw_input())
if x==0: break
if not(1 <= x <=9):
print "잘못 입력하셨습니다","1부터 9사이 숫자를 입력해주세요"
continue
else:
print"구구단" +str(x) +"단을 계산합니다."
for i in range(1,10):
print str(x) +" X" +str(i) + "=... |
c2a3e8f41781288bb13b65ab1b57cd7967d8f41a | rfanimation/LongRange | /ballistics.py | 26,912 | 3.671875 | 4 | #!/usr/bin/python
import csv
import math
def findAlphaOmega(tableFilename):
""" This looks up the range value at the top and bottom of the
ballistic table. It is used wherever the difference in range
values (hi to low vs. low to high) must be considered.
Inputs: tableFilename = the tabl... |
b53ffd41c0e58a1bb496206e010238c9a4481aac | FinnVautier/AdventofCode2020 | /Day3/aovday3.py | 845 | 4.03125 | 4 | '''
Advent of Code 3
'''
toboggan = open("aovday3input.txt").read().splitlines()
map_basis = toboggan
total_trees = []
def is_there_a_tree(hill_x, hill_y):
map_x = hill_x % 31
return map_basis[hill_y][map_x] == '#'
def tree_count_for_slope(right_move, down_move):
x_coordinate = 0
... |
91c63c3ddfe30b2f49811056efbce0b8926efce7 | GlamorousCar/Algorithm | /BinaryExponentiation.py | 302 | 3.734375 | 4 | def BinaryExponentiation(a,n):
if n == 0:
return 1
if n%2 == 1:
return BinaryExponentiation(a, n-1) * a
else:
b = BinaryExponentiation(a,n/2)
return b * b
a,b = input("Please input the number and extent").split()
print(BinaryExponentiation(a,b))
|
c6ebd0079f9fad71b201290bd0b15a5789a6b8cd | souvikb07/Costa-Rican-Household-Poverty-Level-Prediction | /costarican/featurePlot.py | 3,045 | 4.25 | 4 | # Import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Function to plot the feature importances
def feature_importances_plot(df, n = 10, threshold = None):
"""Plots n most important features. Also plots the cumulative importance if
threshold is specified and prints the numb... |
5623ce81485f547b334d4a713924db705a5e4527 | blorgbeard/wsgit | /workspace.py | 1,158 | 3.6875 | 4 | """ Detection of "workspace" (common parent folder) """
import os
from git import is_git_repository
def is_workspace_root(path):
""" A workspace is just the parent folder of at least one git repository root folder. """
for child in os.listdir(path):
if os.path.isdir(child) and is_git_repository(child)... |
e6f9b07eb1b29ee002333766b12ef2efe8f4a690 | hrte5t2s/StudyPython | /button.py | 641 | 3.546875 | 4 | import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x100')
var = tk.StringVar()
l = tk.Label(
window,
textvariable=var,
bg='green',
font=('Arial', 12),
width=15,
height=2)
#l = tk.Label(window, text='OMG! this is TK!', bg='green', font=('Arial', 12), width=15,... |
080bf5bb5c575a0dfc6b1d805c252097b2fe6389 | joannarivero215/i3--Lesson-2 | /Lesson3.py | 1,577 | 4.15625 | 4 | #to comment
#when naming file, do not add spaces
#age_of_dog = 3, meaningful variable name instead of using x
names = ["corey", "philip", "rose","daniel"] #assigning variables values to varibale name in a list(need braket)
print names #without quotation to print value
print names[1] #says second name
print '\n'
for ... |
ab364138bf0d920ae410cfbcc60347b3d25f8798 | Ashwaray/Games | /Chess/chesslib/gui_console.py | 3,899 | 3.5 | 4 | # -*- encoding: utf-8 -*-
import board
import os
import voice
import speech_recognition as sr
UNICODE_PIECES = {
'r': u'♜', 'n': u'♞', 'b': u'♝', 'q': u'♛',
'k': u'♚', 'p': u'♟', 'R': u'♖', 'N': u'♘',
'B': u'♗', 'Q': u'♕', 'K': u'♔', 'P': u'♙',
None: ' '
}
class BoardGuiConsole(object):
error = ''
def... |
095615f1bac4635998d783a8c1e6aad0f17c1930 | hmedina24/Python2021 | /Practice/basic_python_practice/practice04.py | 431 | 4.3125 | 4 | #Create a program that asks the user for a number and then prints out a list of all the divisors that number.
#(If you don't know what a divisor is, it is a number that divides evely into another number.) For example, 13 is a divisor of 26 /13 has no remainder.)
def main():
num = int(input("Enter a number"))
d... |
a7236e24018a9954825dbedc7526b6c9658287db | hmedina24/Python2021 | /Practice/basic_python_practice/practice13.py | 713 | 4.09375 | 4 | #write a program(function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.
#Extras:
# write two difference functions to do this one using a loop and construsting a list, and another one using sets.
# go back and do Excersis 5 using sets, and write the... |
3d24a6fa2290f1fd17e38c7f18507453f005c4d8 | hmedina24/Python2021 | /Practice/basic_python_practice/practice08.py | 1,465 | 3.984375 | 4 | #Make a two-player Rock-Paper-Scissors game.
#(hint: ask for player plats (using input), compare them, print out a message of congratulations to the winner, and ask if the plays want to start a new game)
#Remeber the rules:
# Rocks beats scissors
# Scissors beats paper
# Paper beats rock
def compare(choice_1, choice_2... |
077dd6078669f3ff73df753fa86ace4b7c38ccae | hmedina24/Python2021 | /Sort_Algorithms /insertionSort.py | 582 | 4.15625 | 4 | def insertionSort(arr):
#traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
#move elements of arr[0..i-1], that greater
#than key, to one position ahead
#of their current position
j = i-1
while(j >= 0 and key < arr[j]):
arr[j+1] ... |
a87d462cc9760c43b2e75cfffcada78a0d1f3a92 | NikitaTipule/PPL_Lab | /Assignment6/shapes.py | 1,286 | 4.21875 | 4 | import turtle
s = turtle.getscreen()
t = turtle.Turtle()
class shape:
def __init__(self, sides = 0, length = 0):
self.sides = sides
self.length = length
class polygon(shape):
def info(self):
print("In geometry , a polygon can be defined as a flat or plane , two dimentional with strai... |
2abf423f1c238165f8e1ed1f7805d52617c94087 | alwilson/advent-of-code-2019 | /day_3/part1.py | 956 | 3.625 | 4 | #!/usr/bin/env python3
from typing import List, Tuple
with open('./input.txt') as fd:
wire1 = [(x[0], int(x[1:])) for x in fd.readline().split(',')]
wire2 = [(x[0], int(x[1:])) for x in fd.readline().split(',')]
def walk_the_wire(wire: List[Tuple[str, int]]) -> List[Tuple[int, int]]:
path = [(0, 0)]
... |
5a4de7b98f0ae53eea2170322fdfa3b6af42ccbb | bplaneCMU/SupervisedAI-MLtest | /scripts/k_means.py | 1,420 | 3.671875 | 4 | import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
'''
Disregarding 1st Principal component
use 2nd and 3rd as points in a k-means
algorithm to find to which cluster each
point belongs
Though it appears obvious with the human eye
we should still try to... |
4c9de0b1ebd3f6024940420c3e6a23ad611ac86c | b54041106/X-village-2018-exercise | /Lesson4_exception_Jul16/ex5.py | 535 | 3.625 | 4 | import random
item_in_shop = {"soybean_sauce": 0, "milk": 4, "salt": 10, "soybean_milk": 3}
items = [item for item in item_in_shop.keys()]
cnt = 5
def buy(item):
if item == 'soybean_sauce':
raise Exception("I didn't buy anything")
if item != 'soybean_sauce':
print("Mommy! I've bought ... |
4f39c91b7ed484576a00a3a0fca619e5d79c7a75 | mulyesmita15/Birthday-Remaining-Python | /birthday Remaining.py | 799 | 4.15625 | 4 | from datetime import datetime
import time
def get_user_birthday():
date_str = input("Enter your birth date in DD/MM/YYYY: ")
try:
birthday = datetime.strptime(date_str, "%d/%m/%Y")
except TypeError:
birthday = datetime.datetime(*(time.strptime(date_str, "%d/%m/%Y")[0:6]))
ret... |
62986bab6eb4c428253d272f68bb90cd89ff39f8 | Marcos-Tonari-Diaz/MC102 | /LAB19/lab19.py | 1,302 | 3.65625 | 4 | n, k= input().split()
n=int(n)
k=int(k)
matrix=[input().split()for i in range(n)]
#print(matrix)
def bubblesort(l):
lista=l[:]
for j in range(len(lista)):
for i in range(len(lista)-1-j):
if lista[i]>lista[i+1]:
lista[i], lista[i+1]= lista[i+1], lista[i]
#print(list... |
f624d5f6a0c8e2cccb722c1cb9f359b09f95e1a3 | toe-K-N-E-E/assesment | /client/client.py | 2,069 | 3.78125 | 4 |
from Utils.request_menu import RequestMenu
def showMenu():
"""this will render the menu
:return: nothing will be return
"""
print( "1. Create New User" )
print( "2. Authorize" )
print( "3. Send SMS" )
print( "4. Send Email" )
print( "5. Get Recently Sent Message" )
print( "6. Exit... |
d164983880b4f998a850ab9da10ba1a0287f3744 | ZeroMHua/flask_test | /定量描述统计/定量描述统计.py | 1,227 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:hua
"""
https://www.cnblogs.com/jasonfreak/p/5441512.html
包 方法 说明
numpy array 创造一组数
numpy.random normal 创造一组服从正态分布的定量数
numpy.random randint 创造一组服从均匀分布的定性数
numpy mean 计算均值
numpy median 计算中位数
scipy.stats mode 计算众数
numpy ptp 计算极差
numpy var ... |
3863244f7657b1e117f50bd79f5fe6ddf8799daa | slyons777/Digital-Crafts-Classes | /programming101/errorhandles.py | 168 | 4.09375 | 4 | try:
num = int(input("Enter a number: \n"))
while num > 0:
num -=1
print(num)
except ValueError:
print("You did not enter a number.")
|
3a57b337da35784f202a4d239e674462364e612f | slyons777/Digital-Crafts-Classes | /Python101/Algorithm-Practice/algorithm.py | 2,384 | 4.0625 | 4 | # 1. Given an array of integers, find if the array contains any duplicates.
# MY ANSWER
# def check_set(num):
# num_set = set(num)
# if len(num_set) < len(num):
# print('Yes the original list contained duplicates.')
# return True
# else:
# return False
# check_set([2, 5, 5, 6, 6... |
7bd5804912a1843fb0e9fea1ee4316e0021bcfe2 | slyons777/Digital-Crafts-Classes | /programming101/3times.py | 405 | 3.65625 | 4 | person = "Sarina"
today = "Tuesday"
emotion = "relaxed."
print("Hello " + person + ",\nI hope that your " + today + " is going well.\n" + "I'm personally really " + emotion)
combined = f"Hello {person}, \nI hope that your {today} is going well.\nI'm personally really {emotion}"
print(combined)
print("Hello %s,\nI ho... |
1ab9779122ae33d2d5f25f22dbf4f7e914c89924 | Val-Assistant/Val-Core | /Python Core/is_in.py | 518 | 3.5625 | 4 | def str(frase, str):
try:
if frase.upper() in str.upper():
return True
else:
return False
except AttributeError:
print("Erro com a classe dos arquivos especificados")
def array(frase, array):
try:
for i in array:
i.split()
... |
60aa407a9b4fe6b21c758172bafb682375225707 | justedwa/Khanda_Server_Python | /PowerControl.py | 3,645 | 3.53125 | 4 | # Circumflex Designs 2017
#
# init_comm(port_name) Opens named com port and initializes comm
# end_comm() Closes comm port
#
# output_state(out_on) If state is < 1 then output is turned off. Otherwise, it is turned on.
#
# volts_setpoint_set(volts) Sets output voltage to volts
... |
be99f99f073f061d92aa6f1de3e41b7975a6a07a | johnbukaixin/python-demo | /base/Cycle.py | 1,969 | 3.53125 | 4 | n = 100
counter = 0
sum = 0
while counter <= 100:
sum = sum + counter
counter += 1
print("0到100的和为", sum)
# 死循环
# var = 1
# while var:
# num = int(input("请输入数字:"))
# print("你输入的数字是:", num)
# print("good bye")
number = 0
while number < 5:
print("数字小于5")
number += 1
else:
print("数字大于等于5了")... |
309e2d1d1e10b4abaa50648c04c3814f476ea13d | johnbukaixin/python-demo | /base/objectOriented/CreateBeanProperty.py | 432 | 3.765625 | 4 | import functools
class Person():
def __init__(self):
self.name = None
pass
p1 = Person()
p1.name = 'Bart'
p2 = Person()
p2.name = 'Adam'
p3 = Person()
p3.name = 'Lisa'
def cmp(s1, s2):
if s1.name > s2.name:
return 1
if s1.name < s2.name:
return -1
return 0
L1 = [p1... |
2a984e2e69e7802f7041a1c143ca13c83c53cd9c | johnbukaixin/python-demo | /ndarray/RandomFunction.py | 630 | 3.609375 | 4 | # Author:panta
# CreateDate:2019/11/11
# FileName:RandomFunction
# IDE:PyCharm
import numpy as np
# 创建随机数组,浮点数[0,1)均匀分布
np.random.rand(2,3)
# 标准正态分布
np.random.randn(2,3)
# 100~200d范围内获取值,生成数组
b = np.random.randint(100,200,(3,4))
# 设置相同seed值获得相同数组
np.random.seed(10)
np.random.randint(100,200,(3,4))
np.random.seed(10... |
919ffa119fce7bc365557f6822351a817ab16497 | johnbukaixin/python-demo | /base/objectOriented/CreateBeanMethod.py | 456 | 3.5625 | 4 | class Person1(object):
def __init__(self, name, score):
self.name = name
self.__score = score
def get_grade(self):
if self.__score >= 90:
return 'A-优秀'
if 60 <= self.__score < 90:
return 'B-及格'
else:
return 'C-不及格'
p4 = Person1('Bob'... |
b1030df77af8e2b38aae25656481f331ef816ba5 | ndugal6/BookieBot | /source/MathUtils/MathUtils.py | 4,528 | 3.828125 | 4 | import decimal as decimal_
import math
# For clarification: probability is bounded by 0 & 1
# percentage is probability * 100; bound by 0 & 100...
# If you see somewhere other than here that x has a probability of 40, then translate to .4 for use in this program
class Odds(object):
"""Odds c... |
280316ead847ed3f6aaf806b316926ab74102f92 | titotamaro/List_Spinner | /List_Spinner/List_Spinner.py | 1,198 | 4.1875 | 4 | list_awal = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] #akan diubah menjadi[3,6,9][2,5,8][1,4,7]
#[3,6,9] ==> setiap kolom selisih 3 angka
#[2,5,8]
#[1,4,7]
def counterClockwise (list_x): # fungsi counterClockwise untuk list_x
hasil = [] # storage untuk penghitungan
for i in range(1,len(list_x)+1): # jumlah bari... |
18d9133390adc03dcc257e8118034fe93b870682 | Dando18/pymath | /Polynomial.py | 5,405 | 3.65625 | 4 | import copy
from Monomial import Monomial
class Polynomial(object):
monomials = [] # type: [Monomial]
def __init__(self, monomials):
self.monomials = copy.deepcopy(monomials)
self.sort()
def degree(self):
return self.monomials[0].power
def eval(self, value):
sum = ... |
0d7d70708385982529ac74e46653589a8c483fb0 | xzmystyle/MyLeetcode | /合并区间.py | 1,436 | 3.59375 | 4 | class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
暴力破解版
"""
if len(intervals) < 2: # 如果长度小于2,直接输出
return intervals
intervals = sorted(intervals, key=lambda x:x[0]) # 按interval... |
06ef6961470d6ba77e82d564c2a3b794a47dd581 | lawrel/unilabs | /cs1/hw3/hw3Part2.py | 1,396 | 4.0625 | 4 | #Code asks for a type of lego, 2x4,2x2,2x1,1x1, and lists how many pieces it can build from a given list.
import hw3_util
import math
legos = hw3_util.read_legos('legos.txt')
typelego = input("What type of lego do you need? ==> ")
print(typelego)
if typelego != "2x4" and typelego != "2x2" and typelego != "2x1" an... |
01d8a273447b0ea0831cf492bebc44cac2130bb9 | lawrel/unilabs | /lab7_check2.py | 938 | 3.84375 | 4 | def parse_line(line):
if line.count("/") >= 3:
splitline = line.rsplit('/',3)
for i in range(-3,0):
if not (splitline[i].isdigit()):
return None
return(splitline[1],int(splitline[2]),int(splitline[3]),splitline[0])
def get_line(fname,parno,lineno):
par... |
10151daa302cc59bd3e602e659b524ba48fb892b | lawrel/unilabs | /cs1/hw4/lecture11_p1.py | 841 | 3.890625 | 4 | def earlier_semester(class1,class2):
semester1,year1 = class1
semester2,year2 = class2
if year1 == year2 and semester1 == "Fall":
return False
elif year1 > year2:
return False
elif year1 == year2 and semester1 == semester2:
return False
return True
w1 = ('Spring... |
bc9b80e7163454970854b8d2434475fcc2653c3a | divitrao/email_validator | /checker.py | 909 | 3.5 | 4 | from validate_email import validate_email
from tkinter import *
root = Tk()
root.title('Email Validator')
def checkit(*args):
email_add=str(ent.get())
is_valid = str(validate_email(email_add))
# print(is_valid)
# print(type(is_valid))
if is_valid == 'True':
text.set('Valid Email id')
... |
2089f1051238eb1316666f87073e6005aa823b31 | dmitry-pechersky/algorithms | /uvaonlinejudge/11396 - Claw Decomposition.py | 1,004 | 3.546875 | 4 | def read_test_case():
n = int(input())
if n == 0:
return None
adj_list = [[] for i in range(n)]
while True:
u, v = [int(i) for i in input().split()]
if u == 0:
break
adj_list[u - 1].append(v - 1)
adj_list[v - 1].append(u - 1)
return adj_list, n
de... |
b97be07e570b96cf51af93dd8e7dfc8099f011e5 | dmitry-pechersky/algorithms | /leetcode/94_Binary_Tree_Inorder_Traversal.py | 1,411 | 3.875 | 4 | import unittest
from typing import Optional, List
class TreeNode():
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution():
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
stack = [(root, False)]
... |
737e47e6d5e1d5dddde4c88cf0a240c59572bb2d | dmitry-pechersky/algorithms | /leetcode/16_3Sum_Closest.py | 871 | 3.8125 | 4 | import unittest
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
n = len(nums)
nums.sort()
closest = nums[0] + nums[1] + nums[2]
for i in range(n - 2):
j, k = i + 1, n - 1
while j < k:
s =... |
b19103ac027b441ca79d7e1728c6cd0f8b42a9df | dmitry-pechersky/algorithms | /leetcode/17_Letter_Combinations_of_a_Phone_Number.py | 1,143 | 3.671875 | 4 | import unittest
from typing import List
class Solution:
def _rec(self, digits, n, pos, letters, mapping, combinations):
for ch in mapping[digits[pos]]:
letters.append(ch)
if pos < n - 1:
self._rec(digits, n, pos + 1, letters, mapping, combinations)
else:
... |
57f2f80f5bc5d1a25876c5c589039fb2686c637b | dmitry-pechersky/algorithms | /leetcode/1510_Stone_Game_IV.py | 745 | 3.71875 | 4 | from unittest import TestCase
from math import sqrt
class Solution:
def winnerSquareGame(self, n: int) -> bool:
dp = [False] * (n + 1)
squares = [i * i for i in range(1, int(sqrt(n)) + 1)]
for i in range(1, n + 1):
for square in squares:
if square > i:
... |
ad3cd664c5a54fff4163577c41d5bc108d115779 | dmitry-pechersky/algorithms | /hackerearth/Minimum cost.py | 771 | 3.6875 | 4 | from heapq import heappush, heappop
def successors(node, n, permutaion):
if node > 0:
yield (node - 1, 1)
if node < n - 1:
yield (node + 1, 1)
yield (permutaion[node], 0)
def dijkstra(n, permutaion):
heap, costs = [(0,0)], [None for i in range(n)]
while len(heap) > 0:
cost,... |
9eb206e2cb606ea796c986d41ad6037505c3adf4 | dmitry-pechersky/algorithms | /leetcode/329_Longest_Increasing_Path_in_a_Matrix.py | 1,364 | 3.625 | 4 | from typing import List
from unittest import TestCase
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
n, m = len(matrix), len(matrix[0])
dp = [[0] * m for i in range(n)]
def rec(i, j, dp):
if dp[i][j] == 0:
max_next_lengh = 0
... |
7ae172908858bff36df73096faa8a1be03992222 | dmitry-pechersky/algorithms | /uvaonlinejudge/10684 - The jackpot.py | 871 | 3.546875 | 4 | import sys
def read_numbers():
for line in sys.stdin:
for value in line.split():
yield int(value)
def read_test_cases():
iterator = read_numbers()
while True:
n = next(iterator, 0)
if n == 0:
break
yield [next(iterator, 0) for i in range(n)]
def max... |
e5013880ee58596135c5e4c62582bc0536c1ad6e | dmitry-pechersky/algorithms | /leetcode/23_Merge_k_Sorted_Lists.py | 1,776 | 3.625 | 4 | import unittest
from typing import List, Optional
from heapq import heapify, heappop, heappush
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __eq__(self, other):
if isinstance(other, ListNode):
return self.val == other.val and... |
4b8baf271655f6defc595552a28845df8916912a | dmitry-pechersky/algorithms | /leetcode/64_Minimum_Path_Sum.py | 730 | 3.6875 | 4 | import unittest
from typing import List
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
for i in range(1, n):
grid[0][i] += grid[0][i - 1]
for i in range(1, m):
grid[i][0] += grid[i - 1][0]
for i in range(1, ... |
d7435b5c727353cb1edbd9b7f61089e2442ade88 | dmitry-pechersky/algorithms | /leetcode/1522_Diameter_of_N_Ary_Tree.py | 1,018 | 3.515625 | 4 | class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
class Solution:
def diameter(self, root):
def rec(node):
if node is None:
return (0, 0)
max_diameter = 0
m... |
6241ba2214ff4e9be20c1bbc306c95603d359a65 | dmitry-pechersky/algorithms | /leetcode/71_Simplify_Path.py | 773 | 3.5625 | 4 | import unittest
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for token in path.split("/"):
if token not in ("", "."):
if token != '..':
stack.append(token)
elif len(stack) > 0:
stack.pop()
... |
957e405c7cf51f1c215a32b942f2aa997513136b | dmitry-pechersky/algorithms | /leetcode/42_Trapping_Rain_Water.py | 794 | 3.765625 | 4 | import unittest
from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
n = len(height)
max_height, s = 0, 0
for i in range(n):
if height[i] < max_height:
s += max_height - height[i]
else:
max_height = height[... |
f88d12a50c2a5ccc583296c480b1b9314a58f3f2 | dmitry-pechersky/algorithms | /uvaonlinejudge/00124 - Following Orders.py | 1,293 | 3.5 | 4 | import sys
def read_test_cases():
while True:
words = sorted(sys.stdin.readline().split())
if len(words) == 0:
break
dic = {words[i]: i for i in range(len(words))}
adj_list = [[] for i in range(len(words))]
constraints = sys.stdin.readline().split()
for i... |
38bcaacfb51939e05621ad092547c27f59086361 | dmitry-pechersky/algorithms | /leetcode/198_House_Robber.py | 448 | 3.75 | 4 | import unittest
from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
dp1, dp2 = 0, 0
for num in nums:
dp1, dp2 = dp2 + num, dp1 if dp1 > dp2 else dp2
return max(dp1, dp2)
class RobTest(unittest.TestCase):
def test_1(self) -> None:
self.asse... |
de816081105f55097c6b73c9d4811ee149f3231d | be1be1/python-100 | /leap_year.py | 357 | 3.96875 | 4 | """
input a year, return True if it is lead year, or return false
"""
year = int(input('Please input a year: '))
# We can use \ to split the code if too long
is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
print(is_leap)
# An interesting example: https://techcrunch.com/2008/12/31/zune-bug-explained... |
e1892ac5692ad8d04923730648fb2f0b6de2da3d | jakemdaly/NBA | /regression.py | 3,352 | 4.03125 | 4 | # Module for performing regression on data
import numpy
import matplotlib.pyplot as plt
from statistics import mean
def regression(dataframe_XY, alpha, num_iter, plot=False):
# Extract X and Y variables from the dataframe
X = dataframe_XY.iloc[:, 2:]
X = X.values
X = numpy.matrix(X)
y =... |
2ec310cd447ff95108a537be3414676a04020cc5 | pythonnortheast/slides | /2015/jan/code/process4-7.py | 2,472 | 3.59375 | 4 | #!/usr/bin/evn python
# coding=utf-8
"""
Emergent art. Process 4.
"""
import math
import random
import itertools
import pyprocessing as p
SIZE = 400 # screen size
SCALE = 200 # number of elements
ROTATION = 0.02 # element rotation step
class Element:
def __init__(self):
# TODO: what happens if you change the ... |
3ba0f743d5eb91a697c98ada5add7ff818f7d78a | pythonnortheast/slides | /2015/oct/code/mutation.py | 1,170 | 3.890625 | 4 | #!/usr/bin/env python
"""
Hill climbing. Randomises the best solution so far to generate the current one.
The mutation rate is controlled with the MUTATION_CHANCE parameter.
Prints current solution. Should be run in a terminal for the best effect.
QUESTION: does low or high mutation chance work better?
"""
from __fut... |
aa5798b7f9ee4a6d216f80ca45d9de4ce8dc02bd | pythonnortheast/slides | /2015/oct/code/recombination.py | 2,936 | 4.0625 | 4 | #!/usr/bin/env python
"""
Recombination. Individuals in the new population are generated by crossing over
the attributes of two parent individuals from the old population.
The CROSSOVER_PROBABILITY parameter controls the proportion of individuals in the
population that are subject to mating (the rest is copied without ... |
257f16e47cff4e8ac9c09a2c612c26514a144272 | eternalAbyss/Python_codes | /Data_Structures/zip.py | 585 | 4.34375 | 4 | # Returns an iterator that combines multiple iterables into one sequence of tuples. Each tuple contains the elements in
# that position from all the iterables.
items = ['bananas', 'mattresses', 'dog kennels', 'machine', 'cheeses']
weights = [15, 34, 42, 120, 5]
print(list(zip(items, weights)))
item_list = list(zip(it... |
3245abdabaddd8b0fc17523461cdfa921e91ea64 | eternalAbyss/Python_codes | /Data_Structures/dictionaries.py | 853 | 4.0625 | 4 | # Stores key value pairs
elements = {'hydrogen': 1, 'helium': 2, 'carbon': 6}
print('mithril' in elements)
# get returns None if the element is not present in the disctionary
print(elements.get('dilithium'))
# get with default message when the element is not found
print(elements.get('kryptonite', 'There\'s no such el... |
6c78847d06c260ddb9586bc7531f3959be1b258e | markdawson/AIND-Sudoku | /solution.py | 6,065 | 3.84375 | 4 |
assignments = []
# Define some helpful global variables
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a + b for a in A for b in B]
rows = 'ABCDEFGHI'
cols = '123456789'
boxes = cross(rows, cols)
row_units = [cross(row, cols) for row in rows]
column_units = [cross(rows, col) f... |
fd612be9b059c45bd36f433c6f828ebfc22b2455 | draconar/MITx-600x | /6.py | 279 | 3.734375 | 4 | def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
if a == b: return a
elif max(a, b) - min(a, b) == 1: return 1
return gcdRecur(max(a,b)-min(a,b),min(a,b))
|
f0afc2fc5a1d2e920b1c7e8530d1072eba3dc661 | draconar/MITx-600x | /11.py | 370 | 3.8125 | 4 | def howMany(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
sum=0
# Your Code Here
if len(aDict) == 0: return 0
elif (len(aDict) == 1) and (aDict[0]!=''): return 1
elif len(aDict) > 1:
for i in aDict:
... |
dac78777008f560a2a115d5729bf1753e6a696b9 | uncoolbeans/Endless-Math | /Endless Math Game.py | 4,415 | 3.796875 | 4 | #Endless math game
import random
def convert_Input_To_Int():
while True:
x = input("Enter your selection: ")
try:
x = int(x)
break
except ValueError:
print("Invalid input. Try again.")
return x
def answerRecieve():
while True:
... |
a988815de2621c938523379c54d2e1af5c610c97 | NikitaPlesovskix/cource-work.py | /First part/sort.py | 3,168 | 3.75 | 4 | import random
import algorithms
DIM = 40
bubble_arr = []
insert_arr = []
select_arr = []
CTotal = [0, 0, 0]
MTotal = [0, 0, 0]
for i in range(1, DIM+1):
select_arr.append(i)
bubble_arr.append(i)
insert_arr.append(i)
myfile = open("sort_methods.txt", "w") # Все результаты запишем в файл
print("\nУПОРЯДО... |
e09db7ca634db292ac8793c25553fc4ae32947b8 | konstantin2508/geekbrains_lessons | /Lesson3_Массивы/les3_task3.py | 905 | 4.0625 | 4 | # В массиве случайных целых чисел поменять местами минимальный и максимальный элементы
import random
def replacementArrayElements(array: list) -> list:
"""Выводит массив с поменяными местами мин. и макс. элементами входного массива"""
num_max = array[0]
pos_max = 0
num_min = array[0]
pos_min = 0
... |
5f5deaa62dde074fe526e3b079565fa5a25c51ab | konstantin2508/geekbrains_lessons | /Lesson2_Циклы_Рекурсия_Функции/les2_2_Рекурсия.py | 396 | 4.15625 | 4 | # Рекурсия
# Даны 2 числа: необходимо вывести все числа от A до B,
# в порядке возрастания (A<B) или убывания (A>B)
def func(a, b):
if a == b:
return f'{a}'
elif a > b:
return f'{a}, {func(a - 1, b)}'
elif a < b:
return f'{a}, {func(a + 1, b)}'
print(func(3, 25))
print(func(20, 2)) |
399934423d0ed2faf37565f3027b34a4f97dd50c | konstantin2508/geekbrains_lessons | /Lesson3_Массивы/les3_task2.py | 797 | 4.03125 | 4 | # Во втором массиве сохранить индексы четных элементов первого массива.
# Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5
import random
def evenArrayElements(array: list) -> list:
"""Выводит массив с индексами четных элементов входного массива"""
l... |
29d39e14a4e5315201ef23952065700270f3615e | konstantin2508/geekbrains_lessons | /Lesson3_Массивы/les3_3_СортировкаВставкаЭлементовВМассив.py | 1,384 | 3.921875 | 4 | # 1. Разложить положительные и отрицательные числа
# по разным массивам
import random
# array = [random.randint(-100, 100) for _ in range(100)]
# print(array)
#
# arr_below = []
# arr_lager = []
#
# for item in array:
#
# if item > 0:
# arr_lager.append(item)
# elif item < 0:
# arr_below.appe... |
c9b9fbd54fe038a06b564c809734862a4b8e7393 | sycLin/NLP-Term-Project | /phase 1/Phase1_17/source/llh.py | 12,965 | 3.6875 | 4 | # -*- coding: utf-8 -*-
#################### Import Modules ####################
import os
import sys
#################### Class Definitions ####################
class DataSet:
def __init__(self):
self.BiGramList = [] # list of BiGram instances
self.TriGramList = [] # list of TriGram instances
self.STriGram... |
b00b78f15cd297bca8f76449dc97b728f5ad55ee | arikorhonen/sql | /teht3/matka.py | 1,453 | 3.515625 | 4 | import sqlite3
import math
# Tarkistin testaa tätä funktiota
# 1. Toteuta funktio matka
def matka(lat1, lon1, lat2, lon2):
# Maapallon säde kilometreissä
R = 6371.0
# Laske ja palauta etäisyys pisteiden (lat1, lon1) ja (lat2, lon2) välillä
return
# Tarkistin testaa tätä funktiota
# 2. Toteuta funkti... |
d3d0866efa76a0234a42f17ac2724c0bb44bf7a3 | ashishjsharda/PythonSamples | /matrixmultiplication.py | 160 | 3.90625 | 4 | '''
Created on Jul 28, 2019
Matrix Multiplication
@author: asharda
'''
import numpy as np
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
b=np.array([1,2,3])
print(a*b)
|
3e610fc800a8233d2c747026736cf436711f40f6 | ashishjsharda/PythonSamples | /matrix_mul.py | 220 | 4.0625 | 4 | '''
Created on Sep 7, 2019
Matrix Multiplication using numpy
@author: asharda
'''
import numpy as np
def matrix_mul(a,b):
mul=np.matmul(a,b)
return mul
a=[[1,2],[3,4]]
b=[[4,5],[6,7]]
print(matrix_mul(a, b))
|
17dd0db1aeab353106acd29a7ecf4e1a163f0bc1 | ashishjsharda/PythonSamples | /Queues.py | 466 | 4.09375 | 4 | '''
Created on Aug 11, 2019
Queues in Python
@author: asharda
'''
class Queue:
def __init__(self):
self.items=[]
'Enqueue in Queue'
def enqueue(self,item):
self.items.insert(0, item)
'Dequeue Operation'
def dequeue(self):
self.items.pop()
'Get the Length of Queue'
def... |
ff287659fddb109058d179e2c073e635b3c0a0b1 | ashishjsharda/PythonSamples | /dict.py | 97 | 3.59375 | 4 | '''
Dictionary in Python
@author: asharda
'''
dict={'Name':'Jim','age':40}
print(dict['Name'])
|
a13c8cc1c8a87197285019eda9d50e2c12983451 | HaoHan1997/A-Star_Algorithm | /Bidirectional_A-Star.py | 9,687 | 3.703125 | 4 | """
*** Bidirectional A-Star algorithm ***
Useful for real road network graph problems, on a planar map/grid.
n - number of nodes
m - number of edges
If the graph isn't dense, ie. it's sparse, it's better to implement
priority queue as heap than as array.
A graph is sparse when n and m are of the ... |
9e3e4a2bad5a1b9260e9c0bcef49b8cc76bd4707 | gx-white/Coder | /AimAtOffer/isNumeric/main.py | 1,228 | 3.890625 | 4 | # -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
# "12e","1a3.14","1.2.3","+-5"和"12e+4.3"
length = len(s)
if(length == 0):
return False
has_sign = False
has_point = False
has_e = False
for i in ra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.