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 |
|---|---|---|---|---|---|---|
62c07068b864080d3d6d910b16882567ca8650f4 | dilsonm/CeV | /mundo3/Exercicios/ex081.py | 797 | 4.0625 | 4 | '''
Crie um programa que vai ler varios numeros e colocar em uma lista. Depois disse mostre:
a) Quantos números foram digitados.
b) A lista ordenada em forma decrescente
c) Se o valor 5 foi digitado e se esta ou nao na lista
OBS: Voce digitou {} valores, Os valores em order decrescente são: {}, O valor 5 (não) foi enco... |
61c5e7875f43dafeee99e0170aa0daf7a66b0cb4 | dilsonm/CeV | /mundo2/ex056.py | 899 | 3.8125 | 4 | """
Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre:
- A média de idade do grupo
- Qual é o nome do homem mais velho.
- Quantas mulheres tem menos de 20 anos
"""
from datetime import date
atual = date.today().year
media = 0
nomeh = ""
maisvelho = 0
mulher = 0
for c in ran... |
0006f40e8bc6f7e4bd8b938ae2b1e898f466dfb2 | dilsonm/CeV | /mundo2/ex067.py | 438 | 3.984375 | 4 | # Faça um programa que mostre a tabuada de vários numeros, um de cada vez, para cada valor digitado pelo usuário. O programa sera interrompido quando o número solicitado for negativo
while True:
n = int(input('Quer ver a tabuada de qual valor: '))
if n <= 0:
break
print('-='*30)
v = 1
for t ... |
cf0a763412d2086d16c8fb6f2e10f9d60c2b1c63 | dilsonm/CeV | /mundo3/Exercicios/ex098.py | 1,134 | 4.09375 | 4 | '''
Faca um programa que tenha uma funcao chamada contador(), que receba tres parametros: incio, fim e passo e realize a contagem.
Sei prorama tem que realizar tres contagens ateaves da função criada:
a) De 1 ate 10, de 1 em 1
b) De 10 ate 0, de 2 em 2
c) Uma contagem personalizada.
'''
from time import sleep
def conta... |
04d20699033d035a9f05f696a5234b52c3b93d5a | Zoey-01/caculate | /caculate_math.py | 77 | 3.578125 | 4 | i = 1
while i < 100:
if i % 7 != 0 or '7' not in str(i):
print(i)
i += 1 |
d7a7c00860761b44da6b9a6c2169605a7c456bc9 | lcordier/lcutil | /lcutil/util_image.py | 9,202 | 3.71875 | 4 | """ Utility library for image-processing tools.
"""
import math
from PIL import Image, ImageDraw
hex_map = {
0: '0',
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
7: '7',
8: '8',
9: '9',
10: 'a',
11: 'b',
12: 'c',
13: 'd',
14: 'e',
15: 'f',
}
def mm... |
3d72b9771fbd857b2eb9fa2f7d16bdb1e7823ed1 | ailarde/python-function | /function_stdoutput.py | 265 | 3.515625 | 4 | #!/usr/bin/env python
from socket import *
def MyFunc(name, age):
print "Hi! My name is",name + "and my age is",age
print "Hi! My name is %s and my age is %d" % (name,age)
print "Hi! My name is {} and my age is {}".format(name,age)
MyFunc("Mary",19)
|
911cad17b7a75bac4136b6eef86de32b8dc312a9 | paulzimmclay/ctci | /1.4/1-4.py | 235 | 3.765625 | 4 | def pal_perm_checker(str1, str2):
if str1 == str1[::-1] and str2 == str2[::-1]:
if ''.join(sorted(str1)) == ''.join(sorted(str2)):
return True
return False
print(pal_perm_checker('thingniht', 'thniginht')) |
b983063a522a34789d8ae0485adde7786d43fe3c | IuryBRIGNOLI/infosatc-lp-avaliativo-02 | /4.py | 374 | 3.84375 | 4 | n1 = input("Digite uma marca de roupa ")
n2 = input("Digite uma marca de roupa ")
n3 = input("Digite uma marca de roupa ")
n4 = input("Digite uma marca de roupa ")
n5 = input("Digite uma marca de roupa ")
lista = [n1,n2,n3,n4,n5]
print(lista)
n6 = input("Digite uma marca para saber a posição na lista ")
print("A po... |
d699e19737a5b3bfb9df26115c19ea2232ac606d | kamilczerwinski22/Statistics | /statistics/classes_2/exA/exA.py | 4,342 | 4.0625 | 4 | # A script where for a given probability matrix (made from a markov chain)
# multiply it by itself N times until a convergence criterion is found (each successive
# multiplication yields very small changes), e.g. |P^n - P^(n-1)| < 10^(-5).
# The pi values show a steady state drive.
# Script will show theoretical result... |
e1b2f40d9c269823d2406c41928a804c05c53e06 | iguess1220/py | /class/str.py | 1,408 | 3.84375 | 4 | # class Dog:
# def __init__(self, *args, **kwargs):
# self.name = args
# def __str__(self): # str方法是在对象被输出时调用,return返回值必须为字符串
# return "我是 %s" % self.name
# dog1 = Dog("旺财")
# print(dog1)
import time
class Potato:
"""地瓜类"""
def __init__(self):
self.state = '生的'
s... |
d45712e72812d145f416d7a56fcddc2b32333a0f | iguess1220/py | /0912/tuple2.py | 725 | 4.34375 | 4 | #赋值的右侧为多个数据,有自动组包为元组
""" a = 10,20,'heh'
print(type(a))
print(a)
"""
""" a = 10
b = 20
# 交换变量1 临时变量
temp = a
a = b
b = temp
print(a,b)
# 交换变量2 计算公式
a = a + b
b = a - b
a = a - b
print(a,b)
# 交换变量3 ,元组特性
b,a=a,b # 右侧多个数据会自动组包为元组,当左侧被赋值数量和右侧对等时,进行赋值
print(a,b) """
"""
a = 10
b = 20
c = 30
c,b,a = a,c,b
print(a,b,c)... |
9ae1347de0841b79e77cf9efc8fa204eea5e0c09 | iguess1220/py | /0918/eval.py | 515 | 4.25 | 4 | # 列表转换成字符串后再转列表出现的问题
# str1 = "[1,2,3,4]"
# list1 = list(str1)
# 出现的并不时我们要的结果,列表会把字符串所有元素都拆解
# print(list1)
# 使用函数eval可解决
# list2 = eval(str1)
# print(list2)
# 也可以转换字典,整数,浮点数等
# str2 = "{'a':'2','c':'7'}"
# print(eval(str2))
# eval 不要在工作中使用,可自动识别函数并执行,很危险
a = eval(input("please input: "))
print(a)
#print(__import__(... |
fef2b1e16185608c5e7ed549e44f6b7e4243331f | iguess1220/py | /for/abs.py | 210 | 3.625 | 4 | #!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
def abstest(n):
if not isinstance(n,(int,float)):
raise TypeError("bad operand type")
if n >= 0 :
return n
else:
return -n
|
c0556765191e7d7e49ad7f34b79770933d9e98c0 | iguess1220/py | /0918/lambda.py | 368 | 4.15625 | 4 | # 匿名函数
# a = lambda x,y: x+y
# print(a(1,2))
# #定义匿名函数并直接调用
# result =(lambda x,y: x*y)(1,2)
# print(result)
# 传入可变参数, 返回列表生成式,直接调用取值
result = (lambda *x: [i*i for i in x ])(1,2,3,4)
print(result)
# 解包赋值
a,b,c = (lambda *x: [i*i for i in x ])(2,4,6)
print(a)
print(b)
print(c)
|
c55b3aedeabb43ac12481bb7a5b2ba7d1bacd0b7 | iguess1220/py | /0913/qiepian.py | 316 | 4.1875 | 4 | str1 = 'hello,world'
# 切片格式 字符串[开始索引:结束索引] 范围: [)
print(str1[-1:])
print(str1[:5]) #果如从第一个开始,即0,可以省略,不写零,直接:
print(str1[6:]) # 如果截取到最后,可省略最后的数字
print(str1[-5:]) # 可倒数,从倒数第六个到结尾 |
f7ff64478518928d57c23409839ccb965e934e78 | iguess1220/py | /0918/digui.py | 274 | 3.78125 | 4 | # 求4的阶乘 4*3*2*1
def fun1(num):
result_num = 1
i = 1
while i <= num:
result_num *= i
i += 1
return result_num
print(fun1(5))
def fun2(num):
if num == 1:
return num
else:
return num*fun2(num - 1)
print(fun2(5)) |
f093a03ebc7f9817eeb7647c06c703d95d9fe811 | iguess1220/py | /0910/append.py | 237 | 3.8125 | 4 | L=[1,2,3]
L.append('abc')
L.append(['a','b','c'])
print(L[3][1])
""" print(L)
L.insert(0,'asd')
print(L)
L.insert(1,0)
print(L)
L.extend(['aaa','bbb'])
print(L)
L.extend(('asdafg',123))
print(L)
L.extend({'1':3,'345':'1fh'})
print(L) """ |
3198b2e7c0685d27e53b1e5bfa0dd8bc8b19c402 | iguess1220/py | /class/私有属性.py | 694 | 3.859375 | 4 | class Dog:
def __init__(self):
self.__age = None # 添加两个下划线设置为私有属性,只能类内可用,类外部无法赋值和访问
def set_age(self,age):
if age >= 0:
self.__age = age
else:
self.__info("age")
def get_age(self):
return self.__age
def __info(self,property_name): # 设置方法,只能在类内部调用
... |
409b119022e626a2ab4376f73af01332dd37dcd7 | Tsmith5151/mongodb-examples | /Homework/HW_Chapter2/hw2_1.py | 943 | 3.65625 | 4 | '''Type the following in the terminal to load the grades.json file:
mongoimport -d students -c grades < grades.json'''
'''Find all exam scores greater than or equal to 65, and sort those scores from lowest to highest.
What is the student_id of the lowest exam score above 65?'''
import pymongo
import sys
# Establish ... |
a08577c67feff953867586316d0909d84b37665d | codeplusmath/PPL_Assignments | /Assignment_8/Exception_Handling.py | 535 | 3.90625 | 4 | #Handling zero division error
def divide(x, y):
try:
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
divide(3,0)
#Raising error
def raiserror(x):
if x > 5:
raise Exception('x should no... |
e4581ff1eb8ad46e2ff1a6fdaf976f9e74dc4d75 | zengyuewen/python | /mywork/曾跃文_python05.py | 4,862 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-08-05 20:34:21
# @Author : zengyw (1004324878@qq.com)
# @Link : ${link}
# @Version : $Id$
"""
要求大家用面向对象的设计编写一个python程序,实现一个文字游戏系统。
动物园里面有10个房间,房间号从1 到 10。
每个房间里面可能是体重200斤的老虎或者体重100斤的羊。
游戏开始后,系统随机在10个房间中放入老虎或者羊。
b
然后随机给出房间号,要求游戏者选择敲门... |
4fe62261defaeed3b3dcc21aff9d1bebdca21225 | MarcusDMelv/Summary-Chatbot | /voice.py | 1,395 | 4.125 | 4 | # Code based on https://www.geeksforgeeks.org/text-to-speech-changing-voice-in-python/
# Python program to show
# how to convert text to speech
import pyttsx3
# Initialize the converter
converter = pyttsx3.init()
# Set properties before adding
# Things to say
# Sets speed percent
# Can be more than 100
converter.se... |
c374a5b9fa228c8ffa153f12d9ec15660f50942c | rashi174/Final450 | /SingleElementInASortedArray.py | 1,383 | 3.984375 | 4 | '''
Find the element that appears once in sorted array
Given a sorted array arr[] of size N. Find the element that appears only once in the array. All other elements appear exactly twice.
Example 1:
Input:
N = 11
arr[] = {1, 1, 2, 2, 3, 3, 4, 50, 50, 65, 65}
Output: 4
Explanation: 4 is the only element that
appea... |
ccba1fe6a8c6212b1a94ed8b93a7ef756402ce12 | PoojaVerma-CA/python-challenge | /PyPoll/main.py | 1,876 | 3.890625 | 4 | # Import the os module to create file paths and csv module for reading CSV files
import os
import csv
#Initialize dictionary to store candidates and corresponding votes
candidates = {}
# Path to collect data from the Resources folder
budget_csv = os.path.join("Resources", "election_data.csv")
#open and read csv file... |
4f3f602373b166d9a2a9af94c5a33befa671208c | grantthomas/project_euler | /python/p_0002.py | 955 | 4.1875 | 4 | # Even Fibonacci numbers
# Problem 2
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find... |
9fed1fdc9e37ec42116c7135d83e8f1be827cd97 | grantthomas/project_euler | /python/p_0020.py | 482 | 4.09375 | 4 | # Factorial digit sum
# Problem 20
# n! means n × (n − 1) × ... × 3 × 2 × 1
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
# Find the sum of the digits in the number 100!
import math
from p_0016 import NumToDigits
if __name__... |
208dd4a9f1d5f1b2c2fa48ed3f60eed6df1c8366 | grantthomas/project_euler | /python/p_0012.py | 1,316 | 3.875 | 4 | # Highly divisible triangular number
# Problem 12
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven tr... |
64b527ed4f5a3a18da10ee421e7b88b06e90bed7 | kkbaweja/CS303 | /Hailstone.py | 2,487 | 4.4375 | 4 | # File: Hailstone.py
# Description: A program that computes the hailstone sequence for every number in a user defined range
# Student Name: Keerat Baweja
# Student UT EID: kkb792
# Course Name: CS 303E
# Unique Number: 50860
# Date Created: 2/7/2016
# Date Last Modified: 2/9/2016
def ma... |
db3d0cf4b3a8d9bf0251fa5e9a3c94851fbe9e06 | v-erse/pythonreference | /OOP/generators.py | 787 | 4.09375 | 4 | # Generators can do what a class-based iterator can, in fewer lines
# the __iter__ and __next__ methods are created automatically, and the
# StopIteration exception is automatically raised as well
def letter_by_letter(word):
for i in range(len(word)):
# the yield keyword is specifically for generators, ot... |
81603ced0143981ee6540c89ee829ff663547c2f | v-erse/pythonreference | /Science Libraries/Numpy/arraymath.py | 1,033 | 4.34375 | 4 | import numpy as np
print("Array Math:")
# Basic mathematical functions operate on ndarrays in an elementwise fashion
a = np.arange(10).reshape(2, 5)
b = np.arange(10).reshape(2, 5)
print(a + b)
print(a*b)
# We can use the dot function to find dot products of vectors and multiply
# matrices (the matrixmultiplication.j... |
27725daf58ec0c9e1231dc4f20bc89c293f8dc27 | v-erse/pythonreference | /Basics, control, data structures/dictionaries.py | 635 | 3.78125 | 4 | dictionary = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f'}
print(dictionary)
dictionary[7] = 'g'
print(dictionary, "<- new value added at 7")
del dictionary[7]
print(dictionary, "<- value at 7 deleted")
# loop through the above dictionary
for x, y in dictionary.items():
print(x, y)
# dict comprehensions!
al... |
564016b171a67fbc97c1c656e7c7d0bb914b2339 | v-erse/pythonreference | /Input, output, errors, and exceptions/filereadwrite.py | 230 | 3.890625 | 4 | # open a file
f = open("Reference/Input, output, errors, and exceptions/filereadwrite.txt",
"r+")
print(f.read())
# print each line on a file
for line in f:
print(line)
f.write("\nthis is a line I added in python")
|
d8e0ed843fdd37d8f90d6d204e2ad4f61a64708f | andres-zibula/geekforgeeks-problems-solved | /basic/kth_distinct_element.py | 811 | 3.765625 | 4 | """
Author: Andres Zibula
Github: https://github.com/andres-zibula/geekforgeeks-problems-solved
Problem link: http://practice.geeksforgeeks.org/problems/k-th-distinct-element/0
Description: Given an array of N integers, write a program to print K-th distinct
element in the array. The given array may contain duplicat... |
afe6d64552f6328412a7129f7a2fad6eadc8c554 | andres-zibula/geekforgeeks-problems-solved | /basic/twisted_prime_number.py | 554 | 4.15625 | 4 | """
Author: Andres Zibula
Github: https://github.com/andres-zibula/geekforgeeks-problems-solved
Problem link: http://practice.geeksforgeeks.org/problems/twisted-prime-number/0
Description: A number is said to be twisted prime if it is a prime number and reverse of the number is also a prime number.
"""
import math
... |
672b029999ae4cad82725fd0bf422d7fd2a68282 | MengnanZoeZhou/LearnToProgramCraftingQualityCode | /assignments/test_stock_price_summary.py | 1,463 | 3.609375 | 4 | import a1
import unittest
class TestStockPriceSummary(unittest.TestCase):
""" Test class for function a1.stock_price_summary. """
def test_stock_price_summary_empty_list(self):
"""Test stock_price_summary when the list is empty."""
actual = a1.stock_price_summary([])
expected = (0, 0... |
7c20524345a0242342dd9fa843d1c3af207337a6 | guenhyunsoo/python | /190308.py | 270 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 10:47:12 2020
@author: Administrator
"""
numList = list(range(1,11))
#print(numList)
for i in numList:
# print(i)
# print(i, end='\n')
# print(i, end='')
# print(i, end=' ')
print(i, end='-') |
523fc2fb5144c17a994d48a45ee386baab653f9d | tangweibo123/ASWE | /withoutGAN.py | 19,095 | 3.515625 | 4 | import codecs
import collections
import math
import pickle
import random
import time
import numpy as np
import tensorflow as tf
def has_letter(word):
"""
Checks if input has a single letter. Used to remove punctuation.
INPUT
text: (string) Input String
OUTPUT... |
066247196ddc6188e5e46449e93ce617f6a2a400 | thenatural86/learn-python | /match_flower.py | 678 | 4.0625 | 4 | # Write your code here
def my_func(filename):
d = {}
with open(filename) as f:
for line in f:
letter = line.split(":")[0]
flower = line.split(": ")[1].strip()
d[letter] = flower
return d
def main():
name = input("Enter your First [space] Last name only... |
6a242a0805ba1e1db4c2e1252d378153f12a5439 | nicolas-plazas/universidad | /tarea_1/punto_4/potencia_de_dos.py | 526 | 3.65625 | 4 | import math
def es_ptencia_de_dos(numero):
if numero < 1:
return False
# Regresar al número base
log = math.log(numero, 2)
# Si el resultado del anterior proceso es correcto, sé regresa
# el número base ej: 2.0, se redondea y resta, si el resultado es
# igual a 0 retorna True de lo con... |
e53883689d91f5b4e9130961404df2b29e4a0ed4 | sphill98/ML | /word2vec/back_propagation.py | 2,307 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 8 20:05:17 2020
@author: sphil
Back-Propagation Basics
"""
import numpy as np
import matplotlib.pyplot as plt
V = 2 #Input layer size
N = 8 #Hidden layer size
M = 2 #Output layer size
#load train data
train = np.loadtxt("data/train.txt")
np.random.shuffle(train)
#... |
1e414f65482ba5710af7dcdfa946a8fbbc716134 | TangYihe/COGS18_Colonel_Blotto | /my_module/functions.py | 3,305 | 3.65625 | 4 | """A collection of function for doing my project."""
import math
from classes import *
def grade_inst(inst, population):
"""Computes the total score an instance (its arrangement)
earns when battling against each instance in a given
population.
Parameters
----------
inst: CBInstance. Targ... |
72a2a336e4c0eeacf3c6027f556ee1936331c26d | nishu959/Adityavermaheap | /kthsmallest.py | 467 | 3.53125 | 4 | from heapq import heappop, heappush, heapify
#There is no max heap in python
#so we push every element by changing it sign
# by multiplying it with -1
#At last we return the top element
# by multiplying with - 1
# in [1,2,5,3,6] = 4th smallest = 5
#now in [-1,-2,-5,-3,-6] ,4th greatest = -5
#for ans = 5 *-1= 5
a = li... |
0f4e020e921d831b6f5557103c2946e20034f924 | AndersonFSP/Curso-em-V-deo-Python | /AD1 2020 Q5.py | 640 | 3.578125 | 4 | from random import randint
def buscaValor(K, lista):
contador = lista.count(K)
if contador > 0:
index = lista.index(K)
else:
index = 'Valor não encontrado'
print(f'K: {K}\nIndice: {index}')
def mostraValores(lista):
print('Valores:', end=' ')
for i in range(len(valoresSortead... |
7203343f589cf4ce0969a485adc0de86b076c390 | AndersonFSP/Curso-em-V-deo-Python | /007-MediaAritmetica.py | 159 | 3.84375 | 4 | n1 = int(input('Digite a Primeira nota do aluno: '))
n2 = int(input('Digite a Segunda nota do aluno: '))
print('A média das nota é {}'.format((n1+n2)/2))
|
8c61640565786c388e8cf8753788095fbe47681c | AndersonFSP/Curso-em-V-deo-Python | /AD1 2020 Q1.py | 1,125 | 3.6875 | 4 | def mapeiaString(palavra, alvos):
numDeAlvos = 0
for c in range(len(palavra)):
if palavra[c] in alvos:
numDeAlvos += 1
return numDeAlvos
def medePalavra(palavra):
return len(palavra)
maiorNumDigitosPalavra = ''
somenteMinusculas = 0
cont = 0
while True:
palavra = str(input... |
1a8a244deab40a3095004cee67d384b8544bd38b | AndersonFSP/Curso-em-V-deo-Python | /087-MaisSobreMatriz.py | 684 | 3.8125 | 4 | list = [[0, 0, 0], [0, 0, 0], [0, 0, 0 ]]
aux = []
somaPares = somaColuna = maiorLinha = 0
for c in range(0, 3):
for l in range(0, 3):
list[c][l] = int(input(f'Digite um valor [{c},{l}]: '))
print('-=' * 30)
for c in range(0, 3):
for l in range(0, 3):
print(f'[ {list[c][l]:^5} ]', end='')
... |
e4c4457e349fc2f86df68332a63472080bf67c45 | AndersonFSP/Curso-em-V-deo-Python | /082-DividindoValoresEmListas.py | 476 | 3.734375 | 4 | valores = []
pares = []
impar = []
while True:
n = int(input('Digite um valor: '))
valores.append(n)
resp = str(input('Deseja continuar ? [S/N] ')).upper().split()[0]
if resp == 'N':
break
print('=-' * 20)
print(f'A lista é completa é {valores}')
for c in range(len(valores)):
if valores[c] %... |
a15ca4c48354f6eaf6a529c7bbf8f86e147a0cc8 | AndersonFSP/Curso-em-V-deo-Python | /AD1 Questao1.py | 402 | 3.640625 | 4 | quant = 0
resp = 'a'
media = 0
soma = 0
maiorNumero = 0
while resp != '':
resp = input()
if resp != '':
resp = float(resp)
soma += resp
quant += 1
if resp > maiorNumero:
maiorNumero = resp
media = soma / quant
print('Quantidade de números: {}'.format(quant))
print('M... |
18df68645fe88658ec9c57b7b6d46f730c693169 | AndersonFSP/Curso-em-V-deo-Python | /075-AnaliseDeDuplas.py | 514 | 4.03125 | 4 | valores = (int(input('Digite um numero: ')), int(input('Digite um numero: ')), int(input('Digite um numero: ')), int(input('Digite um numero: ')))
print(f'Você digitou os valores {valores}')
print(f"O valor 9 apareceu {valores.count(9)}")
if valores.count(3) == 0:
print('O valor 3 não foi digitado')
else:
prin... |
6cb60a8fa24c70fcba334f88756e95fd534478c9 | AndersonFSP/Curso-em-V-deo-Python | /029-RadarEletronico.py | 274 | 3.796875 | 4 | vel = float(input('Qual a velocidade do carro ? '))
if vel > 80 :
multa = (vel - 80) * 7
print('Você foi multado, passou de 80 Km/h !! \n Deverá pagar R${:.2f}'.format(multa))
else:
print('Você está abaixo da velocidade limite ')
print('Tenha um bom dia !') |
f29427cecaa24047750b926ffa58aae382bf346b | paliasnyi/Hillel | /hw8r.py | 1,078 | 3.71875 | 4 | ## 7 - revised ###############
def find_same_letter(my_str, my_str_2):
str_list = [i for i in my_str if my_str.count(i) == 1]
str_list_2 = [j for j in my_str_2 if my_str_2.count(j) == 1]
new_list = [k for k in str_list if k in str_list_2]
return new_list
print(find_same_letter('aaaaaabc', 'abcccccc'))... |
b03363c9264e05512b54824d7de029d21746e2ce | kanade9/python-machine-learning-study | /ch2/memo.py | 1,020 | 3.859375 | 4 |
"""
zip関数の使い方。複数のループをまとめる時などに使う
要素数が一致しない場合は”多い方の”要素が無視される。(少ない方の個数にループの回数が設定される)
names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]
for name, age in zip(names, ages):
print(name, age)
------------
Alice 24
Bob 50
Charlie 18
-------------
"""
"""
np.whe... |
b3569988f06f99cb934e5b3cd8e9ad435e3943b7 | onlyrobot/Calculation | /src/terminal.py | 1,056 | 3.96875 | 4 | '''
Date: 2020/1/3
Description: 终端操作
'''
import utilities as utl
import time
import random
def show_history_score():
print('user\tdate\t\tscore')
scores = utl.read_score()
for score in scores[:: -1][: 5]:
print('\t'.join(score))
def main():
question_num = int(input("input how many questio... |
f3f5ba9b65059fc330eef19c1bd8e1b97a8232cc | SuvroBaner/Full-Stack-Web-Developer-Nanodegree | /Codes/Python Programs/5_checkProfanity.py | 1,713 | 3.609375 | 4 | # In Python 3.5
from urllib import request, parse
def read_text():
quotes = open(r"C:\Users\Suvro\OneDrive\Suvro Banerjee_Personal\Profession\Udacity\Nanodegree\Full Stack Web Developer Nanodegree\Codes\movie_quotes.txt") # raw path
contents_of_file = quotes.read()
quotes.close()
check_profanity(conte... |
0d957ae547c625a3c149443c50401623285b3efe | lakyung/python_study | /func_basic.py | 2,079 | 3.921875 | 4 | def print_3_times():
print("안녕하세요")
print("안녕하세요")
print("안녕하세요")
print_3_times()
def print_n_times(value,n):
for i in range(n):
print(value)
print_n_times("안녕",5)
# print_n_times() # 매개변수를 넣지 않아 오류
# 가변 매개변수 함수
def print_n_times(n, *values):
for i in range(n):
... |
3f66b8e76dd2cce6a8d40c581f83fb31b7aa9b75 | lakyung/python_study | /false_value.py | 914 | 4.03125 | 4 | print("# if 조건문에 0 넣기")
if 0:
print("0은 True로 변환됩니다.")
else:
print("0은 False로 변환됩니다.")
print()
print("# if 조건문에 빈 문자열 넣기")
if "":
print("빈 문자열은 True로 변환됩니다.")
else:
print("빈 문자열은 False로 변환됩니다.")
number=0
if number:
print("number은 True로 변환됩니다.")
else:
print("number은 False로 변환... |
fd3d25fd73dd124f6ba5e2246bb257a99d536142 | MuharrikI/Pemjar | /1551502001111074_M. Muharrik I..py | 643 | 3.59375 | 4 | import urllib.request, json
isbn = input("ISBN : ")
domain = "https://www.googleapis.com/books/v1/volumes?q=isbn:"
def get(ini_domain,ini_isbn):
with urllib.request.urlopen(domain+str(isbn)) as google_url:
data_json = json.loads(google_url.read().decode())
for item in data_json['items']:
... |
0805973a3daa8ae7d01acaa8b58077c97155b679 | harshg16/Project-Euler | /Problem_10.py | 243 | 3.90625 | 4 | sum = 2
def is_prime(num):
factor = 3
while (factor <= num**0.5):
if num%factor == 0:
return False
factor +=2
return True
for x in range (3,2000000,2):
if is_prime(x):
sum += x
print(sum) |
ca26154644fcfa864afdd7063d0c435040183a0d | ErycPerovani/Jogo_de_adivinhacao.py | /forca.py | 966 | 4.125 | 4 | def jogar():
print("************************************")
print("**** Bem vindo ao jogo da forca ****")
print("************************************")
palavra_secreta = "Bacana"
letras_acertadas = ["_", "_", "_", "_", "_" ,"_"]
letras_faltando = str(letras_acertadas.count("_"))
enforcou ... |
6706ad7ae8265d42684f43264f69f499122f5fe2 | Mueller-Patrick/PhoenixMinerLogReader | /ShareTimes.py | 240 | 3.65625 | 4 | class ShareTimes(object):
"""
Class is just used to create objects to pass around
"""
def __init__(self, avgTimePerShare, totalTimeSpentMining):
self.avgTimePerShare = avgTimePerShare
self.totalTimeSpentMining = totalTimeSpentMining |
8f9692a0be3836b363adc733511e4addbfc12292 | coder2000-kmj/Python-Programs | /numprime.py | 595 | 4.34375 | 4 | '''
This is a program to print prime numbers starting from a number which will be given by the user
and the number of prime numbers to be printed will also be specified by the user
'''
def isprime(n,i=2):
if n<=2:
return True if n==2 else False
if n%i==0:
return False
if i*i>n:
... |
a41aba2bb975aa1face521dc4b5e95b0cfeeb705 | coder2000-kmj/Python-Programs | /warebank.py | 1,096 | 3.78125 | 4 | # recursive
from typing import List
warebank: List[int] = [0]
def show(index=0):
if index < len(warebank):
print(warebank[index])
index += 1
show(index)
else:
return
def add(count, fee, start=0, end=10):
global decide
if start < end:
decide = input(... |
af6677ed1e058941b8ddf1d687568ddee44f388d | mrr-cs/oop_2021 | /Task4.py | 2,858 | 4.0625 | 4 | import math
class StringToNumber:
def convert(self, string):
if string == "one":
return 1
elif string == "two":
return 2
elif string == "three":
return 3
elif string == "four":
return 4
elif string == "five":
... |
1fbaaa37fc8329f9d74fb0cb2bf1ed3bb09d7729 | rbrush18/PG_RB | /list_RB.py | 741 | 3.96875 | 4 | name = "Ryan Brush"
subjects = ["English","Math","Science","History","Latin"]
print("Hello " + name)
for i in subjects:
print("One of my subjects is " + i)
characters = ["Kensi","Deeks","Callen","Sam","Mosely"]
for i in characters:
if i == "Callen":
print(i + " is my favorite!")
e... |
0e9d2df7773b6091aea6fba846693a47f159b26c | syedshams316/DBAssignment | /create_db.py | 2,534 | 4.09375 | 4 | import sqlite3
from sqlite3 import Error
def get_connection(db_name):
"""Creates a database connection"""
connection = None
try:
connection = sqlite3.connect(db_name)
return connection
except Error as e:
print(e)
return connection
def create_table(connection, create_table... |
31b06e9762311a0672768340d18d19e6f3c91858 | Hengle/Virus | /Manager/Command.py | 292 | 3.53125 | 4 | class Command:
def __init__(self):
print('命令模式开启')
def _help(self):
print('输入help\n')
def getInput(self):
while(1):
command=input("in")
print(command)
if(command=='help'):
self._help()
|
4fa52524360add14f4cd222cb50ed057f5033c72 | raketenlurch/automate-the-boring-stuff | /Automate-the-boring-Stuff-with-Python/littleKid.py | 161 | 3.953125 | 4 | if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You arenot Alice, kiddo.')
else:
print('You are neither Alice nor a lottle kid')
|
1fa50811ef19ebf762b73718b99225bc9927dce9 | gurpreetsachdeva/python-design-patterns | /AbstractFactory/AbstractFactory.py | 620 | 4.0625 | 4 | """
Abstract Factory Pattern
"""
__author__ = 'amit'
class Car(object):
def make(self):
print "A Car\n"
class AirPlanes(object):
def make(self):
print "An Airplane\n"
class CarFactory(object):
def get(self):
return Car()
class AirPlanesFactory(object):
def get(self):
... |
7eaf6a4c56ae24c76511a06ab2faf3583f924c13 | fieldsfarmer/pythonnotes | /class_eg.py | 2,762 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student():
def __init__(self, name, age):
self.name = name
self.age = age
def print_info(self):
print('%s is %d' %(self.name, self.age))
xiaoming = Student('Xiaoming', 12)
print(xiaoming.name, xiaoming.age)
xiaoming.print_info()
class Student2():
def __i... |
95dd6d604b0c3bd224bd02309d4cfd03f2c209ac | swilcox/2019adventofcode | /python/day4p1.py | 579 | 3.625 | 4 | # 2019 Advent day 4 part 1
MIN = 145852
MAX = 616942
def main():
current_number = MIN
valid_count = 0
while current_number <= MAX:
has_repeat = False
past_digit = ''
increases = True
for digit in str(current_number):
if past_digit == digit:
has_r... |
8ebd1c93760131e638453df5febbca55fbfed791 | Tesfit12/Tic-Tac-Toe | /tictactoe.py | 2,697 | 3.9375 | 4 | # tic tac toe created 01/12/2020, for practicing python
# modified code
def board():
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
return board
def board_printer(board):
print(f'{board[0]}|{board[1]}|{board[2]}')
print('-----')
print(f'{board[3]}|{board[4]}|{board[5]}')
print('-----')... |
991984a6b839bfc09b6cb0c71044755bfc892591 | miketwo/logfile-parser | /parser.py | 922 | 3.875 | 4 | #!/usr/bin/env python
'''
Author: Michael Ricks-Aherne
Parses a text file with lines that say either 'starting <something>' or
'finishing <something>', and emits all <something>'s that were started but not
finished.
See README for more details.
'''
import argparse
import re
def parse_args():
parser = argparse.A... |
b54773d027f62755af345cda0c266e0d66a59c5d | essenceD/GB | /Lesson_3/Lesson_3.py | 1,324 | 3.59375 | 4 | def my_foo(s_1, s_2, s_3=7):
# pass # заглушка
print('hi!')
sub = s_1 + s_2 + s_3
print('SUM: {}'.format(sub))
return s_2 * s_3
# my_foo(4, 7)
print(my_foo(4, 3))
def ma_foo_2(*args):
return args
print(ma_foo_2(4, 5, 'fgfdg', False))
def my_foo_1(**kwargs):
return kwargs
print(my_foo_... |
1a27e29aaf9dfb72861b831f14383c0b4cd0a7fd | essenceD/GB | /Lesson_4/HW#4-7.py | 516 | 3.984375 | 4 | def get_fact(base):
res = 1
for i in range(1, base + 1, 1):
res *= i
return res
def list_gen():
for i in range(1, fin + 1):
yield i
while True:
fin = input('Enter length of list: ')
try:
fin = int(fin)
if fin > 0:
break
else:
pr... |
4bba42a785d0ca7b2076046d7b053312de601a0e | essenceD/GB | /Lesson_8/Lesson/Other/2.py | 474 | 3.609375 | 4 | class MyClass:
def __init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
@classmethod
def set_fio(cls, data):
print(data)
name_1, name_2 = data
print(name_1)
print(name_2)
return cls(name_1, name_2)
@staticmethod
def get_f... |
af99f29a72cc97ae5bfb99e14e4b4911cf1e3db9 | essenceD/GB | /Lesson_2/HW#2-2.py | 338 | 3.9375 | 4 | while True:
size = input('Enter a size of list: ')
if size.isdigit() and int(size) > 0:
size = int(size)
break
lst = input('Enter elements separated by space bar: ').split()
print('The list you\'ve input: ', *lst)
for i in range(0, size, 2):
lst.insert(i + 1, lst.pop(i))
print('Modified lis... |
1dfdbe81f84d4cfd9c9709f7747531aa5b6715a9 | essenceD/GB | /Lesson_6/Lesson_6.py | 685 | 3.515625 | 4 | class Transport:
# atributes
def __init__(self, name, model, year):
self.name = name
self._model = model
self.__year = year
print(f'{name}, {model}, {year}')
# methods
def on_start(self):
print(f'Go car {self.name}!')
def __on_stop(self):
print('Stop... |
c64cde2e0caae6336670900b2e9b8a0dbd4d3c66 | essenceD/GB | /Lesson_7/Other/2.py | 438 | 3.8125 | 4 | class Iterator:
def __init__(self, start=0):
self.i = start
def __next__(self):
self.i += 1
if self.i <= 5:
return self.i
else:
raise StopIteration
class IterObj:
def __init__(self, start=0):
self.start = start - 1
def __iter__(self):
... |
26534fb5ae2e75775a06fdef7ae41f2a15e5ce04 | jpdoe/Engeto-python-project-2 | /bulls_cows.py | 3,745 | 4.15625 | 4 | #!/usr/bin/env python3
# Description: Project 2 - Part 1 'Bulls and Cows game' for Engeto Online Python Academy
# Author: Jan Polák
from random import seed, randint
DEBUG = False
def show_welcome():
string = "Welcome to Bulls and Cows game, cowboy!"
print(len(string) * "+")
print(string)
def show_ban... |
d8dd66792916b405fc40b6dbc17b2c8fbb0e5a9e | DipankerBaral/Tkinter-project | /circle.py | 1,263 | 4.3125 | 4 | #mid point circle drawing algorithm
# -*- coding: utf-8 -*-
from tkinter import *
def sympoints(x,y):
w.create_text(x + x_centre, y + y_centre,text='.')
w.create_text(y + x_centre, x + y_centre,text='.')
w.create_text(x + x_centre, -y + y_centre,text='.')
w.create_text(y + x_centre, -x + y_centre,text='.')
w.cre... |
665d94dae704c595b97f735be4dfc06757c8a272 | stanic-mia/zadaca12 | /zadaca12.5.py | 2,579 | 3.78125 | 4 | # pogodi tajni broj nadogradnja - funkcije - vježba
import random
import json
import datetime
# pokretanje igre (izbor A)
def play_game():
secret = random.randint(1, 30)
wrong_guesses = []
attempts = 0
score_list = get_score_list()
name = input("Unesite ime: ")
while True:
... |
cfc95b57f36488843953cafa1311fa68462f566a | swapnilshinde367/python_basic_programs | /check_primality.py | 1,170 | 3.890625 | 4 | import sys
number = input( 'Please enter number : ' )
if( False == number.isdigit() ):
print( 'not a number' )
sys.exit()
else :
number = int(number)
for i in range( 2, (number//2) + 1 ) :
if( 0 == number% i ) :
print( f'{number} is not prime' )
sys.exit()
print( f'{number} is prime' )
##########... |
f77f0c50e37d2962c53c5ac97632d91eaeaad7f7 | swapnilshinde367/python_basic_programs | /list_remove_duplicates.py | 256 | 3.671875 | 4 | lstNumbers = [1,2,3,4,5,6,7,9,9,987,4,234,5,3456,2,1,234,6,2,112,34,56,2,2345,2,345,6,2,334,43,123,4,45,3]
print(len((lstNumbers)))
print((list(set(lstNumbers))))
lstNew = []
for i in lstNumbers :
if( i not in lstNew ):
lstNew.append(i)
print(lstNew) |
eaeec7e65b82d30992711d84a5488285dbd79d8d | swapnilshinde367/python_basic_programs | /hackerrank_list_operations.py | 752 | 3.8125 | 4 | if __name__ == '__main__':
lstOperations = ['insert','remove','append','sort','pop','reverse','print']
lstNumbers = []
n = int(input())
for _ in range(n) :
strOperation, *lstOpNumbers = input().split()
lstOpNumbers = list(map(int,lstOpNumbers))
if( strOperation in lstOperations ) :
if( 'insert' == strOpera... |
833d044adc1c7557bb1ba1e8a322a3495661e49b | swapnilshinde367/python_basic_programs | /character_input.py | 255 | 3.953125 | 4 | name = str( input( 'Please enter your name ' ) )
age = input( 'Please enter your age ' )
if( False == age.isdigit() ) :
print( 'You didn\'t enter number' )
print( 'Your name is ' + name )
else :
print( 'Hi ' + name + ' you are still young and ' + age ) |
3e752f6da44e3ffb0773479504328d933eecd2e6 | swapnilshinde367/python_basic_programs | /guessing_game_2.py | 615 | 3.8125 | 4 | import sys
import random
print( 'Keep number in your head between 1 to 100, I will guess the nuber' )
guess_attempts = 1
start = 1
end = 100
middle = end // 2
while( 1 ) :
middle = (start+end) // 2
print( f'{start}, {middle}, {end}' )
print( f'number is {middle}' )
userinput = int( input( 'Press "1" for hig... |
bedf9ba2db50f1a1647c689852ab305a088a3ecf | Divisekara/MoraXtreme-5.0 | /matrices multiplication.py | 672 | 3.578125 | 4 |
##Input matrices change the matrices as wish
L=[[1,2,3,4], [5,6,7,8], [9,10,11,12]]
M=[[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]
## Operation is L * M first matrix is and second matrix is M
L_rows, L_cols = len(L), len(L[0])
M_rows, M_cols = len(M), len(M[0])
#In order to multiplication be val... |
acfa143d657ba2e529b7eae5713e5b2a7eff271b | PaulGuo5/leetcode-1 | /538/Solution.py | 1,312 | 3.9375 | 4 | """
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output... |
b1b4237efab087b3ffa4dd074d0563b780a35a27 | saishanker41/LeftRotation | /printMax.py | 295 | 3.9375 | 4 | def printmaxele(arr, k, n):
max = 0
for i in range(n-k+1):
max = arr[i]
for j in range(1,k):
if arr[i + j] > max:
max = arr[i + j]
print(str(max) + " ", end = " ")
arr = [1,9,4,6,2,1,1,6,2,10]
k = 3
n = len(arr)
printmaxele(arr, k, n) |
e63c653000fbb2e2b2c4522b3d3a46d2b45ecd3b | laowantong/mocodo | /mocodo/cross.py | 1,437 | 3.5 | 4 | from functools import lru_cache
crossed_strings = frozenset(["-++-", "-++0", "-+0-", "-0+-", "0++-", "+--+", "0--+", "+0-+", "+-0+", "+--0"])
@lru_cache
def cross(x1, y1, x2, y2, x3, y3, x4, y4):
""" Tests whether the segments ((x1,y1), (x2,y2)) and ((x3,y3), (x4,y4)) intersect.
Two segments sharing exact... |
33218429b101094aaa3a42d0b39db7b8e14f0cfc | ghosx/git | /二分.py | 313 | 3.625 | 4 | def f(x):
'''
帮一朋友写的二分法求根
'''
return 2*x**3-4*x**2+3*x-6
low = -10
high = 10
i = 1
while low < high:
x = (low + high)/2
print('第{}次二分'.format(i)+'x={}'.format(x))
if f(x) == 0:
print('\n方程的结果是X = :',x)
break
elif f(x) < 0:
low = x
else
high = x
i += 1 |
077ae9420fd5a4371d08520a179996f75c4976c6 | AARabee/AI | /study/python/tensorflowDemo/basic/constructGraph.py | 1,031 | 3.546875 | 4 | # 代码参考网址:https://www.w3cschool.cn/tensorflow_python/tensorflow_python-fibz28ss.html
import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.], [2.]])
product = tf.matmul(matrix1, matrix2)
#
# sess = tf.Session()
# result = sess.run(product)
#
# print(result)
#
# sess.close()
with tf.Sessio... |
a00c950d395a4eed5567f16b7f88bfb15a09a6e2 | noe-guzman/proyectos | /Terminados/proyecto 5 terminado.py | 1,108 | 3.75 | 4 | import math
print ("ingrese una seria de 10 numeros")
a = float (input())
b = float (input())
c = float (input())
d = float (input())
e = float (input())
f = float (input())
g = float (input())
h = float (input())
i = float (input())
j = float (input())
me = float (a+b+c+d+e+f+g+h+i+j)
print("la media de los numeros in... |
699a5e2f0ada201028a27b46bbede3e9672c8803 | conorp854/SETI_Scripts | /SpaceTime.py | 2,918 | 4.0625 | 4 | #Plot time on vertical axis and distance on horizontal axis.
# 0 > Time > 100,000 years ago
# 0 < Distance < 100,000 lightyears
#Draw a line that represents your light cone. On a spacetime diagram the maximum slope is 1 which
#corresponds to the speed of light
#ct vs x
#1.Draw SpaceTime Diagram (Note that ti... |
d908f460fb296cbf66d8e3df0a3aaddbcb2edb7a | JustinCalma/CECS-100-Lab-9 | /JustinCalma_Lab9.py | 673 | 3.90625 | 4 | #Import random
import random
#Define Main
def main():
randList()
lowNumb(list)
highNumb(list)
totalNumb(list)
#Generate random numbers
def randList():
list = []
for i in range(0, 20):
x = random.randint(0, 100)
list.append(x)
lowNumb(list)
highNumb(list)
print(list)... |
27bd34eceea816bf46493721918ca6c91d105829 | fluxt/cs440 | /mp1/bfs.py | 1,875 | 3.5625 | 4 | import numpy as np
import utils
from collections import defaultdict
def bfs(graph, pacman_pos, goal_position):
# dictionary of nodes visited
distance = {node:None for node in graph}
distance[pacman_pos] = 0
# dictionary of node's parents
parent = defaultdict(lambda: None)
# push start position into the queue (l... |
d1d135dd264c15b2a1b965146cf74a58ace049f0 | smalltide/learning_python3 | /Script.py | 182 | 3.921875 | 4 |
print('First Program')
replaced = 'Ardit'.replace('A', 'O')
print(replaced)
currency = 145
currency_today = 100.5
currency1 = 'nothing'
print(currency, currency_today, currency1)
|
9dc1813e131c313c6e47b7bce5ac55e55191a89c | eileencuevas/Intro-Python-I | /src/isprime.py | 533 | 3.65625 | 4 | import sys
import math
# def is_prime(potential_prime):
# for num in range(2, int(potential_prime) + 1):
# if potential_prime % num == 0:
# return print(False)
# return print(potential_prime > 1)
def is_prime(potential_prime):
limit = math.sqrt(potential_prime)
for num in range(2... |
74d0ac1113043c9d875b576ffb3e62094482a163 | abhay772/LeetCodeSolutions | /python-solutions/20.py | 887 | 3.65625 | 4 | ## Runtime: 24 ms, faster than 95.82% of Python3 online submissions for Valid Parentheses.
## Memory Usage: 14.3 MB, less than 62.87% of Python3 online submissions for Valid Parentheses.
class Solution:
def isValid(self, s: str) -> bool:
need = []
for i in range(len(s)):
if s[i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.