blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
51a100b4165118a5a63c57c84d15f2a59e9d7f18 | luyasi/python_study | /python-16-20180926/13.网络编程.py | 1,293 | 3.5625 | 4 | """"""
"""
网络编程:是如何在程序中实现两台计算机的通讯
socket
socketserver
服务端:被动相应的叫服务端
客户端:主动发起呼叫的叫客户端
单工:通讯通道只有一条,通讯双方不可逆。
半双工:通讯通道只有一条,通讯双方可逆。
全双工:通讯通道有多条。
服务端
1、导入socket模块
import socket
2、创建socket对象,socket是一个类
sock = socket.socket(socket_family,socket_type)
socket_family
socket.AF_INET ipv4
s... |
dbc5dc0610ab103aaba2582b94e6e84f12a760d9 | curieshicy/My_Utilities_Code | /Useful_Code_Snippets/6_find_number_of_smaller_elements_to_right.py | 2,257 | 3.796875 | 4 | # find number of the smaller elements to the right
# e.g. given [3, 4, 9, 6, 1] ---> [1, 1, 2, 1, 0]
# the first is 1 since there is only one item smaller than 3 to the right (i.e. 1)
# the second is 1 since there is only one item smaller than 4 to the right (i.e. 1)
# the third is 2 since there is only one item small... |
60cc967a96355cfbc76a68ed514d85ecf105c180 | zabiullakhangithub/Python_Session2_Assignment_2.4 | /Assignment 2.4a.py | 1,790 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 7 13:40:10 2018
@author: zabiulla.khan
Write a Python Program(with class concepts) to find the area of the triangle using the
below formula.
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
Function to take the length of the sides of triangle from user should be defined in ... |
d4e325e8da86bc8f2253905bb31c1e8f2d117629 | HenriqueNO/Python-cursoemvideo | /Desafios/Desafio_081.py | 666 | 3.734375 | 4 | lista = []
p = ''
while p != 'n':
n = lista.append(int(input('Digite um valor: ')))
p = str(input('Deseja continuar? [S/N] ')).lower().strip()[0]
while True:
if p != 's' and p != 'n':
p = str(input('Deseja continuar? [S/N] ')).lower().strip()[0]
else:
break
print(f'Vo... |
1df3416a7a435a5ba830b14695b896396aa219a3 | athletejuan/TIL | /Algorithm/BOJ/10_math2/3009.py | 254 | 3.53125 | 4 | xs,ys = [],[]
for _ in range(3):
x,y = (list(map(int, input().split())))
xs.append(x)
ys.append(y)
for x in xs:
if xs.count(x) == 1:
print(x, end=" ")
for y in ys:
if ys.count(y) == 1:
print(y) |
c16d13a8d7e1ac116f07bccf4b097b80ad074c8e | Bhogavarapuvaralakshmi/python- | /ifelse1.py | 155 | 3.578125 | 4 | p=float(input('enter apercentage'))
bl=int(input('enter no.of backloags'))
if p>=60 and bl==0:
print('eligible')
else:
print('not eligible')
|
511d391fab99d3ed7a7b93ddd2348801cde41a1e | sbauer/python-data-structures | /linked_lists/linked_list_tests.py | 1,897 | 3.78125 | 4 | import unittest
from linked_list import *
class LinkedListTests(unittest.TestCase):
def test_empty_list_should_have_no_head(self):
list = LinkedList()
self.assertIsNone(list.head)
def test_adding_one_value_should_create_head(self):
list = LinkedList()
list.insert("First")
... |
6b87aec0e53d10a19fdcd1cb6c91faa0bd963ee7 | anjlapastora/kaizend | /session-3/labs/lab_file_reverser.py | 1,717 | 4.09375 | 4 | import argparse
import sys
# create an instance of ArgumentParser without any arguments
parser = argparse.ArgumentParser(description='Read a file in reverse')
# use the add_argument method to specify a positional argument called filename and
# provide some help text using the help argument.
parser.add_argument('filen... |
bf00f696da255577468b22ab8c2ab8a0bd9981b7 | dsluijk/TICT-V1PROG-15 | /les-3/practice/3_2.py | 505 | 3.578125 | 4 | """
Sums the given list.
@param {List of Integers} getallenlijst - List of integers to sum
@return {Integer} Returns the sum
"""
def som(list=[]):
return sum(list);
# "Unit tests"
print(som([1, 2, 3])); # Expect 6
print(som([1, 0, 0])); # Expect 1
print(som([])); # Expect 0
print(som([345345345, 512451254, 654364... |
bdbde425c3ff9e190acca927c0a9ea38ef9523a3 | HAREESH341/WONDER-WORLD | /task.py | 443 | 4.09375 | 4 | list2=int(input("enter lenght of list:"))
normallist=[]
for i in range(list2):
now=input("enter the element ")
normallist.append(now)
print("total list is", normallist)
# output
# enter lenght of list:8
# enter the element 3
# enter the element 6
# enter the element 2
# enter the element 1
# enter the element 4
... |
5ffc7aced9f4500a2821d8103810504297e28033 | susanpowell/intrepid_python | /ex11.py | 415 | 3.984375 | 4 | print "How old are you?",
age = int(raw_input())
print "How old is your mother?",
mom_age = int(raw_input())
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input('Enter in pounds, please:')
birth_age = mom_age - age
print """
So you're %r years old, your mother was %r wh... |
8f7446a1e2e87f9954b6daa5b29b18623183452c | saparia-data/data_structure | /geeksforgeeks/hashing/15_subarray_range_with_given_sum_difficult.py | 2,135 | 4.125 | 4 | '''
Given an unsorted array arr[] of N integers and a sum. The task is to count the number of subarray which adds to a given number.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow.
Each test case contains an integer N denoting the size of the array. Th... |
95dbf373672ce0b3dea9746703ba618d920e5e3b | orange-eng/Leetcode | /easy/204_Count_Primes.py | 1,008 | 3.84375 | 4 |
# Leetcode practice
# author: orange
# date: 2021/6/1
'''
这题搜到一个非常牛逼的算法,叫做厄拉多塞筛法.
比如说求20以内质数的个数,首先0,1不是质数.2是第一个质数,然后把20以内所有2的倍数划去.
2后面紧跟的数即为下一个质数3,然后把3所有的倍数划去.3后面紧跟的数即为下一个质数5,
再把5所有的倍数划去.以此类推.
'''
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
""... |
4d98e253f5b9c0f8f5484082ac4e484d54cc4a0c | SandyHoffmann/ListasPythonAlgoritmos | /Lista 3/SH-PCRG-AER-Alg-03-Ex-02.py | 511 | 3.859375 | 4 | #Pedindo os anos do cachorro
idade = int(input("Quantos anos tem o seu dog? "))
#Se idade for numero negativo n pode ser considerado.
if idade<0:
print(f'Dados inválidos!')
#Se idade menor ou igual a dois calcularemos conforme foi dito pelo enunciado
elif idade<=2:
print(f'A idade do cachorro é de {idade*10.5} ... |
6094234af46ad6b25edcd8947adf82da34a723d3 | jonahhill/mlprojects-py | /TimeSeriesRegression/AnalyzeError.py | 1,655 | 3.734375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math as math
def drawLineChart(df, feilds):
ts = df[feilds[0]]
plt.plot(range(len(ts)), ts, "r--")
# df.plot(y='Sales')
plt.show()
#http://pandas.pydata.org/pandas-docs/stable/visualization.html
#df = pd.read_csv("data/ross... |
72f598b34c073cf84ae99f0e99dfd00300ad8031 | mikefeneley/topcoder | /src/SRM-171/rpg.py | 970 | 3.53125 | 4 |
class RPG:
def dieRolls(self, dice):
print(dice)
minimum = self.calculate_min(dice)
maxi = self.calculate_max(dice)
average = self.calculate_avg(dice)
final = (minimum, maxi, average)
return final
def calculate_min(self, dice):
minimum = 0
... |
832190494a73a969ab5eec0568c0a94cb1580eba | LusianaDiyan/belajarpython | /praktikum4.py | 5,893 | 3.9375 | 4 | def list1():
thislist = ["apple", "banana", "cherry"]
print(thislist)
def accesitem():
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
def negativeindex():
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
def rangeindex():
thislist = ["apple", "banana"... |
0c6acf9ab857a6ce12cfa2b2286569ed509eee55 | affection123456/Learn-python-the-hard-way | /ex37.py | 3,776 | 3.609375 | 4 | # del
a = [1,2,3]
del a[0]
print a
b = [1,2,3]
del b[1:2]
print b
# c = [1,2,3]
# del c
# print c
# as
import random as affection
# another way: import random
# affection = random
# del random
i = 0
bucket = []
while i < 10:
i = i + 1
number = affection.randi... |
f796b60606bd70afd95643afc7b6aaa87806a50a | rafaelperazzo/programacao-web | /moodledata/vpl_data/137/usersdata/172/52954/submittedfiles/Maratona.py | 160 | 3.953125 | 4 | # -*- coding: utf-8 -*-
n=int(input('número de postos: '))
x=int(input('número médio: '))
for i in range(2,n+1,1):
d=int(input('distância: '))
|
e310c9c8f1408d968ae68d2ab591a98bedd50906 | kategerasimenko/hse-ling-algorithms | /students/Zelenkova_Lera/02/5_valid_parens.py | 628 | 3.75 | 4 | class Solution(object):
def isValid(self, s):
alles = []
dict_ = {')':'(', ']':'[', '}':'{'}
for elem in s:
if elem in dict_.values():
alles.append(elem) # это начало стека - аппендим открывающую скобочку
elif elem in dict_.keys():
if n... |
d5ec0c82e3458ff36b36b977adb8a52c9688bd13 | BabafemiOyinlola/Clustering-and-Classification | /K_means.py | 5,155 | 3.640625 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
class KMeans:
def __init__ (self, k = 3):
self.k = k
self.centroids = []
# self.cluster = {}
self.points = []
self.point_labels = []
self.grouped_points = []
self.cluster = []
self.iter = ... |
25c6109ed881e0946040c31bdcfb2fda6237d51e | dlatney/Python | /band_name.py | 184 | 4.09375 | 4 | band_firstname = input("What city did you grow up in?")
band_lastname = input("What is the name of your pet?")
print("Your band name should be: " + band_firstname +" "+ band_lastname) |
7bb4db3aab4a4ae07223147b46a03c0761de52e5 | AFazzone/Python-Homework | /afazzone@bu.edu_hw_4_10_5.py | 336 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 10:16:43 2019
@author: alf11
"""
a,b,c,d,e,f,g,h,i,j = eval(input("Enter ten numbers: "))
x_list = [a,b,c,d,e,f,g,h,i,j]
y_list = []
for i in x_list:
if i not in y_list:
y_list.append(i)
print("The distinct numbers are :", str(y_li... |
d3d16c0b7daf19ed08723136a7fbc7e9377d2fcc | navya-005/sddp-python8 | /assignment321910301023-M.Navya sree-5pro.py | 147 | 3.984375 | 4 |
mystring = 'Create a list of the first letters of every word in this string'
mylist = [word[0] for word in mystring.split()]
print(mylist)
|
267160a6b5a4b723ed63d3b59c4888b2d2dbe35d | pedrolucas27/exercising-python | /list03/exer_02.py | 575 | 3.875 | 4 | #Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha
# igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
user = str(input("INFORME SEU USER: "))
password = str(input("INFORME SUA SENHA: "))
flag = False
while flag != True:
if user.lower() == ... |
bdcc09deb8ca777d02314739f3bccb0ac41234b9 | rabestro/sololearn-challenges | /easy/pro-kaleidoscopes/Kaleidoscopes.py | 130 | 3.890625 | 4 | number = int(input())
price = 5 * number
if number > 1:
price *= 0.9 # 10% discount
price *= 1.07 # Tax
print("%.2f" % price)
|
523164ea0835c7a4be72d7c181685f14dd8d8dde | elenaposadac27/Programaci-n1 | /Clases/clase12/pandas_ejemplo.py | 1,353 | 3.96875 | 4 | import pandas as pd
#Primera entrada nombre de archivo
#Segunda entrada Encoding
#Terecera entrada el header
#delimitador es el caracterecter especial que separa mis datos
#.to_dict transforma mis datos en un diccionario
#Asi:
# diccionario =p.read_csv("estudiantes.csv",encoding='UTF-8', header = 0,delimiter=';').... |
43010c39b593e02f0f369c92d3e6812d484c4551 | hisland/my-learn | /python3/python3.6.2-doc/section5-data-structure/06.list-comprehension.map.py | 187 | 3.703125 | 4 | list1 = [1, 2, 3]
list2 = list(map(lambda x: x**2, list1))
list3 = [x1**2 for x1 in list1]
list4 = [x1**2 for x1 in list1 if x1 > 1]
print(list1)
print(list2)
print(list3)
print(list4)
|
34543610688e988c3f27b047ad60e7b08c5a0230 | viktorpenelski/adventofcode2020 | /day_3/day_3.py | 876 | 4.0625 | 4 | def file_lines_as_matrix(file_name):
with open(file_name, "r", encoding="utf-8") as file:
# list(str) returns a char array :O
return [list(line.rstrip("\n")) for line in file]
def find_trees(slope, right=3, down=1):
rows = len(slope)
cols = len(slope[0])
c = 0
trees_encountered = 0... |
3f26b9cd88314d580cd7dada3f29c2f2dd25c840 | blackplusy/weekend0303 | /例子-0324-03.return.py | 228 | 3.71875 | 4 | #coding=utf-8
def sum(a,b):
jisuan=a+b
return jisuan
s=sum(99,1)
print(s)
#多个返回值
def re(a,b):
a*=10 #a=10*a
b*=10
return a,b
num=re(4,5)
print(num)
print(type(num))
num1,num2=re(10,40)
print(num1,num2)
|
4d895940e873cc24eb422c5b15d2dcc6bf0e4bb7 | ftlka/problems | /leetcode/edit-distance/solution.py | 704 | 3.5 | 4 | def minDistance(word1, word2):
dp = [[0] * (len(word1) + 1) for l in range(len(word2) + 1)]
# first row is from 0 to len(word1) + 1
for i in range(len(word1) + 1):
dp[0][i] = i
# same for first column
for i in range(len(word2) + 1):
dp[i][0] = i
for i in range(1, len(word2... |
a180a10780e8b1f92cc9d7ac259290322ba40506 | subodhss23/python_small_problems | /return_high_and_low.py | 439 | 4.0625 | 4 | ''' Create a function that accepts a string of space separated integers and returns the highest and
lowest integers(as a string). '''
def high_low(txt):
new_lst = txt.split()
int_lst = []
for i in new_lst:
int_lst.append(int(i))
return max(int_lst), min(int_lst)
# print(high_low("1 2 3 4... |
0515fd45161985a16aeb12193a63193c45aeb2c0 | FraBenny/TensorflowHandwriting | /main.py | 1,160 | 3.578125 | 4 | import sys
import preprocess
import cnn
def main(train):
# Load all data
X_train, y_train, X_test, y_test, mapping = preprocess.load_data('emnist')
cr = cnn.CharRecognizer()
if train:
# Train the Convolutional Neural Network
cr.train_model(X_train, y_train, epochs=10)
# Save... |
8e6b147f9f7a07f1f08b9206adab44168e496859 | lucasbbs/APC-2020.2 | /funções/questao6/main.py | 406 | 3.71875 | 4 | str1, str2, numero = input().split()
numero = numero
numeric_filter = filter(str.isdigit, numero)
numeric_string = int("".join(numeric_filter))
def concatenar(str1, str2):
return str1 + str2
def repetir(str1, str2):
return str1*numeric_string
def ambos(str1, str2):
return (str1 +str2)*numeric_stri... |
9bd1a208632e199f09bea4ea8f5cbeb4c5aab591 | innovationb1ue/MathModeling | /seed.py | 6,521 | 3.5625 | 4 | import math
import random
def sum(list):
total = 0.0
for line in list:
total += line
return total
def rand(a, b):
number = random.uniform(a,b)
return math.floor(number*100)/100
PI = math.pi
def fitness(x1,x2):
return 2*(x1-3)*math.sin(8*PI*x2)+(x2-4)*math.cos(13*PI*x1)
def todecimal(str... |
027864a39a5ce6f243d7a44dcfec4aa3e4a01aa7 | UmuhireAnuarithe/Login | /run.py | 1,301 | 4.125 | 4 | #!/usr/bin/env python3.6
from sigin import User
U=input("username : ")
print("create password")
P=input("password : ")
save = User(U, P)
save.saving()
print("Username and password has been created !!!")
print("Welcome again login into your acount")
#this will check the created account
def main():
print("... |
f63b22c3c82b300120597cdcd09ecb217a57b80c | jagadeesh1414/assign5_note_M2.py | /assign5_prog2_M2.py | 259 | 4.25 | 4 | from math import tan,pi
GRAVITY = 9.8
length = float(input("Enter the length of each side of Polygon (in meters): "))
number = int(input("Enter the number of sides: "))
area = (number * length ** 2)/(4 * tan(pi/number))
print("The area of Polygon is ",area) |
de721f47e50c60be0343ba8aab043979a21573a7 | shen-huang/selfteaching-python-camp | /19100205/vassili321/d5_exercise_array.py | 702 | 4.03125 | 4 | arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 将数组反转
arr.reverse()
print('this ia a reversed array:',arr)
# 将翻转后的数组拼接成字符串
str1 = ''.join(str(i)for i in arr)
print(str1)
# 用字符串切片的方式取出第三个到第八个字符(包含第三和第八个字符)
str2 = str1[2:8]
print(str2)
# 将获得的字符串进行反转
str3 = str2[::-1]
print(str3)
# 将结果转为int型
int1 = int(str3)
print(int1)
# 分别转换成二进制... |
a57739788d056f2c641ca1874e06d40a919dfe48 | haka913/programmers | /p_2_예상대진표.py | 234 | 3.53125 | 4 | n = 8
a = 4
b = 7
def solution(n, a, b):
cnt = 0
while a!=b:
a = a//2+ a%2;
b = b//2+b%2;
cnt+=1
return cnt
print(solution(n,a,b))
# def solution(n,a,b):
# return ((a-1)^(b-1)).bit_length() |
a2e1a4c7376856891dcce7e675bc4320492c30ff | kookoowaa/Repository | /SNU/Python/BigData_Programming/170623/t6.py | 184 | 3.71875 | 4 | a = ['aa','ab','ac','ad','ae']
b = ['zz','xx','cc','vv']
print("{0[1]} {1[2]} {0[3]} {0[4]} {0[4]}".format(a, b))
c = 2
d = 3
print ('{1} {0}'.format(c,d))
print ('{} {}'.format(c,d)) |
4628ac76ff485655807e06bfd7e99b68f0421c35 | HyunIm/Baekjoon_Online_Judge | /Problem/2566.py | 289 | 3.515625 | 4 | table = [list(map(int, input().split())) for _ in range(9)]
maxValue = 0
row = 0
column = 0
for i in range(9):
for j in range(9):
if maxValue < table[i][j]:
maxValue = table[i][j]
column = i
row = j
print(maxValue)
print(column+1, row+1)
|
396cfcb4582910a9bf3c92c3fd85e41a7174e9aa | viswaf1/HierarchicalMeshClustering | /init.py | 2,081 | 4.0625 | 4 |
import sys
import os
# Python 2 compatibility
try:
input = raw_input
except NameError:
pass
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user ... |
1e879b6dac805d3fc7007619c79764341554bcb2 | kaioaresi/coursera | /Intro_ciencia_python/semana_5/exercicio_aula/binomial.py | 422 | 3.859375 | 4 |
n = int(input('Digite o valor N: '))
k = int(input('Digite o valor K: '))
def fatorial(numero):
x = numero
f = 1
while x > 0:
f *= x
x -= 1
return f
'''
n! / k!(n - k)!
'''
def binomial(n, k):
return fatorial(n) // (fatorial(k) * (fatorial(n - k)))
def test_binomial():
if binomial(20, 10) == 18475... |
94f9719ea3bafb52fb5ea71541380aa245912c33 | linhx13/leetcode-code | /code/1253-reconstruct-a-2-row-binary-matrix.py | 870 | 3.53125 | 4 | from typing import List
class Solution:
def reconstructMatrix(
self, upper: int, lower: int, colsum: List[int]
) -> List[List[int]]:
n = len(colsum)
res = [[0] * n for _ in range(2)]
for i, s in enumerate(colsum):
if s == 2 or (s == 1 and lower < upper):
... |
2e6c3169c63b1b5b56ede484baf427a4c7f26eb9 | chetanhonnavile/beginner | /Numpy_matrix.py | 943 | 4.28125 | 4 | # Create multidimensional matrix using class
# Use numpy to do basic math.
import numpy as np
import random
class Matrix():
"""Matrix Multiplication"""
def __init__(self,row,col):
self.row = row
self.col = col
self.mat = []
for i in range(0,row):
self.mat.append([... |
10bd3565e441ab861c209b9b36e06a8b492e992c | fsonntag/nalaf | /nala/structures/data.py | 11,119 | 4.28125 | 4 | class Label:
"""
Represents the label associated with each Token.
"""
def __init__(self, value, confidence=None):
self.value = value
"""string value of the label"""
self.confidence = confidence
"""probability of being correct if the label is predicted"""
def __repr_... |
e3db282c4bfb08dd03e5f0b1b971d8953092d51b | cd-chicago-june-cohort/Python_random_Sam | /Fundamentals/mult-sum-avg.py | 572 | 3.734375 | 4 | #Multiples
#Part One
def odd_print():
for num in range(1, 1000):
if (num % 2 == 0):
continue
print num
#odd_print()
#Part Two
def multiples_of_five():
peak = 1000000 / 5
for mult in range (5, peak + 1):
print 5 * mult
#multiples_of_five()
#Sum
def sum_of_list(ls... |
cc749e3a6afba59f7503733e7b5c57abbcbf716a | uesin/python | /bmi.py | 538 | 4.125 | 4 | #BmI判定プログラム
while True :
try:
weight = float(input("体重(kg)は?"))
height = float(input("身長(cm)は?"))
#bimの計算
height = height / 100 #mに直す
bmi = weight / (height * height)
break;
except:
print("入力ミスがあります。")
if bmi < 18.5:
result = "痩せ型"
if (18.5 <= bmi < 25):
result = "普通体重"
if (25... |
57180c58446e1aa04387804dd7a2a522089e37a4 | armandorp10/KataMaximo | /CalculadoraTest.py | 2,337 | 3.53125 | 4 | from unittest import TestCase
from Calculadora import Calculadora
class CalculadoraTest(TestCase):
def test_getEstadisticas(self):
self.assertEquals(Calculadora().getEstadisticas("")[0], 0, "Cero numero de elementos")
def test_getEstadisticasUnNumero(self):
self.assertEquals(Calculadora().ge... |
51bb3b277ed18d6de40e78d1cd5f6b91421260b5 | anorak6435/CStupid | /cstupid/data_objects/cstast.py | 1,593 | 3.734375 | 4 | # contains the Nodes of the syntax tree
class Node(object):
pass
class VarDeclar(Node):
def __init__(self, vartype : str, varname : str, value : Node):
self.type = vartype
self.name = varname
self.value = value
def __repr__(self):
return f"(VARDECLAR {self.type}:{self.name... |
69c20b8fea6caa94c9d133bac5670f9f708903fe | podoynitsyn-va/GEEKBRAINS-Learning | /1.Introduction_to_Python/Guess_the_Number/someone/Lesson3_Угадайка.py | 3,815 | 3.984375 | 4 | # ТЗ 3 Угадайка
import random
user_number = 0 #чтобы услвоие красивое работало
levels = {1:15,2:10,3:5}
#Определим диапазон чисел для игры
#Ихже будем использовать для сужения диапазона
number_min = 1
number_max = 100
# Если true, то в двух последних попытках будем брать случайное число
panic_mode = True... |
b23478f8e01b5f1ad002101e776dca37e216a66a | chimnanishankar4/200244525033_shankar | /Day 1/lower_case.py | 327 | 4.25 | 4 | #Arrange String characters such that lowercase letters should come first
str="PyNaTive"
lower_case=[]
upper_case=[]
for i in str:
if i.islower():
lower_case.append(i)
else:
upper_case.append(i)
sort_string=''.join(lower_case + upper_case)
print("Arranging characters in lower case:")
print(sort_s... |
547fdef244f23621ba91687fac9b01e0305b650e | daveshed/lego-bot | /daveshed-legobot/daveshed/legobot/robot.py | 3,743 | 3.921875 | 4 | """
Robot class definitions
"""
import abc
import logging
_LOGGER = logging.getLogger("ROBOT")
class Robot(abc.ABC):
"""
The robot base-class has a fixed API that will be accessed by a controller
object or alternatively by direct calls.
"""
@abc.abstractmethod
def move_x(self, distance):
... |
3097cc81256a8d9724c8ae2447f7e2c36a00d516 | santanu5670/Python | /coding/Anonymous_Lambda/lambda.py | 141 | 3.90625 | 4 | minus=lambda x,y:x-y #this called lambda function
print(minus(10,5))
def sub(x,y): #this is normal function
m=x-y
print(m)
sub(10,5) |
ed63ad8df5c22b07332c92849deb4f4d75b3dc6a | tyagian/Algorithms-and-Data-Structure | /leetcode/top-100/1_array/6_maximum_subarray.py | 245 | 3.71875 | 4 | """
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
"""
|
02eb0a3ec16a4f6718875c2adf85dc03c5e274ae | acc-cosc-1336/cosc-1336-spring-2018-Aronpond | /src/homework/homework9/player.py | 849 | 4.09375 | 4 | #write import statement for Die class
from src.homework.homework9.die import Die
'''
Create a Player class.
'''
class Player:
def __init__(self):
'''
Constructor method creates two Die attributes die1 and die2
'''
self.die1 = Die()
self.die2 = Die()
def ro... |
8a3f321ae3366e401d984ae3472738ce3646225c | ProfessorJas/Python_100_days | /day_004/break.py | 101 | 3.953125 | 4 | for letter in 'ityouknow':
if letter == 'n':
break
print('Current letter: ' + letter) |
8eed8d8ec4f0eeb48c15e4a1d5c9bece943b7d82 | rrabit42/Python-Programming | /Python프로그래밍및실습/ch12-TKinter/lab12-9-My calculator.py | 10,786 | 3.765625 | 4 | from tkinter import *
# button 0, 1, 2, ... , 9를 눌렀을 때 실행할 함수들 정의
def btn0Compute():
choice = var.get() # radio button 값 받음
if choice == 1: # 숫자1 입력 상태
e1Val = e1.get()
if e1Val == "" : # 비어 있다면
newNum = 0 # 새로운 값은 0이다
else: # 비어 있지 않다... |
1890caf5564e36fdbf3178a167e22daa625cb1df | TheAlgorithms/Python | /dynamic_programming/combination_sum_iv.py | 2,811 | 4.1875 | 4 | """
Question:
You are given an array of distinct integers and you have to tell how many
different ways of selecting the elements from the array are there such that
the sum of chosen elements is equal to the target number tar.
Example
Input:
N = 3
target = 5
array = [1, 2, 5]
Output:
9
Approach:
The basic idea is to... |
9760b875fd877da97761723730df391b59208e1a | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/kindergarten-garden/d34ee3b4c33b4ab798dadf791cf3783a.py | 1,111 | 3.59375 | 4 | from collections import defaultdict
class Garden:
STUDENTS = ['Alice',
'Bob',
'Charlie',
'David',
'Eve',
'Fred',
'Ginny',
'Harriet',
'Ileana',
'Joseph',
'K... |
60596d57f832b20af0c54abcc3ed8cfd8b69a2b9 | cjwmay/CodingDojoAssignments | /Python/FooBar.py | 538 | 3.765625 | 4 | #for x in range(100,1000):
#for a in range(2,x/2):
#if x==a*a:
#print x,"Bar";
def isPrime():
primecount = 0
for i in range(100, 10000):
count = 0
count2 = 0
for j in range(2, i):
if i%j == 0:
count += 1
if i/j == j:
... |
2c9628b7952d4cdf958b9fd93bf53976f405b3f7 | MoranLi/algoritm-and-data-structure | /linkedlist/ck189/partition-before.py | 297 | 3.734375 | 4 | import random
def partition_before(listx,partition):
for a in range(0,len(listx)):
if listx[a] < partition:
ele = listx.pop(a)
listx.insert(0,ele)
return listx
list1 = []
for x in range(0,10):
list1.append(random.randint(0,5))
print(list1)
print(partition_before(list1,2)) |
4db41d3c3988a98eebff3450142db03be31821d8 | koustavmandal95/Competative_Coding | /Greedy Problems/problem_discussion.py | 672 | 3.5 | 4 | def get_number(arr,k):
arr=sorted(arr)
small = arr[0]+k
big = arr[len(arr)-1]-k
if small > big:
small,big=big,small
for i in range(1,len(arr)-1):
substract=arr[i]-k
add=arr[i]+k
if (substract>=small) or (add <=big):
arr[i]=substract
... |
176370ff25555cb81bef46aef2ceec5799a3424d | Eric6320/graduateWork | /finishedScripts/root_find_bisection.py | 1,354 | 4.15625 | 4 | import numpy as np
# root_find - Program to find the roots of a polynomial of degree three using Bisection Method.
# Author: Edward J. Brash
# Initialize the polynomial
a0 = 1.80
a1 = -4.05
a2 = 0.40
a3 = 1.00
xlow = -4.0
xhigh = 4.0
npoints = 10000
xval = np.empty(npoints, dtype=object)
yval = np.empty(npoints, dt... |
8817506d6416504b6e10a84dc5341cf489892bed | marczuo/LatinTextID | /textmodel_simp.py | 3,378 | 3.625 | 4 | #!/usr/bin/env python
# encoding: utf-8
import string
import re
import json
class TextModel(object):
"""A model for storing text identification data."""
def __init__(self, name):
"""Keyword arguments:
name -- Identifying name of the text model.
"""
self.name = name
self.words = {} # Dictionary of word fr... |
984423238367d0b121328f61a6970c8b307fed75 | maxleverage/math | /consecutive_prime_sum.py | 5,236 | 4.15625 | 4 | #!/usr/bin/env python
import math as m
import numpy as np
import time
""" Search Space Definition """
def sieve(number_limit):
""" Checks for all primes below a given number limit """
numbers = range(0, number_limit)
for prime in numbers:
if prime < 2:
... |
cf961c4f7efdc0dae398387ad839b732ff5bc3e4 | Neutrino666/Learning_SQLite | /car_in_bd_engine.py | 8,330 | 4.09375 | 4 | import sqlite3
def user_answer():
# Меню пользователя
user_menu = """
_______________________________________________
/ МЕНЮ ДЛЯ РАБОТЫ С БД \\
| 1. Посмотреть все авто 2. Добавить авто |
| 3. Найти авто 4. Изменить данные |
... |
d921db97e90bc01de447f7cafae8bf7e1850b8b0 | vrna/AoC-2017 | /7- tree/tree.py | 2,946 | 3.515625 | 4 | import sys
from collections import Counter
file = open(sys.argv[1],"r")
data = file.readlines()
#trees = [int(i) for i in data[0].split()]
# padx (45) -> pbga, havc, qoyq
# hmm, i wouldn't even need to build a tree to find out the answer...
class Tree(object):
def __init__(self, dataline):
splitData = d... |
5062fca707e7a0cd8e3733540f53da571d2deaac | Mamata720/if-else | /gread.py | 238 | 4.03125 | 4 | per=int(input("enter a number"))
if per<25:
print('F')
elif per>=25 and per<45:
print('E')
elif per>=45 and per<50:
print('D')
elif per>=50 and per<60:
print('C')
elif per>=60 and per<80:
print('B')
else:
print(A)
|
5708dbbb9a2d82d141eb095ea25a1c3f6e183dea | 511717out/Learn-Python-The-Hard-Way | /Lean Python The Hard Way/ex3.py | 1,737 | 4.4375 | 4 | # _*_ coding:utf-8 _*_
# 打印输出“I will now count my chickens:这句话”
print "I will now count my chickens:"
# 打印输出Hens 并计算25+30/6的值 注意算数优先级
print "Hens", 25 + 30 / 6
# 打印输出 Roosters 斌计算100-25*3%4
print "Roosters", 100 - 25 * 3 % 4
# 打印输出 Now I will count the eggs:
print "Now I will count the eggs:"
# 打印输出 3+2+1-5+4%2-1/4+... |
ccc7539c53a27ac35255aa90aaa79e8ba3d4feb1 | BedaSBa6koi/Homework-07.05.2020-task-1 | /ak-47.py | 568 | 3.703125 | 4 | class Soldier:
def __init__(self,name):
self.name = name
class Guns:
def __init__(self, gun):
self.gun = gun
class Act_of_shooting(Soldier, Guns):
def __init__(self, name, gun):
self.gun = gun
self.bullets = 30
super().__init__(name)
def fire(self):
pri... |
e74d1ac2d57c092127737600b8523f2d82c613cf | abhinavgoyal13/Python | /ibm/sdet/Try&Except.py | 135 | 3.65625 | 4 |
try:
x = int(input("Enetr temp"))
x= x*100
print(x)
except:
print("Enter a number")
finally:
print("i will print") |
01903fc8c473dc0d4157585e76b0a02ed36d91b1 | FumihisaKobayashi/udemy_python3 | /control_structure/function.py | 781 | 4.28125 | 4 | #まず関数定義から実行する
"""
def say_something():#関数定義def
print('hi')
f = say_something()#()つける必要がある
f()#functionという型なので f で出力なども見える
"""
def say_nothing():
s = 'hi!'#sの変数宣言
return s #返り値 sで返す
result = say_nothing() #resultで返り値を出力
print(result)
def what_is_this(color):#color 引数
if color == 'red':#colorがredなら
retu... |
401492c951dfdb5af0b959183f8945ca25b09638 | PriyankaKhire/ProgrammingPracticePython | /Blind 75/Programs/Serialize and Deserialize Binary Tree - LevelOrder Toomuch Space.py | 3,214 | 3.921875 | 4 | # Serialize and Deserialize Binary Tree
# https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def height(self, nod... |
d34c333fa05b5fd1990fdff466ee03bd5e43b5a8 | NikitaAlexandrovich/lessonsProj | /pandas/pandasTask.py | 3,467 | 3.90625 | 4 | import pandas as pd
data = pd.read_csv("data_adult.csv")
data.head()
print(data)
# 1. Сколько мужчин и женщин (признак sex) представлено в этом наборе данных?
sumMale = sum(data.sex == "Male")
sumFemale = sum(data.sex == "Female")
print("Мужчин: ", sumMale, " Девушек: ", sumFemale)
# 2. Каков средний возраст (признак... |
e273c835908a988c6ff7875446626db271863c84 | jeffreymkabot/adventofcode2018 | /day14/part2.py | 862 | 4 | 4 | import sys
import os.path
from part1 import simulation
from typing import List
def subsequence(search: List, seq: List) -> bool:
"""Determine if seq is a subsequence of search, starting at index 0.
"""
return len(search) >= len(seq) and all(x == y for (x, y) in zip(search, seq))
def main():
sequence... |
ae21dccd1c93926627a7a16f634fe43d89295a31 | Elly-bang/python | /chap03_Datastr/lecture/step02_list2.py | 1,013 | 3.71875 | 4 | '''
리스트 내포
-list에서 for문 사용
형식1) 변수=[실행문 for 변수 in 열거행 객체 ]
실행순서 : 1. for > 2. 실행문 > 3. 변수 저장
형식2) 변수=[실행문 for 변수 in 열거행 객체 if 조건식 ]
실행순서 : 1. for > 2. if문 > [3.실행문 > 4.변수 저장 (생략 가능)] ===>??????순서
'''
#형식1) 변수 = [실행문 for 변수 in 열거행 객체 ]
#x 각 변량에 제곱
x=[2,4,1,3,7]
#x**2
data=[]
for i in x:
print(i**2)... |
9f66a60010011f2a61773284bd45767d47c557c8 | Patrrickk/aprendendo_python | /ex099.py | 500 | 3.78125 | 4 | from time import sleep
def maior(* m):
maxx = 0
print('-' * 60)
print('Analisando os valores passados...')
for pos, c in enumerate(m):
if pos == 0:
maxx = c
else:
if c > maxx:
maxx = c
print(c, end=' ')
sleep(.5)
print(f'Foram... |
b509aa02f03da1a2f447fd0a2f2333e22477de59 | tatparya/LeetCode | /Add and Search Word - Data Structure Design/solution.py | 2,926 | 4 | 4 | class TrieNode(object):
def __init__(self, isWord):
self.isWord = isWord
self.charMap = {}
def __str__(self):
return ( "Is Word : " + str( self.isWord ) + str( self.charMap ) )
class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here... |
0b73901a3fd5e22ec13eecb908ebe7393eef44af | mdumke/reinforcement-learning-experiments | /tic-tac-toe-agent/game.py | 2,238 | 3.78125 | 4 | from board import Board
from players import *
class Game:
def __init__(self, player1, player2):
self.board = Board()
self.players = [player1, player2]
def run_training(self):
'''
runs a single game and returns the winner, i.e. 0 (stale), 1, or 2
returns the winner
... |
e9d9d4a3526fe321e8f28ad49f5a6dea0904e607 | khushboojain123/python-code | /armstrong no.py | 854 | 4.09375 | 4 | # python programe to find armstrong no.
#an armstrong no is the sum of the power of its digit is equals to the no. itself
def armstrong():
return armstrong()
def main():
num = int(input("Enter a number:-"))
if num =='x':
Break
else:
number = int (num)
total = 0
... |
0474fdd97619776cd71c145c0faa4b665228164f | yuanxu-li/careercup | /chapter7-object-oriented-design/7.1.py | 4,334 | 4.09375 | 4 | # 7.1 Deck of Cards: Design the data structures for a generic deck of cards. Explain how you would subclass the data structures
# to implement blackjack.
import pdb
from random import shuffle
class DeckOfCards:
def __init__(self, num_of_decks=4):
self.clear_decks(num_of_decks)
def clear_decks(self, num_of_decks=4... |
047f6614c1eb557e001bc39da808eada58a89b19 | samschmalz/PythonFiles | /PythonStructures/Queue.py | 234 | 3.734375 | 4 | #!/usr/bin/python3
__author__ = "Sam Schmalzried"
class Queue:
def __init__(self):
self.items = []
def enqueue(self, x):
self.items.append(x)
def dequeue(self):
return self.items.pop(0)
def count(self):
return len(self.items)
|
22e30debe977357b7ab2c556f2ebfe55d077f11b | JohnAdamsII/A_star | /A_Star.py | 1,963 | 4.15625 | 4 | from Map import Map
def main():
#initialize a new map
my_map = Map("connections.txt", "locations.txt")
while True:
start = input("Enter the start node: ")
if start not in my_map.connections_dictionary.keys():
print("Invalid selection. Please try again...\n")
else:
... |
f7f1177c426578cbb7756e339ff120ba0b8f1e15 | skuldyami/praxis | /HackerRank/plus_minus.py | 427 | 3.640625 | 4 | def plusMinus(arr):
pos=0
neg=0
zeros=0
for i in range(len(arr)):
if arr[i]>0:
pos+=1
elif arr[i]<0:
neg+=1
else:
zeros+=1
print("{:.6f}".format(float(pos)/len(arr)))
print("{:.6f}".format(float(neg)/len(arr)))
print("{:.6f}".format(float(zeros)/len(arr)))
if ... |
499e72ced10b7a8a1939dab9ec0fd467561063ad | borin98/RedesNeuraisEmPython | /RedePercepton/Perceptron.py | 2,968 | 3.84375 | 4 | import matplotlib.pyplot as plt
import random as r
"""
Classe na qual cria o objeto Perceptron para a análise de seu uso
no algorítmo principal
"""
class Perceptron :
def __init__(self, amostras, saidas, taxaAprendizado=0.1, epocas = 1000, limiar = -1) :
self.amostras = amostras
self.saidas = s... |
5695a4489f036b71accf9badf3d29787e977b65b | jcgallegorpracticas/patrones-decorator-flyweight-interprete-null_object | /patron decorador.py | 2,028 | 4.4375 | 4 | """
Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending
functionality.
"""
import abc
import math
class Component(metaclass=abc.ABCMeta):
"""
Define the interface for objects that can have responsibilities
added ... |
f3d3a861351c7ea37f8f8a0d8f2b2fd91ce8b873 | JiangHuYiXiao/PythonStudy | /Python基础&并发编程/day22/small_game/game/game.py | 1,184 | 4.25 | 4 | # -*- coding:utf-8 -*-
# @Author : 江湖一笑
# @Time : 2021/8/4 16:57
# @Software : Python_study
# @Python_verison : 3.7
'''
要求1:
一个回合制小游戏,每个角色都有hp、power,hp代表血量,power代表攻击力,hp的初始值为1000,power为200.
定义一个fight方法:
hp_final = hp - enemy_power
hp_enemy = enemy_hp - power
两个人的血量对比,剩下多的获胜
要求2:
多了一个角色,叫做后裔,后裔继... |
c74982e567fbb0b18b653cd927c66327d582730e | digitalrebar/provision-plugins | /cmds/vmware/content/templates/passgen.py.tmpl | 2,151 | 3.5625 | 4 | #!/usr/bin/env python3
import random
import string
SPECIAL_LIST = "%@^"
lowers = string.ascii_lowercase
uppers = string.ascii_uppercase
nums = string.digits
def gen_pass(length=10, chars=7, req_nums=2, special_chars=1,
special_char_list=None, upper=2, lower=5, padding=None,
... |
c0c2cc8df6f9995808c3cc0184411298d681f83b | byronlara5/python_analyzing_data | /module_3/four.py | 3,877 | 3.65625 | 4 | import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
from scipy import stats
file = '/home/byron_lara/PycharmProjects/analyzing_data/venv/module_3/cars_bins_and_dummy.csv'
df = pd.read_csv(file)
#Correlation and Causation
""... |
66bf8f084b8fef1f1669d250a309792893a66f4b | cyhe/Python-Note | /Base/1.6_Iteration.py | 1,013 | 3.796875 | 4 | # for interating_var in sequence:
# statements(s)
for letter in 'Python':
print('当前字母:', letter)
fuilts = ['banana', 'apple', 'mango']
for fruit in fuilts:
print('当前水果:', fruit)
print('-------end---------')
# 通过序列索引迭代
fruits1 = ['banana', 'apple', 'mango']
for index in range(len(fruits1)):
print('当前... |
483754e2714f864664586a3ce0aefd6acd9b93fb | OswaldZero/pythonLearning | /实验2.8 类的运算符重载.py | 990 | 4.09375 | 4 | import math
class Vector3:
x=0
y=0
z=0
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def __add__(self,anotherPoint):
vector=Vector3(self.x+anotherPoint.x,self.y+anotherPoint.y,self.z+anotherPoint.z)
return vector
def __sub__(self,anotherPoint):
... |
c8da2324fd718e840ee4369b18ccdc36b2de70dd | damar-wicaksono/learn-python-THW | /ex3/ex3_drills_2.py | 321 | 3.828125 | 4 | # -*- coding: utf-8 -*-
#
# Learn Python the Hard Way, 3rd Edition
# Adapted for python3
# Exercise 3: Numbers and Math
# Study Drills 2
#
# Print statement the purpose of calculation
print("Calculating the inlet void fraction:")
print("inlet void fraction = ", \
1 / (1 + (1-0.05) / 0.05 * 1.1274*10**-3/-0.1943))... |
4893fbfa1476e136cf3bde12cc7415fb3b349d1f | HareemZubair/Pycharm | /hello_world/main6.py | 147 | 3.859375 | 4 | #if else
print("Enter your marks:")
marks = int(input())
if (marks>80):
print("A+")
elif (marks>60 ):
print("B")
else:
print("Failed")
|
3fb61bc29acb89c514e033c3e5ed2aec4d853003 | MerleLiuKun/python-demo-small | /Questions/basic/fib_def.py | 251 | 3.78125 | 4 | # coding=utf-8
"""
问题: 求斐波那契数列第n项的值
"""
def fib(number):
if number <= 1:
return number
else:
return fib(number - 1) + fib(number - 2)
if __name__ == '__main__':
n = 5
print(fib(n))
|
6480f807776d2ba5a078aa5d5304c1ab400e43b1 | move-z/adventofcode2015 | /src/16_aunt_sue.py | 29,496 | 3.71875 | 4 | #!/usr/bin/env python3
def first(aunts):
stuff = {
'children': 3,
'cats': 7,
'samoyeds': 2,
'pomeranians': 3,
'akitas': 0,
'vizslas': 0,
'goldfish': 5,
'trees': 3,
'cars': 2,
'perfumes': 1
}
def accept(aunt_stuff):
fo... |
161e26cb36aa011cfead24f2c5716fe7d68e825c | parasmehan123/Machine-Learning | /TextPreprocessing_V1.py | 4,506 | 3.625 | 4 | """****************************************************************************"""
"""SCRIPT FOR TEXT PREPROCESSING"""
"""Steps involved in preprocessing
1. Noise Removal.
i. Removing HTML tags.
ii. Replacing contractions.
2. Tokenization.
3. Normalisation.
i. Removing non-ASCII characters.
ii. ... |
49ffec2da75af775d7a956b0f0ea4c4fa63aa2f5 | Anshuman2328/pyfunda | /interm.two.py | 2,480 | 3.78125 | 4 |
arr = [10,7,8,3,2,9]
def sel(arr):
for i in range(len(arr) +1):
if arr[i] < arr[i+1]:
i = i+1
else:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1]
return(arr)
print(sel(arr))
# x = [ [5,2,3], [10,8,9] ]
# students = [
# ... |
e6b166337c5eab84b08fb4f45524fdc28b8659c4 | kayfay/scientific_programming_python | /intro_materials/var_newton2law_motion.py | 1,033 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""Newton's second law of motion:
y(t) = v0*t - (1/2)*g*t**2
* v0 as initial velocity of objects
* g acceleration of gravity
* t as time
With y=0 as axis of object start when t=0 at initial time.
As a transform for a function of motion and return to initial state:
v0*t - (1/2)*g*t**2 = t(v0... |
1d6569d36df5b0e38d7c3a031d7941f424441e3a | iehoshia/math | /encript.py | 800 | 3.65625 | 4 | import random
def get_prime(n):
prime = True
for i in range(2,n-1):
if n % i == 0:
prime = False
break
return prime
prime = False
while (prime == False):
#p = input("INPUT THE VALUE OF P: ")
p = random.randint(1,256)
p=int(p)
prime = get_prime(p)
prime = False
while (prime == False):
#q = input("INPU... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.