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
be90e83b67be93177d2aa6797044fb6504b28473
olegrok/TrackUIAutomatization
/lesson1/6.py
539
4.28125
4
#!/usr/bin/python3 # Написать программу, определяющую является ли фраза палиндромом или нет. # Входные данные содержат строку. # Ответ должен содержать: "полиндром" если это палиндром или "не полиндром" если нет. import re str1 = str(input()) str1 = re.sub(r'\W', '', str1).lower() if str1 == str1[::-1]: print(...
56e99210b9b5884f3b9605ea85728cda5aa14058
tarantot/decorator-sample
/code.py
628
3.8125
4
def my_decorator(func): def wrapper(text): decor, i_1, i_2, j = list(text), 0, 0, 0 while i_1 in range(len(decor)): i_1 += 1 print('+-' * i_1, end='+\n') while j in range(len(decor) + 1): decor.insert(j, '|') j += 2 print(''.join...
904955dcec8ea9e1b26b39739242b0c2f47dbc55
ignasiialemany/cell-packing
/polypacker/packing/distances.py
1,706
3.625
4
import numpy as np from scipy.spatial import distance_matrix def midpoint(polygon): """Compute the polygon mid-point. This is the mid-point between bounds, NOT the centroid! When enclosing the object in a circle, this guarantees the smallest radius, unlike when using the centroid. """ x0, y0, ...
b45aeed618f032d767d31706a99960a06ba31b18
Subrata11/Data-Mining-CS-F415
/Lab1/Python/lab1.py
806
3.53125
4
''' Lab 1 - Data Preprocessing Part 1 ''' import numpy as np # used for handling numbers import pandas as pd # used for handling the dataset from sklearn.impute import SimpleImputer # used for handling missing data from sklearn.preprocessing import LabelEncoder, OneHotEncoder # used for encoding categorical data from ...
09c341d849f05d2047fcf7deed103423212af390
amanullah28/code_practice
/python_practice/iterator&generator/fib.py
302
3.515625
4
# def fib_list(max): # nums = [] # a, b = 0, 1 # while len(nums)<max: # nums.append(b) # a, b = b, a+b # return nums # fib = fib_list(100000) # print(fib) def fib_gen(max): x, y = 0, 1 count = 0 while count<max: x, y = y, x+y yield x count+=1 for n in fib_gen(10000000): print(n)
3b97d23b700201ff54f2269345d9d1bb29f48f41
mtjen/132
/assignment2.py
3,838
3.96875
4
# checks if the given substring is within given string def containsSubsequence (inputString, subString): count = 0 maxCount = len(subString) result = "" doesContain = False for character in inputString: if character == subString[count]: count = count + 1 result = resu...
e08dbbcc37d86980091367cedd5547866e7ce5f8
DorakAlba/100_days_of_python
/25_day_actually/main.py
1,047
3.640625
4
import turtle import pandas as pd screen = turtle.Screen() screen.title('Us States Game') image = 'blank_states_img.gif' screen.addshape(image) turtle.shape(image) tu = turtle.Turtle() tu.penup() tu.hideturtle() tu.color('black') data = pd.read_csv('50_states.csv') print(data) answered = 0 game_on = True answer = [...
5ec90b5061479057ab0be74166f7662897056973
KyeCook/PythonStudyMaterials
/LyndaStudy/LearningPython/Chapter 3/time_delta_objects.py
1,347
4.34375
4
###### # # # Introduction to time delta objects and how to use them # # ###### from datetime import date from datetime import datetime from datetime import time from datetime import timedelta def main(): # Constructs basic time delta and prints print(timedelta(days=365, hours=5, minutes=1)) # print date...
48cf608faab61973d1a3660ca5e466728f0db0f9
KyeCook/PythonStudyMaterials
/LyndaStudy/LearningPython/Chapter 2/loops.py
820
4.28125
4
######## # # # Introduction to loops # # ######## def main(): x = 0 # Defining a while loop while (x < 5): print(x) x =+ 1 # Defining a for loop for x in range(5,10): print(x) # Looping over a collection (array, list etc.) days = ["mon", "t...
487b014e7135c03ae74b9cea534be012cef98fe3
nikolaygtitov/CSC573
/Project_2/ngtitov_p2mpclient.py
14,833
3.5625
4
""" ngtitov_p2mpclient.py CSC 573 (601) - Internet Protocols Project 2 This program implements the solution the Project 2 assignment: Point-to-Multipoint File Transfer Protocol (P2MP-FTP). P2MP-FTP - protocol that provides a FTP sophisticated service: transferring a file from one host (p2mp client) to multiple destin...
2008ba337dfbe5d145d4b0256391bddd66cc1e8e
nelsonwcf/academics
/ANLY520 - Sentiment Analysis/Assignment 8/CorrocherFilho_Nelson_Unit_9_Assignment.py
5,103
3.640625
4
import nltk # Question 1 # You need some way to extend the grammar (tense agreement, in this example). While this could have been done using the # previously introduced tools, this chapter introduces the concept of using feature structure to match tenses, grammar # categories, etc. # Grammar solution from (8...
ab74ca3ff1375a875b9ee288e5bff305576521d9
nelsonwcf/academics
/ANLY520 - Sentiment Analysis/Assignment 4/CorrocherFilho_Nelson_Unit_4_Assignment.py
2,169
3.65625
4
import nltk # Exercise 3 sentence = "They wind back the clock, while we chase after the wind." tokens = nltk.word_tokenize(sentence) tags = nltk.pos_tag(tokens) print [nltk.help.upenn_tagset(w) for (_, w) in tags] # Exercise 5 d = {} type(d) d['dragon'] = 'green' # print d['tiger'] - Causes an error b...
20766911f05268e641c10a492a1ff488fe16c4fb
nelsonwcf/academics
/CISC601 - Scientific Computer II/PythonProject/_numint.py
557
3.65625
4
''' module: _numint.py author: Luis Paris description: - formulas from Chapra's numerical methods textbook - implements discrete single/multi segment trapezoid rules (1st order newton-cotes integration formulas) - chapters on numerical integration for discrete functions - implemented from algorithms/pseudoc...
20842aa42c92fdb2af336c0b7941f6ad075eb29e
devedzic/woodstock
/woodstock/python/dictionaries.py
3,120
4.84375
5
"""Demonstrates dictionaries """ def demonstrate_dictionaries(): """Creating and using dictionaries. - create a blank (empty) dictionary - create a non-empty dictionary - print a non-empty dictionary - print all items using the items() function - print one item per line - pprint di...
6d9ccd22786dff690afbdba5bff795912d8bf044
eltoraz/alchemy
/alchemy/prototypes/textadv/game.py
17,350
3.609375
4
"""Text adventure prototype to start playing around with the alchemy framework. Mix ingredients in the cauldron to create potions, and store them in your inventory. Drink (or otherwise apply) them, but most of the effects won't actually do anything yet! """ from alchemy.cauldron import Cauldron from alchemy.character ...
2393f2d8885ba4db3215ef5b71b0d4949f3cc849
wkisme/kemeny-young-rank
/kemeny-young rank/src/input.py
241
3.703125
4
def input1(): l1 = [] while (True): a = input('输入字符串: ') if a == 'q': break b = input('输入字符串个数:') for i in range(int(b)): l1.append(a) return l1
845559d233a47be2365bd86381e6bf427363ea77
wkisme/kemeny-young-rank
/kemeny-young rank/src/list_of_dictionary_to_matrix.py
626
3.609375
4
import numpy as np # greater = 1 smaller = 0 no_sense = 2 def list_of_dictionary_to_matrix(list_of_dictionary): row = len(list_of_dictionary) col = len(list_of_dictionary[0]) a = np.zeros((row, col*3)) for i in range(len(list_of_dictionary)): counter = 0 for j in list_of_dictionary[i].ke...
a073c919a3d59dc6cf38d8a2ade36be198eda93e
TheWizard91/TheNimGame
/Nim.py
8,175
3.578125
4
class Nim(): def __init__(self): """This is the class where the set up is being made""" self._pilesAndStones = {} self._player1 = "" self._player2 = "" self._numberOfPiles = 0 self._currentPlayer="" def setName(self, name, one=True): """Set the...
46931e33c78761b5076cf7646a13ea24f3ee5143
JennyAlmeniana/PYTHON-LMS
/Testfunction.py
4,320
3.640625
4
# -*- coding: utf-8 -*- import sys from Library import Library from User import Member from catalog import Catalog from Librarian import Librarian library = Library({"the reader":[4,"bernhard schlink","120H",1995,218],"the secret garden":[3,"frances hodgson burnett","121H",1911,375],"number of stars":[...
c73bbcb19f8fefe0c8ac9a03af30f84878398d34
rafianathallah/modularizationsforum
/modnumber10.py
395
4.125
4
def pangramchecker(str): alphabet = "abcdefghijklmnopqrstuvwxyz" for characters in alphabet: if characters not in str.lower(): return False return True sentence = str(input("Enter a sentence: ")) if(pangramchecker(sentence) == True): print("This sent...
38517d65ba535fa6a2de129dbb0444cf01a67af6
ieeecsufabc/SmartIEEE
/URI Programs/Python/1017.py
75
3.625
4
x1 = int(input()) y1 = int(input()) fuel = (x1*y1)/12 print("%.3f" %fuel)
70e71a31b5ca0e8d156dc620db28289b93610647
ieeecsufabc/SmartIEEE
/URI Programs/Python/1019.py
172
3.828125
4
x1 = int(input()) hours = (x1)/3600 hours = int(hours) x2 = x1 - hours*3600 mi = (x2)/60 mi = int(mi) x3 = x2 - mi*60 sec = x3 print(str(hours)+":"+str(mi)+":"+str(sec))
15d6a745ce028cb89f062656806295e31c49daf7
ieeecsufabc/SmartIEEE
/URI Programs/Python/1043.py
203
3.515625
4
A, B, C = map(float, input().split()) if (A + B> C) and (B + C > A) and (C + A > B) : pe = A + B + C print("Perimetro = "+str("%.1f" %pe)) else : a = (A + B)*C/2 print("Area = "+str("%.1f" %a))
e8cd743e53e9cd341caff4c8c9f798f1998f5966
JeffreyJLi/rosalind
/counting-point-mutations.py
451
3.625
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 15 18:28:19 2017 @author: Jeff """ with open('test-cases/rosalind_hamm.txt', 'r') as f: line1 = f.readline().strip() line2 = f.readline().strip() def hamming(seq1, seq2): assert len(seq1) == len(seq2), "Sequence lengths not equal" hamming = 0 for...
b2681199c636f8d3cf67f2e3211100e512f951d8
CamiloYate09/Python_Django
/FACTORIAL.py
334
4.21875
4
# factorial = int(input("Ingresa Un numero para saber su factorial")) # # acum = 1 # # while factorial>0: # acum *=factorial # factorial = factorial-1 # # # # print('%i' % acum) #FACTORIAL DE FORMA RECURSIVA def factorial(x): if (x==0): return 1 else: return x * factorial(x-1) print...
e9c023d8afffb2b4d28954c7bc2ff4311c3e1a94
Ryan149/Bioinformatics-Repository
/bioinformatics/coding/month.py
705
4.15625
4
name={} name[0]="January" name[1]="February" name[2]="March" name[3]="April" name[4]="May" name[5]="June" name[6]="July" name[7]="August" name[8]="September" name[9]="October" name[10]="November" name[11]="December" def daysInMonth(month): days = 30 if (month < 7): if (month % 2 == 0): ...
36373bc8acdc43a375a5e934cee11ac50109889f
chelvanlab/Graphics_Algorithms
/CircleDrawing-2D/CircleDrawing.py
418
4.09375
4
from tkinter import * import math root = Tk() c = Canvas(root,height=500,width=500) c.pack() def drawCircle(ox,oy,r): for i in range(0,361): x = r*round(math.cos(math.radians(i)),2) y = r*round(math.sin(math.radians(i)),2) x = ox+x y = oy-y print(x,y) ...
934c0e6eba73205096065e9ac1850fbb71a98fc0
fabiomacdo/curso-python
/mundo2/ex070.py
948
3.71875
4
total = 0 maismil = 0 count = 0 baratopreco = 0 baratonome = '' print('========== LOJA SUPER BARATÃO ==========') while True: produto = str(input('Qual o nome do produto? ')).strip() preco = float(input('Qual o preço desse produto? R$')) total += preco if count == 0: baratopreco = preco ...
feec34030ac57a31efc14cc40dc558a2ad9b2903
fabiomacdo/curso-python
/mundo2/ex038.py
260
4.03125
4
n1 = int(input('Digite um número inteiro: ')) n2 = int(input('Digite outro número inteiro: ')) if n1 > n2: print('{} é MAIOR'.format(n1)) elif n1 < n2: print('{} é MAIOR'.format(n2)) else: print('Não existe valor maior, os dois são IGUAIS!')
a951f2a75c431d418f8c990fd498432c466ed4f9
fabiomacdo/curso-python
/mundo2/ex055.py
405
3.90625
4
maior = 0 menor = 0 for p in range(1, 6): peso = float(input('Informe o peso da {}ª pessoa, em kg: '.format(p))) if p == 1: maior = peso menor = peso else: if peso > maior: maior = peso if peso < menor: menor = peso print('O maior peso informado foi {:...
be95335fed74411c0268c2e429791485a316eee6
fabiomacdo/curso-python
/mundo3/ex078.py
725
3.703125
4
valores = [] maior = 0 menor = 0 for cont in range(0,5): valores.append(int(input(f'Digite um valor para a posição {cont}: '))) if cont == 0: maior = menor = valores[cont] else: if valores[cont] > maior: maior = valores[cont] if valores[cont] < menor: menor = ...
fb50a0556943e1b15b9960b94c64544313f48cb4
fabiomacdo/curso-python
/mundo1/ex034.py
224
3.90625
4
salario = float(input('Informe o seu salário atual: ')) if salario <= 1250: aumento = salario + salario * 0.15 else: aumento = salario + salario * 0.10 print('O seu novo salário será de R${:.2f}!'.format(aumento))
c1a2e85828c3500027a161b4947827e855196c15
fabiomacdo/curso-python
/mundo3/ex081.py
542
4.09375
4
valores = [] while True: valores.append(int(input('Digite um valor: '))) print('Valor adicionado com sucesso!') verificador = ' ' while verificador not in 'SN': verificador = str(input('Quer continuar? [S/N]: ')).strip().upper()[0] if verificador in 'N': break print(f'Você digitou {l...
1690732a508672af9100195e90c5329378872ccf
gkchan/PyQuizBase
/questions.py
1,254
3.65625
4
# Questions for quiz in learning code program # More questions to come depending on time # import classes from model module from model import User, Level, Module, Function # import database necessities from model module # from model import db, connect_to_db from random import randint, choice, sample, shuffle def a...
87e82f31d1624d627eed4c122307fc3762165e75
EdBali/Python-Datetime-module
/dates.py
1,626
4.3125
4
import datetime import pytz #-----------------SUMMARRY OF DATETIME module------------ #-------------The datetime module has 4 classes: # datetime.date ---(year,month,date) # datetime.time ---(hour,minute,second,microsecond) # datetime.datetime ---(year,month,date,hour,minute,second,microsecond) # datetime.timedelta ---...
5c7e02cc4dda2dad439ba57fffba223550329f5d
allan-mlpe/coursera_data_structures
/algorithmic_toolbox/week2/fibonacci_number.py
187
3.9375
4
def nth_fib_number(n): arr = [0, 1] for i in range(1, n): arr.append(arr[i] + arr[i-1]) return arr[n] nth_number = int(input()) print(nth_fib_number(nth_number))
a87c9ad06898f5bca7e5728029675ab57ba2456d
alsimoes/mao-na-massa
/lista2/lista2_exercicio1.py
179
3.5
4
# -*- coding:utf-8 -*- a = [8,12,3,32,18,5,15,4,2,7] print '\nCrescente' a.sort() for i in a: print str(i) print '\nDecrescente' a.reverse() for i in a: print str(i)
2beb7f29b3a651492c802c9d32d34487cdbc2c86
Juanpablo9816/Ejercicio5
/Principal.py
926
3.84375
4
from ManejadorAlumno import Lista_Alumno if __name__ == "__main__": alumno = Lista_Alumno() alumno.CargarLista() def op1 (): Año = int(input("Ingrese Año: ")) divicion = int(input("Ingrese Divicion: ")) alumno.Item1(Año,divicion) def op2 (): from Clase_Alumno import Al...
d05a2a4abb437bd4958ebb7e7e296b88ee51a923
CS328/CS328-A1
/python/A1/step_detection.py
1,850
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 7 15:34:11 2016 @author: cs390mb Step Detection This Python script receives incoming accelerometer data through the server, detects step events and sends them back to the server for visualization/notifications. """ import numpy as np from filters import Butterworth...
a6fea7fc0a94fe8eaec6c390bf4b599a89b060be
kirath2205/AI_assignment2
/AI_assignment2/p1_weather.py
3,045
3.671875
4
import math def euclidean_distance(data_point1, data_point2): distance=math.sqrt((((data_point1['TMAX']-data_point2['TMAX'])**2)+((data_point1['TMIN']-data_point2['TMIN'])**2))) return distance def read_dataset(filename): list_of_lines=list() # used to store all the lines of the rain.txt file in ...
7f1a0ae79e8d53f6319e74aa96b56fe4c5377ee1
chrisflucas/238_221_project
/data.py
1,559
3.640625
4
import csv import sys, os import datetime ''' Wrapper class for data reading, handling, etc. ''' class DataUtil(): def __init__(self): self.data = {} return None ''' Takes in and parses a CSV file. Return: rows - list of dicts, each dict represents a row of data and maps from column names to data po...
1fb6fc3d3c4b9aa81017831ab40bf77fddb6fed3
krista-bradshaw/csse1001-a1
/a1.py
6,453
3.921875
4
""" CSSE1001 2019s2a1 """ from a1_support import * def get_position_in_direction(position, direction): """Calculate the new row,column position in the given direction. Parameters: position (tuple<int, int>): The row, column position of a tile. direction (str): The given direction. Return...
581eca1f3d9285b97cda775c13ab4b30df2ef7e2
BabiyaSharma25/tasks
/mobile no..py
299
4.0625
4
import re def num(number): regex = re.compile("(91)?[7-9][0-9]{9}") return regex.match(number) number = input('Enter mobile number :') while True: if(num(number)): print('Valid') break else: number = input('Enter number :')
a1d69d9a43163882862a5460605a20086fc8f334
marcemq/csdrill
/strings/substrInStr.py
665
4.125
4
# Check if a substring characters are contained in another string # Example # INPUT: T = ABCa, S = BDAECAa # OUTPUT: ABCa IN BDAECAa import sys from utils import _setArgs def checkSubstrInStr(substr, mystr): frec = {key:0 for key in substr} for key in substr: frec[key] += 1 counter = len(frec) ...
9919ff6adadda31963d22f35c68e0859244691e9
novking/Data-Structure-and-Algorithms
/process_packages.py
2,248
3.53125
4
# python3 class Request: def __init__(self, arrival_time, process_time): self.arrival_time = arrival_time self.process_time = process_time class Response: def __init__(self, dropped, start_time): self.dropped = dropped self.start_time = start_time class Buffer: def __init_...
e1010fcef38081827ce65150ea93eb922d87e2be
kemoelamorim/Fundamentos_Python
/exercicios/Ex018.py
528
4.125
4
""" Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. """ from math import sin, cos, tan, radians # lendo ângulo angulo = int(input("Digite o ângulo: ")) # valores de seno e cosseno seno = sin(radians(angulo)) print("O ângulo de %d tem o seno de %.2f" %(ang...
4fe669ddce4a2ec9e5df71d9c408a37b4ecc65f4
kemoelamorim/Fundamentos_Python
/Tipos_primitivos/1-Strings/1.0-tipos_primitivos.py
2,007
4.3125
4
# Variaveis e Tipos nome = 'kemoel' # valor com o tipo string ou 'str' idade = 26 # valor com o tipo inteiro ou 'int' salario = 4.728 # valor com o tipo ponto flutuante ou 'float' masculino = True # valor com tipo boleano 'bool' # Função type() mostra o tipo que valor da variável possui print(type(nome)) # tipo s...
012f1e25827a45d2812b034834944c5fcd75d951
kemoelamorim/Fundamentos_Python
/exercicios/Ex008.py
323
4.0625
4
""" Escreva um programa que leia um valor em metros e o exiba convertido em centimetro e milimetros. """ valor = int(input('Digite um valor em metros: ')) centimetros = valor * 100 milimetros = valor * 1000 print('O valor {} convertido para centimetros é {} e para milimetros é {}'.format(valor, centimetros,milimetros))...
f87f2b92594468b50462b7516cb32d245ff1c9dd
kemoelamorim/Fundamentos_Python
/exercicios/Ex001.py
263
4
4
""" Crie um script Python que leia o dia o mês e o ano de nascimntoo de uma pessoa e mostre uma mensagem com a data formatada. """ dia = input('Dia = ') mes = input('Mês = ') ano = input('Ano = ') print(f'Você nasceu no dia {dia} de {mes} de {ano}. Correto?')
59277fde267ace726840302d9432aa13cd3b2de2
aiiachinakova/University
/factorial_iterator.py
409
3.609375
4
class Factorial: class _Fact_iter: def __init__(self): self.i = 1 self.fact = 1 def __next__(self): self.fact *= self.i self.i += 1 return self.fact def __iter__(self): return Factorial._Fact_iter() fct = Factorial() i...
bee76b8f9b8161ad0dc12bd44297efb8dc5048d9
sabirribas/pymr
/ex02.py
489
3.828125
4
# Example 2: Word counting import pymr import sys def fmap((filename,nothing)): f = open(filename,'r') text = f.read() f.close() stext = text.replace('\n',' ').replace(',',' ').split(' ') return zip( stext , [1 for i in range(0,len(stext))] ) def freduce(vs): return sum(vs) # same as reduce(lambda v1,v2:v1+v2,...
921eceeaeda93a66f93641a61d3efa3a68bb7970
patrick330602/UST-Frontier
/area.py
1,258
3.796875
4
from collections import namedtuple import random Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax') def rectangle(X1,Y1,width1,height1,X2,Y2,width2,height2): ra = Rectangle(X1,Y1,X1+width1,Y1+height1) rb = Rectangle(X2,Y2,X2+width2,Y2+height2) dx = min(ra.xmax, rb.xmax) - max(ra.xmin, rb.xmin) ...
7275edaa47ab9f720111bf4f0e3fe9c185a53d0f
vrushti306/college-python
/assignment2/anagram.py
184
4.03125
4
s1=str(input("enter string")) s2=str(input("enter string 2")) def check(s1,s2): if sorted(s1)==sorted(s2): print("anagrams") else: print("Not anagrams") check(s1,s2)
2a3c4c11d5fbcb16d69d2c18ebc3c0ef30d0b352
PsychoPizzaFromMars/exercises
/intparser/intparser.py
1,951
4.40625
4
'''In this kata we want to convert a string into an integer. The strings simply represent the numbers in words. Examples: - "one" => 1 - "twenty" => 20 - "two hundred forty-six" => 246 - "seven hundred eighty-three thousand nine hundred and nineteen" => 783919 Additional Notes: - The minimum numbe...
a772a0797599a86db6c6abd2b0b02863a573d6e2
kd411/DAA
/coutinginversion.py
492
3.875
4
import time import random L= [] n=int(raw_input("Enter range of array : ")) for i in range(n): print "Enter element ",i+1,"of the array : " L.append(int(raw_input())) print "Array :",L def inversion(list1,n): count=0; for i in range(n): for j in range(i+1,n): if(list1[i]>list1[j]): count=count+1 print "No...
3749fe87693a26236a058088d45501b2d6639c80
brettmroach/cs8-lab07
/lab07.py
2,381
3.75
4
# lab07.py # Brett Roach # 6907380 def totalWords(filename): '''Returns the total number of words in the file''' infile = open(filename, 'r') text = infile.read() infile.close() for char in text: if char in ',.!?;': text = text.replace(char, ' ', 1) word_list = text.split()...
46ba35075f3c60ffbc5b5ebdffa5c4de16469349
fredrik-sy/AoC2020
/day9.py
890
3.53125
4
import request import itertools def part_one(numbers): preamble = 25 for i in range(preamble, len(numbers)): combinations = set(sum(j) for j in itertools.combinations(numbers[i - preamble:i], 2)) if numbers[i] not in combinations: return numbers[i] def part_two(numbers): in...
191fdd4a785cdbf54eb9679be3f12d8b2efec455
mariacarolina0810/TallerPython
/ejercicio6.py
272
3.5625
4
import random def listaAleatorios(n): lista = [0] * n for i in range(n): lista[i] = random.randint(0, 50) return lista print("Ingrese cuantos numeros aleatorios desea obtener") n=int(input()) aleatorios=listaAleatorios(n) print(aleatorios)
ab8e8df80b806f86152ee8e2a1d343d08fa839d0
mariacarolina0810/TallerPython
/ejercicio7.py
771
3.8125
4
personas=int(input("Digite la cantidad de personas que desea calcular el IMC")) for i in range(1,personas+1): peso=float(input("Digite su peso")) estatura=float(input("Digite su estatura")) imc=peso/estatura**2 if imc<18.5: print (imc, " Esta bajo de peso") elif imc>=18.5 and imc...
3b1cc3621fdd084d179c4e7a3c8a5b82bb82fa60
fp-computer-programming/cycle-5-labs-p22rlugo
/lab_5-2.py
412
4.28125
4
# Ryan Lugo: RJL 10/27/21 first_string = input("First Word?: ") second_string = input("Second Word?: ") if first_string > second_string: print(first_string + " is bigger than " + second_string) elif first_string < second_string: print(second_string + " is bigger than " + first_string) elif first_string == sec...
37879667279fa03edc79300b3667827c57a26a39
31v1n/turing_machine
/turing_machine.py
659
3.65625
4
def comp(p,x,sym): i = 1 #head position q = 0 #current state x1 = list(x) #convert the tape (which is a string) into an array state = "" while state != "f": #print the tape and the current position of the head along with the state print(len(x)*"-") print("".join(x1)) ...
701a15d279676543ceb0aa35efbd3e611a07f5cb
soldcarvalho/my-projects
/toleranceamento.py
38,003
3.71875
4
from time import sleep import math def main_program(): print('''[0] - Fechar Programa. [1] - Consulta Geral - SR-DQ-001 [2] - Medir Tolerâncias - SR-DQ-001 [3] - Tubo Estruturado Frio "ISO EN 10219-2" - Quadrado e Rectangular [4] - Erro Admissível Fita Métrica''') def septit(msg): print('-=' * 29) print...
80d2008455dc937de197802177241472e75c8f1a
Afnaan-Ahmed/GuessingGame-Python
/guessingGame.py
1,036
4.4375
4
import random #Generate a random number and store it in a variable. secret_number = random.randint(1,10) #Initially, set the guess counter to zero, we can add to it later! guess_count = 0 #set a limit on how many guesses the user can make. guess_limit = 3 print('Guess a number between 1 and 10.') #Do this so the p...
14fb59b01f99399e6c623d2f84ae9a2e357fb6ba
sourabh06986/devopsprac
/pythonexp/ec2-user/script3.py
317
4.28125
4
#!/usr/bin/python users = ["user1","user2","user3"] print (users[0]) #Accessing last element print (users[len(users)-1]) print (users[-1]) print (users[-2]) users.append("peter") print users print users[-1] + " " + users[-2] #insert element at specific index users.insert(1,"marry") users.remove("user1") print users
ab9645b2508b02b72898f2b10304f9965f1362b8
rmg2995/Code-Wars
/8kyu/test.py
291
3.765625
4
# Make a function that returns the value multiplied by 50 and increased by 6. If the value entered is a string it should return "Error". # https://www.codewars.com/kata/55a5bfaa756cfede78000026/train/python def problem(a): #Easy Points ^_^ return "Error" if a == str(a) else a*50+6
a0ef2f1f2709b0ac1d340461fb508c0e79fea7a3
ktb0311/class
/person2.py
1,447
3.65625
4
class Person: def __init__(self, name, job = None, pay = 0): self.name = name self.job = job self.pay = pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay = int(self.pay * (1 + percent/100)) def __repr__(self): #...
a3030af4170daecdecc826d4a0c950802a71146d
benheart/stock-spider
/dao/user_dao.py
741
3.640625
4
# -*- coding: utf-8 -*- import config import MySQLdb def get_user_info(): user_info_dict = {} # 打开数据库连接 db = MySQLdb.connect(config.DB_HOST, config.DB_USERNAME, config.DB_PASSWORD, config.DB_DATABASE) # 使用cursor()方法获取操作游标 cursor = db.cursor() # 查询用户信息 sql = "SELECT user_id, name, email FRO...
5dbb4db96d384b13f027ca6adba424dae8f8b7a0
vishnupsingh523/python-learning-programs
/gratestofThree.py
543
4.375
4
# this program is to find the greatest of three numbers: def maxofThree(): # taking the input of three numbers x = int(input("A : ")); y = int(input("B : ")); z = int(input("C : ")); #performing the conditions here for finding the greatest if x>y: if x>z: print(x," is the g...
a7bcd8eacaf66ea462672bdb6f5c716902123e12
saravana1992/python
/find_duplicate.py
396
3.859375
4
st = [1, 2, 3, 1, 2] duplicate = [] for sts in st: if sts not in duplicate: duplicate.append(sts) print(duplicate) # sort a string or number in list st.sort() print(st) # reserve a string st.reverse() print(st) # string or number there or not if 21 in st: print("its there") # Copy sts = st[:] pr...
d9e4911308860951dbc9a96ceb9aec9aaf4f59e0
klaus2015/py_base
/code/day10/类变量练习.py
340
3.515625
4
class Wife: """ 老婆类 """ count = 0 @classmethod def print_count(cls): print("总共生产了%d个老婆类" % Wife.count) def __init__(self,name): self.name = name Wife.count += 1 wife01 = Wife("王昭君") wife02 = Wife("甄姬") wife03 = Wife("大乔") Wife.print_count()
49c2c979f0196ab52336d7b549a8d2a3cd9d391e
klaus2015/py_base
/code/day05/r.py
424
3.609375
4
# 逛论坛,查看utf-8和utf-16区别 # for i in range(10,0,-1): # print(i) # list01 = list("我是齐天大圣") # print(list01) list01 = ["我", "是", "齐", "天","大","圣"] # 正向索引 0 1 2 3 4 5 # 反转序列 # 第一种 5 4 3 2 1 0 # for index in range(len(list01)-1,-1,-1): # print(list01[index]) # 第二种 -1 -2 -3 -4 -5 -6 for index in range(-1,-len(list01...
4655713e1415fdd743d5cb546f6d7671f0a08e18
klaus2015/py_base
/code/day16/生成器练习.py
632
3.921875
4
list01 = [4,5,566,7,8,10] #方法1 list02 = [] for item in list01: if item % 2 == 0: list02.append(item) print(list02) # 方法2 list03 = [item for item in list01 if not item % 2] print(list03) #方法3 def get_odd(target): for item in list01: if item % 2 == 0: yield item g01 = get_odd(list01...
f5d9e022aaeff6f68a3e2edd79652c040a34b191
klaus2015/py_base
/data/day03/recursion.py
162
4.0625
4
""" 求一个数的阶乘 递归实现 """ def recursion(num): if num <= 1: return 1 return num * recursion(num - 1) print("n! = ",recursion(5))
73fbed975c1bf47966d57223465fe01a9acddfc1
klaus2015/py_base
/data/day03/累加.py
367
3.6875
4
# 选择排序 list01 = [10,9,4,3,5] def select(): for r in range(len(list01)-1): min = r for c in range(r+1,len(list01)): if list01[min] > list01[c]: min = c if min != r: list01[r],list01[min] = list01[min],list01[r] select() print(list01) #插入排序 def insert...
21350d5d9abac219f6d72b45e20502b84d097dac
klaus2015/py_base
/code/project_month01我的/student_manager_system.py
4,137
3.96875
4
""" 学生信息管理系统 项目计划: 1.完成数据模型类StudentModel 2.创建逻辑控制类StudentManagerContral """ class StudentModel: """ 学生数据模型 """ def __init__(self,name="",age=0,score=0,id=0): """ :param name: 姓名 str类型 :param age: 年龄 int类型 :param score: 分数 int类型 ...
98236d5baccc330d1ef6e21890d4b9d4e06f162d
klaus2015/py_base
/code/day16/月考.py
1,603
3.65625
4
# class A(object): # def go(self): # print("go A go") # class B(A): # def go(self): # super().go() # print("go B go") # class C(A): # def go(self): # super().go() # print("go C go") # class D(B,C): # def go(self): # super().go() # print("go D go") ...
1facb849f4abb618cd8fe5ccb757dcc942a5a79a
klaus2015/py_base
/code/day07/字典推导式.py
580
3.875
4
list01 = ["无极", "赵敏", "周芷若"] list02 = [101, 102, 103] dict01 = {} dict03 = {} for item in list01: dict01[item] = len(item) print(dict01) dict02 = {item:len(item) for item in list01} print(dict02) # 通过索引在多个列表中同时获取元素 for i in range(3): dict03[list01[i]] = list02[i] # 索引相同,所以用相同的一个索引即可 print(dict03) # {'无极': 10...
ff1f883239fa72719b7bc8d661ddd88804e29dc3
klaus2015/py_base
/code/day05/r10.py
195
3.953125
4
# names = ["周习明","陈曦","丁丁","罗浩"] # ages = [28,29,30,31] # for i in range(len(names)): # print(names[i], "is",ages[i], "year's old") # a = list(zip(names, ages)) # print(a)
06f801b32b81d6becefb3e5504bd47f9fb877070
klaus2015/py_base
/concur/day03/线程锁Lock.py
457
3.859375
4
""" thread_lock线程锁 """ from threading import Thread,Lock lock = Lock() # 定义锁 a = b = 0 def value(): while True: lock.acquire() # 上锁 if a != b: print("a=%d,b=%d"%(a,b)) lock.release() # 解锁 t = Thread(target=value) t.start() while True: with lock: # 上锁 a += 1 ...
c0c4b6d7ca202b163122c06b3e6e0f17a98bb6d8
klaus2015/py_base
/code/day11/作业2老师版.py
1,167
3.96875
4
""" 4. 请用面向对象思想,描述以下场景: 玩家(攻击力)攻击敌人(血量),敌人受伤(掉血),还可能死亡(掉装备,加分)。 敌人(攻击力)攻击玩家,玩家(血量)受伤(掉血/碎屏),还可能死亡(游戏结束)。 """ class Player: def __init__(self,atk,hp): self.atk = atk self.hp = hp def attack(self,other): print("玩家攻击敌人") other.damage(self.atk) def damage(self,va...
4db1862dd0c6508368c515de5ebedc672ae1f5e5
klaus2015/py_base
/剑指offer算法/练习.py
1,340
4.1875
4
'''给定一个只包括 '(',')','{','}','[',']' ,'<','>' 的字符串,判断字符串是否有效。 有效字符串需满足:  左括号必须用相同类型的右括号闭合。  左括号必须以正确的顺序闭合。  注意空字符串可被认为是有效字符串。  示例 1: 输入: "()" 输出: true  示例 2: 输入: "()[]{}<>" 输出: true  示例 3:输入: "(<{)]}" 输出: false  示例 4: 输入: "([{ }]" 输出: false  示例 5:输入: "(<{[()]}>)" 输出: true  ''' class QueueError(Exception): pass class...
daba7e92bed572893619a532c2a2c6d168774210
klaus2015/py_base
/code/day06/练习5.py
402
3.96875
4
""" 将1970年到2050年中的闰年,存入列表 """ list_leap_year = [] for item in range(1970, 2051): if item % 4 == 0 and item % 100 != 0 or item % 400 == 0: list_leap_year.append(item) print(list_leap_year) # 列表推导式 list_leap_year01 = [item for item in range(1970, 2051) if item % 4 == 0 and item % 100 != 0 o...
c01a03555580688020583d59989b0c6e14386da7
klaus2015/py_base
/data/day02/exec_1.py
618
3.875
4
""" 创建两个链表,两个链表中的值均为有序值 将连个链表合并为一个,合并后要求值仍为有序值 """ from linklist import * l1 = LinkList() l2 = LinkList() l1.init_list([1,5,7,8,10,12,13,19]) l2.init_list([0,3,4,9]) l1.show() l2.show() def merge(l1,l2): # 将l2合并到l1中 p = l1.head q = l2.head.next while p.next is not None: if p.next.val ...
0a4caf484e2250f64c6e2744033e1aae590ecbbe
klaus2015/py_base
/IO/day01/exec_1.py
599
3.765625
4
""" 从终端输入一个单词 从单词本中找到该单词,打印解释内容 如果找不到则打印"找不到" """ def search_word(): word = input("Word:") # 要查找的单词 # 默认r打开 f = open('dict.txt') # 每次获取一行 for line in f: w = line.split(' ')[0] # 如果遍历到的单词已经大于word就结束查找 if w > word: print("没有找到该单词") break elif w...
fa15e1473e6437004918a6e18c82d5568f0c05b7
klaus2015/py_base
/code/day16/迭代器.py
446
3.734375
4
tuple01 = ("铁扇公主","铁锤公主","扳手王子") iterable = tuple01.__iter__() print(iterable) while True: try: item = iterable.__next__() print(item) except StopIteration: break dict01 = {"铁扇公主":101,"铁锤公主":102,"扳手王子":103} iterable = dict01.__iter__() while True: try: key = iterable.__next_...
f56c7aa765eb2bca9821d1158d052112f5d6ae54
klaus2015/py_base
/data/day03/exec_2.py
151
3.875
4
""" 求一个数的阶乘 """ # n次 def fun(num): result = 1 for i in range(1,num + 1): result *= i return result print(fun(5))
56d82fcc0abbfa60d66e6bc9ea5cb13ec9a202c8
klaus2015/py_base
/code/day08/r1.py
302
3.765625
4
""" 练习1:定义计算四位整数,每位相加和的函数. 测试:"1234" "5428" """ def each_unit_sum(number): result = number % 10 result += number // 10 % 10 result += number // 100 % 10 result += number // 1000 return result re = each_unit_sum(1400) print(re)
cdd383d3959b8ea02086267fe51163a1f79e7aa6
klaus2015/py_base
/code/day04/r6.py
252
4.15625
4
""" 在控制台中获取一个整数作为边长. """ length = int(input("请输入边长: ")) string = "*" space = ' ' print(string * length-2) for item in range(length): print(string + space * (length - 2) + string) print(string * length)
c97b8521b5ff8af2ecbc824db3b21f3b93d57548
klaus2015/py_base
/code/day03/yesterday_review.py
590
3.921875
4
""" 重本质,弱语法 不要被语法束缚思维 看着对,就是对的 数据类型转换,数据基本转换 记住主干,理解其中小知识点 """ # and 发现False,就有了结论,后续条件不再判断,节省CPU #短路逻辑————>>尽量将复杂(耗时)的判断放在简单判断的后面 num = 1 re = num + 1 > 1 and input("请输入: ") == "a" # or 发现True,就有了结论 ————>短路逻辑 #尽量将复杂的判断放在简单判断的后面 re = num + 1 > 1 or input("请输入: ") == "a" python 引用管理机制 百度
5da93f4fc12c7d5c81675f0da6a4cbd4b74c4881
Gaotao22/CSCA08-48
/untitled-1.py
3,480
3.8125
4
def rsum(received_list): '''(list of int) -> (int) This function will take a list and return the sum of all elements. Exp: >>> rsum([1, 2, 3]) 6 >>> rsum([0, 1, -3]) -2 ''' if received_list != []: return received_list.pop() + rsum(received_list) else: return 0 d...
a7b152f7559d5f67b657840dc1f88fb53964c3f0
Gaotao22/CSCA08-48
/ex10.py
904
3.875
4
def radix_sort(unsorted): size_unsorted = len(unsorted) final_sorted = [] digit = 1 finished_num = 0 while finished_num < size_unsorted: sorted_list = [] finished_num = 0 num_bin = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[]} num_list = [0, 1, 2, 3, 4,...
5650b17874ec202f6e08731349c3ee6a58008f3b
deepak07031999/MongoPython
/create.py
1,213
3.78125
4
import pymongo from pymongo import MongoClient from random import randint #Step 1: Connect to MongoDB client = MongoClient("mongodb://Username:password@HOSTNAME:NODEPORT") db=client.newdb #Step 2: Create sample data #Here we are creating 100 business reviews data randomly names = ['Spoon','Tree','Country', 'Delecious',...
a978f84fbec7c82a587582ea173cd83d87141bb5
rikordi/Python_lessons_basic
/lesson04/home_work/hw04_easy.py
1,462
3.703125
4
# Все задачи текущего блока решите с помощью генераторов списков! # Задание-1: # Дан список, заполненный произвольными целыми числами. # Получить новый список, элементы которого будут # квадратами элементов исходного списка # [1, 2, 4, 0] --> [1, 4, 16, 0] # coding=utf-8 el = [1, 2, 4, 0] list = [g ** 2 for g in el...
3349311b8347f6eac17c3dfb9b87da5816f57e0c
eestey/PRG105-16.4-Using-a-function-instead-of-a-modifier
/16.4 Using a function instead of a modifier.py
945
4.1875
4
import copy class Time(object): """ represents the time of day. attributes: hour, minute, second""" time = Time() time.hour = 8 time.minute = 25 time.second = 30 def increment(time, seconds): print ("Original time was: %.2d:%.2d:%.2d" % (time.hour, time.minute, time.second)) ...
d1a1577c70569d24200c5fe928f7caadc6788c4e
induane/logcolor
/src/log_color/formatters.py
1,980
3.546875
4
import logging from logging import LogRecord from .colors import ColorStr from .lib import COLOR_MAP, multi_replace, strip_color from .regex import COLOR_EXP class ColorStripper(logging.Formatter): """ Strip references to colored output from message. This formatter removes all color code text from a mes...
afc3ece2ddcf862909345bc8a88fc32413a87702
dwarampudi/f2
/great.py
96
3.6875
4
a=100 if a>10: print("a is big") elif a>20: print("a is 20") else: print("default")
5887cb2957ec8f2faa03f51740e949f4295a4546
ankita0115/CloudJetTestAnkitaBetala
/Assignment 4 Python Program/disp_mult.py
475
3.8125
4
def multipleofseven(num): if(num%7)==0: return True else: return False def multipleofthirteen(num): if(num%13)==0: return True else: return False print("A program in python") for counter in range(30,300): anynum=multipleofseven(counter) othernum=multipleofthirteen(counter) if (anynum==True...
eeefc62a780f1f3a158f16786c6f3bbb8d6b278c
carolaraujo/logicaProgramacao-python
/ac1/ConversaoPolegadasmm.py
105
3.515625
4
polegadas = float(input()) m = polegadas * 25.4 print(polegadas, "polegada(s) eh o mesmo que", m, "mm")
e2c154b0924e8c33db600b7321b0c6f69a358654
saramissak/67262-spotify-term-project
/queries/analytical_query_2.py
1,036
3.78125
4
import psycopg2 as pg2 con = pg2.connect(database='spotify', user='isdb') con.autocommit = True cur = con.cursor() def query(username): tmp = ''' SELECT s.song_name FROM Song AS s JOIN Listen_Song AS ls ON s.song_id=ls.song_id WHERE ls.username = %s AND EXTRACT(YEAR FROM listened_timesta...
302bee99dec0d511bda305ec8ba4bdc6fa028138
Rossnkama/AdaLesson
/linear-regression.py
1,181
4.25
4
# Importing our libraries import numpy as np import matplotlib.pyplot as plt # Our datasets x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] # Forward propagation in our computational graph def feed_forward(x): return x * w # Loss function def calculate_loss(x, y): return (feed_forward(x) - y)**2 # To plot...