blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
121797e8fa3828ddf9cedcde10679abd6a73bac9 | annaQ/annaWithLeetcode | /Reverse Words in a String.py | 494 | 4.15625 | 4 | # Given an input string, reverse the string word by word.
# For example,
# Given s = "the sky is blue",
# return "blue is sky the".
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
list = s.split(" ")
list.reverse()
newStr = ""
for str in l... |
d1a6f7f242bc7c2af3d35c9176040f8c0df0adbb | annaQ/annaWithLeetcode | /Reverse Integer.py | 452 | 4 | 4 | # Reverse digits of an integer.
# Example1: x = 123, return 321
# Example2: x = -123, return -321
# How to deal with the possible overflow?(although no test case on that)
class Solution:
# @return an integer
def reverse(self, x):
if x == 0 or x == None:
return x
new = 0
tmp = abs(x)
dir = tmp / x
whil... |
9c4ee98244418c7726fae42702fb511799f2cb2e | depth221/python | /If Else.py | 79 | 3.9375 | 4 | x = 5
if x % 2 == 0:
print("x is odd")
else:
print("x is even")
|
d9fd069b53ccaccaa63c71fdbbbd7423d0a24c46 | RNSAINJU/Python | /list.py | 989 | 4.46875 | 4 | #Create a List:
# thislist = ["apple","banana","cherry"]
#Print the second item of the list:
# print(thislist[1])
#Change the second item:
# thislist[1]="blackcurrent"
#Print all items in the list, one by one:
# for x in thislist:
# print(x)
# Print the number of items in the list:
# print(len(th... |
cca2bb0dda0ac3b2c404299b1b15adc3063fb04a | gkedts/gachasims | /goldsim.py | 2,755 | 3.71875 | 4 | """
A Python 2.7 implementation of the gold capsule pull simulator. Can simulate multiple and specific pulls, as well as collect and export data to a .csv.
"""
from numpy import random as r
from collections import Counter
import csv
"""
Defining classes for later use; add more classes and functions here in the futur... |
bbd5c587cc5043e1b272d9bd7402575040c1a355 | dangvinh1406/FamilyTree | /core/FamilyTree.py | 3,045 | 3.546875 | 4 | from core.Person import *
import copy
class FamilyTree:
def __init__(self, idf, familyName):
self.__idFamily = idf
self.__familyName = familyName
self.__tree = {}
def lookupPerson(self, idp):
return copy.deepcopy(self.__tree[idp])
def addPerson(self, idp, name, year, gender):
person = Perso... |
71a3880433bb1cbd5106b4653301c116c083ba28 | magentawitch/dnd | /cuenta.py | 1,188 | 3.5 | 4 | class Cuenta:
def __init__(self):
self.saldo = 0
def consultar(self):
return self.saldo
def depositar(self, monto):
self.saldo += monto
def retirar(self, monto):
if monto <= self.saldo:
self.saldo -= monto
else:
raise Exception ("No tene... |
1e428783742398fdecff03b0c55f2399772d69a3 | zaino1234/Python | /CursoemVídeo/ex003.py | 108 | 3.765625 | 4 | n1=int(input('digite um número'))
n2=int(input('digite mais um número'))
s=n1 + n2
print('A soma vale',s)
|
a9c7b34d3e5695b923c01fc5f95b8025310f1bf1 | zaino1234/Python | /CursoemVídeo/ex075Análise de dados em uma Tupla.py | 452 | 4.09375 | 4 | tupla = (int(input('Digite um valor: ')),
int(input('Digite um valor: ')),
int(input('Digite um valor: ')),
int(input('Digite um valor: ')))
print(f'Você digitou: {tupla}')
print(f'O número 9 apareceu {tupla.count(9)} vezes')
if 3 in tupla:
print(f'O primeiro valor 3 apareceu na {tupla.in... |
c90b62eb74d16593234a17be581f1e468ac3da21 | zaino1234/Python | /CursoemVídeo/ex076Lista de Preços com Tupla.py | 417 | 3.578125 | 4 | produtos_preco = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.90, 'Estojo', 25,
'Transferidor', 4, 'Compasso', 9.99, 'Mochila', 120.32, 'Livro', 34.90)
print('-'*45)
print(f'{"LISTAGEM DE PREÇOS":^45}')
print('-'*45)
for a in range(0, len(produtos_preco)):
if a % 2 == 0:
print(f'{produtos_... |
e13386a9cc8be26316f13726a7aa3ea3e271cbf2 | kirill0206/python | /hw01_normal.py | 3,366 | 3.859375 | 4 |
__author__ = 'Aristarkhov Kirill Viktorovich'
# Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа.
# Например, дается x = 58375.
# Нужно вывести максимальную цифру в данном числе, т.е. 8.
# Подразумевается, что мы не знаем это число заранее.
# Число приходит в виде целого беззнакового.
... |
3b19d0ce8a362b2148a39d6e4781d9938bd8fa47 | noobcoderr/my_leetcode | /leetcode7.py | 565 | 3.578125 | 4 | class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
abs_x = str_x = list_x = result = 0
if x < 0:
abs_x = abs(x)
else:
abs_x = x
str_x = str(abs_x)
list_x = list(str_x)
list_x.reverse()
... |
44a11515c82efd3d9c9fce2ea52ab8ccb6e02d08 | awsserver/awsserver | /python/keywords/continue.py | 211 | 4.125 | 4 | for letter in 'python':
if letter == 'n':
continue
print "Current Letter", letter
var = 10
while var > 0:
var = var -1
if var == 5:
continue
print "Current Variable value :", var
print "Good bye"
|
47193fe6c97eb7f37aa859b78f3b4adcfe17d068 | awsserver/awsserver | /python/ex29.py | 620 | 4.0625 | 4 | #!/usr/bin/python
people = int(raw_input("Enter The number of People:- "))
cats = int(raw_input("Enter The number of cats:- "))
dogs = int(raw_input("Enter The number of dogs:- "))
if int(people) < int(cats):
print "Too Many cats! The world is doomed!"
if int(people) > int(cats):
print "Not many cats! The world i... |
2bd95d1d8d10eaa5bb361410372b78c7f97d8e4f | awsserver/awsserver | /python/ex30.py | 631 | 4.1875 | 4 | #!/usr/bin/python
people = int(raw_input("Enter the People Value:- "))
cars = int(raw_input("Enter the Cars Value:- "))
trucks = int(raw_input("Enter the Truck Value:- "))
if cars > people:
print "We should take the cars.Becasuei cars %d greter the people %d" % (cars, people)
elif cars < people:
print "We should not... |
df1caf49fd2df480997be58a72ad571cd543b252 | PacktPublishing/Python-for-the-.NET-Developer | /Ch03/03_03_Loops/Begin/Python_VSC/Ch3/Program.py | 1,479 | 4.25 | 4 |
def demo_if():
testGrade = 95
# Ex: if
if testGrade>85:
print("You did good!")
else:
print("You did not work hard!")
# Ex: elif
if testGrade > 94:
print("You did awesome!")
elif testGrade > 85:
print("You did good!")
else:
print("You did no... |
1fe1f827c9766cee56b867c253ab9eed13b643b2 | sangeeth98/AIWPlab | /Assignment_1/question5.py | 231 | 4.3125 | 4 | import math
radius = float(input("Enter Radius r = "))
pi = math.pi
diameter = 2*radius
circumference = 2*pi*radius
area = pi*radius*radius
print("Diameter = %.2f\nCircumference = %.2f\nArea = %.2f"%(diameter,circumference,area))
|
273bc164a0ef058ab524f7466474b570d4fe6f5d | BobNextDoor/pyTest | /dirTest/ls.py | 233 | 3.59375 | 4 | import sys
def list(dirName):
import os
for childDir in os.listdir(dirName):
childDirPath = os.path.join(dirName,childDir)
if os.path.isdir(childDirPath):
list(childDirPath)
else:
print(childDirPath)
list(sys.argv[1])
|
883f122f4d04ebf2e71ddf57265a11b6614ca004 | kueller/bellamybot | /boteval.py | 5,574 | 3.546875 | 4 | import shlex
import operator
from functools import reduce
# A sort of mini Lisp interpreter type that can be used.
class BotEval:
def __init__(self):
self.functions = {
'+': self.add,
'-': self.sub,
'*': self.mult,
'/': self.div,
'if': self.if_c... |
17ca43f396e11b34eba0ddb905239f7dd3480dac | ben-dasilva/lc-solutions | /lcpy/30dc-0420/c_04_01_20.py | 420 | 3.5625 | 4 | from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
oddOne = 0
for n in nums:
oddOne ^= n
return oddOne
print(f'Result: {Solution().singleNumber([1, 2, 5, 3, 2, 1, 3])}')
print(f'Result: {Solution().singleNumber([2, 2, 1])}')
print(f'Result:... |
c3c41527404d933e9790aebc53064a9110298a6f | ben-dasilva/lc-solutions | /lcpy/30dc-0420/c_04_09_20.py | 1,594 | 3.625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
"""Given two strings S and T, return if they are equal when both are
typed into empty text editors. A '#' means a backspace character."""
sp, tp = len(S) - 1, len(T) - 1
sb, tb = 0, 0
while sp >= 0 or tp >= ... |
33d2e8cd09c95554a2b0954898c8c44a4a71c33d | ben-dasilva/lc-solutions | /lcpy/30dc-0420/c_04_13_20.py | 998 | 3.796875 | 4 | from typing import List
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
"""Given a binary array, find the maximum length of a contiguous subarray
with equal number of 0 and 1."""
longest = 0
count = 0
start = {0: -1}
for i, bit in enumerate(nums)... |
9237328282b98ad33f7cf986e8b6466af8c28caa | ben-dasilva/lc-solutions | /lcpy/30dc-0520/c_05_11_20.py | 1,336 | 3.59375 | 4 | from typing import List
import collections
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
original = image[sr][sc]
if original == newColor:
return image
else:
image[sr][sc] = newColor
l_r, l... |
ef2a21ef84cfd4b6af86f7c3e0c00afb598576b4 | ben-dasilva/lc-solutions | /lcpy/30dc-0420/c_04_17_20.py | 1,977 | 3.90625 | 4 | from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""Given a 2d grid map of '1's (land) and '0's (water), count the
number of islands. An island is surrounded by water and is formed
by connecting adjacent lands horizontally or vertically. You may
... |
eb23888cf65c1f17b48d31bffd400008e87449dc | ben-dasilva/lc-solutions | /lcpy/30dc-0520/c_05_09_20.py | 776 | 3.609375 | 4 | class Solution:
def isPerfectSquare(self, num: int) -> bool:
guess = (num+1) // 2
last = guess
while True:
product = guess * guess
if product == num:
return True
guess = (guess + num/guess + 1) // 2
if guess == last:
... |
6131b02e0629f38b6d605c3743842ccb1f4082d7 | jjolbo/crawling_practice | /Day1/ex03.py | 351 | 3.640625 | 4 | cars = 100
people_int_a_car = 4
drivers = 30
passengers = 90
cars_not_drive = cars - drivers
cars_driven = drivers
space_in_a_car = cars - passengers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print(cars)
print(drivers)
print(passengers)
print(passengers)
pri... |
43d48df86978d6253e0ac2e6b6342234cd458607 | jjolbo/crawling_practice | /Day2/if.py | 438 | 3.765625 | 4 | people = 20
cats = 30
dogs = 15
if people < cats:
print('cat')
if people > cats:
print('cat 적당')
if people < dogs:
print('세상에 침이 젖고 있어요')
if people > dogs:
print('건조한 세상이군요 ')
dogs - dogs + 5
if people >= dogs:
print('사람은 개보다 많거나 같아요')
if people <= dogs:
print('사람은 개보다 적거나 많아요')
else:
pr... |
944bdb839cef700475b9e10629abdcd98cb20deb | trorter/Test2_oy | /test/test_6.py | 426 | 3.609375 | 4 | import random
total = 0.0
count = 0
for i in range(1000000):
randprice = random.randint(0, 100)
randdeel = random.randint(0, 100)
#print(randprice)
#print(randdeel)
#print("=====")
if randdeel >= randprice:
sumdeal = (randprice * float(1.5)) - randdeel
total = total + sumdeal
... |
4e6ff78d4a638e34e20bc35524568bd0386db0c1 | madhu-ravuri/Coding-Dojo | /PythonStack/Python/Fundamentals/functions_basic2.py | 815 | 3.71875 | 4 | def countdown(num):
countList = []
for i in range(num, -1, -1):
countList.append(i)
return countList
def printAndRet(list):
print(list[0])
return list[1]
numList = [2, 4]
print(printAndRet(numList))
def firstLength(list):
sum = list[0] + len(list)
return sum
nums = [1,2... |
6e1febbc97e7157f983be585dfaf0fdc43de2eff | pohily/www.hackerrank.com- | /organizingContainers.py | 467 | 3.609375 | 4 | def organizingContainers(container):
h = []
v = []
for i in container:
h.append(sum(i))
for i in range(len(container)):
tmp = 0
for j in container:
tmp += j[i]
v.append(tmp)
h.sort()
v.sort()
if v == h:
return 'Possible'
else:
r... |
0af9f1c9e6e37de1034a6e6c9bd5305491787c3d | pohily/www.hackerrank.com- | /getMinimumCost.py | 311 | 3.578125 | 4 | def getMinimumCost(k, c):
cost = sorted(c, reverse=True)
sur = 1
pay = 0
if k >= len(c):
return sum(c)
else:
while cost:
pay += sum(sur * cost[:k])
cost = cost[k:]
sur += 1
return pay
print(getMinimumCost(2, [2, 5, 6]))
|
929800d523c673f17d2c605f05244dac6d0324a5 | pohily/www.hackerrank.com- | /beautifulTriplets.py | 276 | 3.65625 | 4 | def beautifulTriplets(d, arr):
result = 0
for i in arr:
if i + d in arr and i + 2*d in arr:
result += 1
print(i, i+d, i+2*d)
return result
#print(beautifulTriplets(1, [2, 2, 3, 4, 5]))
print(beautifulTriplets(3, [1, 2, 4, 5, 7, 8, 10]))
|
0064f0c6cac4b044f0434fc464ddeb2a8a4dfd37 | douxing/dx-study | /leetcode/problems_213_house-robber-ii.py | 1,012 | 3.890625 | 4 | import unittest
class Solution(object):
def rob1(self, nums):
if not nums:
return 0
elif len(nums) == 1:
return nums[0]
# mid >= 1
mid = len(nums) // 2
return max(self.rob1(nums[:mid-1]) + nums[mid] + self.rob1(nums[mid+2:]),
self.rob... |
365326224a5db9fce2622ff96f20dd766581d388 | marcelovieiratecnologia/ImportClinicOdontomed | /lendoCSV.py | 2,428 | 3.515625 | 4 | import csv
from datetime import datetime
#
# usando pandas, porém tenho que instalar a biblioteca
# import pandas as pd
# print(pd.read_csv('clinica.csv', 'rb', encoding='latin-1'))
# arquivo = open('clinica.csv', 'r', encoding='latin-1')
# def lerArq(arquivo):
# linhas = arquivo.readlines()
# countLinha = 0
#... |
d90a246f284a1934efc7fe3a21c60e81f6e8e219 | Sajan491/MINI-PROJECT-COMP204 | /servernew.py | 4,724 | 3.640625 | 4 | #!/usr/bin/env python3
import socket
import sys
import threading
import time
from queue import Queue
all_connections = []
all_address = []
HOST = ""
PORT = 5072
queue = Queue()
# creating a socket to connect two computers
def create_socket():
try:
global s
s = socket.socket()
except:
... |
cde4eb969fa3e0caf2465b15fb61e576c6ef718d | rachelgittelman/highest-weight-path | /highest_weight_path.py | 4,113 | 3.546875 | 4 | '''This script will calculate the highest weight path in a directed acyclic graph. It will
implement it using either a set of dictionaires, or a matrix, or a node class. It will
assume that the nodes are already in topological order, but it will be possible to modify
this'''
'''an example file containing a DAG is giv... |
d9bb7be142ca88e3d52b8a7fff742bf082008bbf | Anirudh-Muthukumar/Python-Code | /paying off debt in a year.py | 329 | 3.671875 | 4 | balance=3329
annualInterestRate=0.2
monthlyInterestRate=annualInterestRate/12.0
payment=00.0
while balance:
for i in range(12):
payment=balance*monthlyInterestRate;
balance=balance-payment+((annualInterestRate/12.0)*(balance-payment))
payment+=10.0
print balance
print round(p... |
e8e83bce8ffa112d3773ec84257c96b6d588a6fb | Anirudh-Muthukumar/Python-Code | /alphabetical order words.py | 212 | 3.796875 | 4 | def alphabeticalOrder(word,Wordlist=None):
current=word[0]
for i in word:
if i>=current:
current=i
else:
return False
return True
|
805f129c4ac5a2e74090cc65d5eecb01c63ebc2e | Anirudh-Muthukumar/Python-Code | /merge sort.py | 705 | 3.890625 | 4 | def mergesort(l):
if len(l)<2:
return list(l)
else:
m=int(len(l)/2)
left=mergesort(l[:m])
right=mergesort(l[m:])
return merge(list(left),list(right))
def merge(left,right):
i,j=0,0
result=[]
while i<len(left) and j<len(right):
... |
fa9741a9bc93b44c7f866afedb3578b3a80c7123 | Anirudh-Muthukumar/Python-Code | /cubes of n fibo nos..py | 131 | 3.515625 | 4 | n=input()
cube=lambda a: a**3
l=[]
a,b=0,1
for _ in range(n):
sum=a+b
l.append(cube(a))
b,a=sum,b
print l
|
f3bdda9c2b53596412a42743f49b619eebf60fdb | Anirudh-Muthukumar/Python-Code | /Rabin Karp Algorithm.py | 723 | 3.703125 | 4 | def search(text, pattern, q):
d = 10
m = len(pattern)
n = len(text)
p = 0
t = 0
h = 1
i = 0
j = 0
for i in range(m-1):
h = (h*d) % q
# Calculate hash value for pattern and text
for i in range(m):
p = (d*p + ord(pattern[i])) % q
t = (d*t + ord(text[i]... |
31c502d3bca2cd57d2bd0bb56c6ed3dd26ee3470 | Anirudh-Muthukumar/Python-Code | /Print all Root to Leaf paths of a Binary Tree.py | 1,055 | 3.78125 | 4 | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def rootToLeafPath(root):
res = []
q = [(root, [root.val])]
while q:
node, path = q.pop(0)
if not node.left and not node.right: # leaf node
res += path,
... |
6f52d2a4f25bd805ce02cb0a23545ee4057087dc | Anirudh-Muthukumar/Python-Code | /first n prime nos.py | 240 | 3.703125 | 4 | n=input('Enter no. of primes to be found out :')
i=2
print 'First',n,'prime nos. are '
while n :
for j in range(2,i):
if i%j==0:
break
else:
print i
n-=1
i+=1
|
7a08f343b28bb4ec5cb62d7eec0ef7d31cf7e3b1 | Anirudh-Muthukumar/Python-Code | /Decimal to Binary.py | 207 | 3.765625 | 4 | def binary(x):
ans = ""
while x:
if x&1:
ans += '1'
else:
ans += '0'
x = x//2
return ans[::-1]
for i in range(8, 16):
print(binary(i)) |
a3320c7e155e5dc1519a4c0d5572cfb937f97ec8 | Anirudh-Muthukumar/Python-Code | /Print all nodes of a binary tree that do not have sibling.py | 1,124 | 3.8125 | 4 | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def noSibling(root):
res = []
q = [root]
while q:
node = q.pop(0)
if node.left and node.right: # node has two children
q.append(node.left)
q.append... |
3ae29b7420fd83b01dbbeca47b167614a8decd00 | Anirudh-Muthukumar/Python-Code | /Trie using Defaultdict.py | 1,112 | 3.96875 | 4 | import collections
class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.isWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
marker = self.root
for ch in word:
marke... |
01040af7d652b073f3f5e2aae3a27bab3423b3da | Anirudh-Muthukumar/Python-Code | /minimum payment.py | 526 | 3.828125 | 4 | balance=3329
monthlyPaymentRate=0.02
annualInterestRate=.2
payment=0.0
remaining=0.0
paid=0.0
for i in range(0,12):
payment=balance*monthlyPaymentRate
remaining=balance-payment+(annualInterestRate/12.0*(balance-payment))
balance=remaining
paid+=payment
print 'Month: '+str(i+1)
prin... |
0e686bfb0e647ce499957d39a1e8fcb825e12d22 | FlorianGD/adventofcode_2019 | /day07.py | 4,702 | 3.6875 | 4 | """AoC 2019 day 5: Sunny with a Chance of Asteroids"""
from pathlib import Path
from typing import List, Generator, Tuple
from collections import namedtuple
from itertools import permutations
Instruction = namedtuple("Instruction", "opcode mode1 mode2 mode3")
opcodes = {
99: "end",
1: "add",
2: "mul",
... |
a9a402cbd481be64c85618f5dc2d2ceb4156de8e | SurajKakde/Blockchain | /assignments/assignment2_Suraj.py | 691 | 4.3125 | 4 | # 1) Create a list of names and use a for loop to output the length of each name (len()).
name_list = ['john','Maylie','Dash','Navin']
for name in name_list:
print(name + ' ' + str(len(name)))
# 2) Add an if check inside the loop to only output names longer than 5 characters.
if len(name) > 5:
print('Na... |
0658c002cd9bef1b0c2ff9ca2f4abb3cb88ef4ff | MasumTech/FunProject-with-Python | /number_guessing_game.py | 500 | 4.09375 | 4 | from random import randint
random_num = randint(1,11)
user_num = int(input('Please enter your desired Number: '))
print(f'The Random Number was {random_num} and What you guessed is {user_num}')
if random_num == user_num:
print('Congratulations!!!!!!!!You won the game.')
elif random_num > user_num:
print('You... |
7cd1d084ed4f4352e362bcbbda07bb9221ff0b24 | sergiosacj/Practice | /CP/UVA/12250.py | 367 | 3.984375 | 4 | i = 0
while(1):
i+=1
n = input()
if(n == '#'):
break
print("Case " + str(i) + ": ", end="")
if(n == "HELLO"):
print("ENGLISH")
elif(n == "HOLA"):
print("SPANISH")
elif(n == "HALLO"):
print("GERMAN")
elif(n == "BONJOUR"):
print("FRENCH")
elif(n == "CIAO"):
print("ITALIAN")
elif(n == "ZDRAVSTVUJTE")... |
1e2cbd56b88756863258d4c8f05506611cfb47c0 | HigerSkill/Algorithms | /MST_algorithm.py | 1,937 | 3.71875 | 4 | class Graph(dict):
def __init__(self, nodes, edges):
for n in nodes:
self[n] = dict() # Множества для неповторяющихся элементов
if edges == None: # Если все вершины в графе не имеют связей
pass
else:
for e in edges:
self.add_edge(e)
d... |
55a880b671e111c825372d77d561c93d080745ec | zoctobere/Siren | /getDateFromDay.py | 472 | 3.765625 | 4 | from datetime import date, timedelta
def next_weekday(weekday):
# print('This is next_weekday of getDateFromDay.py')
days = {
'Monday': 0,
'Tuesday': 1,
'Wednesday': 2,
'Thursday': 3,
'Friday': 4,
'Saturday': 5,
'Sunday': 6
}
da... |
210c0105e237f1e0afe9ead7d9c3ea7b5f053344 | eevan7a9/playground-python3 | /statements.py | 551 | 4.15625 | 4 | number = 13
if number == 12:
print(f"you're number {number} is equal to 12")
else:
print(f"you're number {number} is not equal to 12")
player1_score = 420
player2_score = 320
if player1_score > player2_score:
print("player1 wins the game")
elif player1_score < player2_score:
print("player2 wins the g... |
88e22ef3eafe103c67945c5b156020943f53e05a | AllenZqy/VirusDB | /DenseAI/VirusDB/transformer/metrics.py | 2,484 | 3.8125 | 4 | """
BERT stands for Bidirectional Encoder Representations from Transformers.
It's a way of pre-training Transformer to model a language, described in
paper [BERT: Pre-training of Deep Bidirectional Transformers for
Language Understanding](https://arxiv.org/abs/1810.04805). A quote from it:
> BERT is designed to pre-t... |
e9d03f611886dea44cd25a5bd2dbb68a32dde9a0 | SenneW-Web/c9-python-getting-started | /9 - Handling multiple conditions/code_challenge.py | 933 | 3.96875 | 4 | # Ask a user their name
name = input("Enter your first name: ")
# If their first name starts with A or B
# tell them they go to room AB
eerste_letter1 = name[0:1]
if eerste_letter1.upper() in ('A', 'B'):
room = 'AB'
# IF their first name starts with C
elif eerste_letter1.upper() == ('C'):
room = 'C'
# tell t... |
788cfd19936346d85732c50c216eacf7a64da5e3 | iStanHua/python-demo | /gcd.py | 411 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
求二个数的最大公约数和最小公倍数
gcd.py
"""
# 最大公约数
def gcd(x, y):
if x > y:
(x, y) = (y, x)
for factor in range(x, 1, -1):
if x % factor == 0 and y % factor == 0:
return factor
return 1
# 最小公倍数
def lcm(x, y):
return x * y // gcd(x, y)
p... |
d29032aa3ae0a4d2fa0564e59de6976a8f65c426 | luismaia-git/Python-Websocket-server | /WebServer Python/ServidorTCP.py | 2,103 | 3.90625 | 4 | # Import socket module
from socket import *
# Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)
serverSocket = socket(AF_INET, SOCK_STREAM)
# Assign a port number
serverPort = 8888
# Bind the socket to server address and server port
serverSocket.bind(('', serverPort... |
c0ba86d499ca051d30bee625457436c6341189f6 | JoshuaOndieki/contacts | /models/phonebook.py | 3,289 | 3.9375 | 4 | from models.contact import Contact
class Contacts():
"""Contains and manages all contacts. This is a phonebook instance.
Args:
This class takes no arguments
Returns:
Returns nothing.
"""
def __init__(self):
self.data = {}
def add(self, firstname, surname, number):
... |
09e3917653eb6da1c6e488a8fb0ec844fde773a0 | 768446472/PokerGame | /PokerGameScoring/Simulate_game.py | 2,810 | 3.578125 | 4 | import random
import time
import paixing
number = int(input('请输入玩家人数:'))
# number = 4
A = ['♥', '♠', '♦', '♣']
B = ['3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2']
poker = []
pokers = []
pokername = []
n = 1
for i in A:
for j in B:
pokers.append((n, (i + j)))
n = n + 1
print("开始洗牌.... |
5ca217d740c7572a408b720e4f02703150fa6b6b | ostapstephan/BayesianML | /project4/project4.py | 9,418 | 3.78125 | 4 | # python 3
# Ostap Voynarovskiy
# Prof. Keene
# Project 4
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.io
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# from scipy.io import arff
'''
Part 1:
Re-do the plott... |
1872de3a851f3d92abf176e9c32c61a555dcc1ee | tmb14190/Poulation-Weighted-Daily-Temperature | /main_with_new_lat_lon.py | 6,848 | 3.515625 | 4 | '''
Created on 29 Jun 2021
@author: jackm
In this it was decided that Albany and Portland Maine are sensors far enough off that they deserve to be their own locations,
and we can simply eye ball using a map their long and lat. By my eye, these are roughly exactly 42.6526° N, 73.7562° W, and
43.6591° N, 70.256... |
a6415ac532ceb8f837cd0b88b023ac50563a437c | rutujamalusare/py_vsc | /fullname.py | 593 | 4.125 | 4 | #import string
#sentence = 'Python is one of the best programming languages.'
#formatted = string.capwords(sentence, sep = None)
#print(formatted)
#print(string.capwords("they're bill's friends from the UK"))
string = "this is a tEst String"
capitalized_string = string.capwords(string)
print(capitalized_string)
... |
290ab815f1e1204062bb7d87068010b5430f2de4 | rutujamalusare/py_vsc | /casefold_lower.py | 312 | 3.859375 | 4 | string="Enter Any String"
print(string.casefold())
print(string.lower())
string1="ENTER AnY sTring"
print(string1.casefold())
print(string1.lower())
string2="rUTuja@$*8~`"
print(string2.casefold())
print(string2.lower())
"""casefold and lower works same for characters and spefcial characters
in english"""
|
d3cbe233b4f5772b98c3e807d3e229d6027424a6 | rutujamalusare/py_vsc | /title.py | 291 | 3.640625 | 4 | """a="rutuja malusare".title()
print(a)
"""
"""print(a[0])
print(a[1])
print(a[2])
print(a[14])
"""
"""for x in a:
print(x)"""
a="cyber succes python 5"
print(a[0].capitalize())
for x in range (0,len(a)):
if a[x] ==" ":
letter = a[x+1]
print(letter.capitalize())
print(a)
|
c39a8de459b1f361ac6fca06257fef36c6906fac | rutujamalusare/py_vsc | /calculator.py | 590 | 4.15625 | 4 | no1= input("enter 1st number")
no2= input("enter 2nd number")
operation= input("enter operation to be performed")
if (operation ==sum):
sum = float(no1) + float(no2)
print('The sum of {0} and {1} is {2}'.format(no1, no2, sum))
else:
pass
#subtraction
sub = float(no1) - float(no2)
print('The subtraction of... |
ee19c068348cf5baf160bc538e0b598ea9b0162c | 759796385/pythonDemo | /main/regularExpression/ReDemo.py | 335 | 3.828125 | 4 | import re
# 正则字符串用r前缀,无需转移
s = r'ABC\-001'
rex = r'^\d{3}\-\d{3,8}$'
# 匹配成功返回match对象 ,否则返回None
if re.match(rex, '0101-12345'):
print('ok')
else:
print('no match')
#预编译正则
re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
re_telephone.match('010-12345').groups() |
4d2e365b03213fdc5494aabb84c9173df12fe1d2 | 759796385/pythonDemo | /main/oop/extendDemo.py | 1,737 | 3.6875 | 4 | # python支持多继承 需要啥父类 就在类括号里加上就行
# 对应提供继承方法的类 一般加上MixIn后缀
# 重写str方法 等同java的tostring
class Student(object):
def __init__(self, name):
self._name = name
def __str__(self):
return 'student name:%s' % self._name
print(Student('doudou'))
# 实现自定义迭代器 实现__iter__()方法:返回一个可迭代对象。 for循环会不断调用迭代对象的__nex... |
65712c9828aef5debbc9e4be7bf2792c73266b5c | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day03/demo07.py | 142 | 3.625 | 4 | """
while 计数
"""
# 循环3次
count = 0
while count < 3:
usd = eval(input("请输入美元:"))
print(usd * 6.9)
count += 1 |
a5dc20810d1199f03c1175c85279314249757ad8 | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day15/login.py | 1,662 | 3.71875 | 4 | """
注册登录模拟
"""
"""
mysql.py
pymysql 操作数据库基本流程演示
"""
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost',port=3306,user='root',password='584023982',database='Student',charset='utf8')
# 获取游标 (操作数据库,执行sql命令)
cur = db.cursor()
# 注册
def register():
name = input("用户名:")
password = input("密码:")
# 判断... |
f6a3c2c15f5ddaf0c69b096ab26335a97eaa8037 | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day06/tcp_server.py | 988 | 3.703125 | 4 | """
tcp_server.py tcp套接字服务端流程
重点代码
注意:功能性代码,注重流程和函数使用
"""
import socket
# 创建tcp套接字
sockfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定地址
sockfd.bind(('127.0.0.1',8888))
# 设置监听
sockfd.listen(5)
while True:
# 阻塞等待处理连接
print("Waiting for connect......")
try:
connfd, address = sockfd.acc... |
304190c3cb293923519bc03459a2f453ce248797 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day04/day03_exercise/exercise03.py | 954 | 4.125 | 4 | """
根据身高体重,参照BMI,返回身体状况
BMI:用体重千克数除以身高米的平方得出的数值
中国参考标准
体重过低 BMI<18.5
正常范围 18.5<=BMI<24
超重 24<=BMI<28
I度肥胖 28<=BMI<30
II度肥胖 30<=BMI<40
III度肥胖 BMI>=40.0
"""
while True:
height = float(input("请输入身高(m):"))
weight = float(input("请输入体重(kg):"))
BMI = weight / p... |
44de5397799aeaebf2a9c395b1f92a7470f1ce66 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day03/exercise07.py | 957 | 3.8125 | 4 | """
在控制台中获取一个整数
如果是偶数为变量state赋值"偶数",否则赋值"奇数"
在控制台录入一个年份
如果是闰年,给变量day赋值29,否则赋值28
"""
# 在控制台中获取一个整数
# 如果是偶数为变量state赋值"偶数",否则赋值"奇数"
number01 = eval(input("请输入一个整数:"))
# if number01 % 2 == 0:
# state = "偶数"
# else:
# state = "奇数"
state = "奇数" if number01 % 2 else "偶数"
print("{}".format(state))
# 在... |
9f05d990cfc1a5a74232968a15f06e877bb8a884 | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day03/exercise01.py | 1,601 | 3.75 | 4 | """
一段文字中有()[]{},编写一个接口程序去判断括号是否匹配正确
"""
from lstack import *
text = "The core (of) extensible" \
"programming [is] defining functions." \
"Python allows {mandatory [and]}" \
" optional (arguments,{keyword} " \
"arguments),and even arbitrary " \
"argument lists."
# 将验证条件提前定义好
parens =... |
78de12012d4f3ffbf4372a1353a6f2dbf42434a9 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day08/exercise03.py | 444 | 3.5 | 4 | """
定义一个根据成绩计算等级的函数
"""
def get_score_level(score):
"""
根据成绩计算等级
:param score:输入的成绩
:return: 返回等级
"""
if score > 100 or score < 0:
return "输入有误!"
if 90 <= score:
return "优秀"
if 80 <= score:
return "良好"
if 60 <= score:
return "及格"
return "不及格"... |
a3f05f3b164d4f5c8800153e459953239f50e452 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day03/exercise05.py | 415 | 3.984375 | 4 | """
在控制台中录入一个成绩,判断等级(优秀/良好/中等/及格/不及格/输入有误)
"""
score = eval(input("请输入您的成绩:"))
if 90 <= score <= 100:
print("优秀")
elif 80 <= score < 90:
print("良好")
elif 70 <= score < 80:
print("中等")
elif 60 <= score < 70:
print("良好")
elif 0 <= score < 60:
print("不及格")
else:
print("输入格式不对") |
d5b26737e29650a7491418df65d74399aa0afdd1 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day17/exercise01.py | 559 | 4.34375 | 4 | """
练习:定义生成器函数my_enumerate,将元组与索引合成一个元组
list01 = [3,4,55,6,7]
for item in enumerate(list01):
# (索引,元素)
print(item)
for index,element in enumerate(list01):
print(index,element)
"""
list01 = [3,4,55,6,7]
def my_enumerate(iterable_target):
# index = 0
# for item in iterable_target:
# yield (ind... |
5d45a74d92025ebf897de1a9b6fa3f72d33eef01 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day16/exercise04.py | 954 | 4.0625 | 4 | """
员工管理器记录多个员工
迭代员工管理器对象
"""
class Employee:
pass
class EmployeeManager:
def __init__(self):
self.__employees = []
def add_employee(self,employees):
self.__employees.append(employees)
def __iter__(self):
return EmployeeIterator(self.__employees)
class EmployeeIterator:
... |
519753c34a57c9a96e65b429b28cce6f77a103c0 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day08/exercise08.py | 205 | 3.609375 | 4 | """
统计一个函数的执行次数
"""
count = 0
def fun01():
global count
count += 1
fun01()
fun01()
fun01()
fun01()
fun01()
fun01()
fun01()
print("函数调用了{}次".format(count))
|
0b27329468be09f368df2c232d0f3d4771b418f5 | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day04/search.py | 481 | 3.828125 | 4 | """
二分查找训练
"""
# list_为有序数列,key为要查找的关键值,返回在key在数列中的索引号
def search(list_,key):
# 第一个数index,最后一个数index
low,high = 0,len(list_)-1
while low < high:
mid = (low + high) // 2
if list_[mid] < key:
low = mid + 1
elif list_[mid] > key:
high = mid - 1
else:
... |
c5bc7181fdba5447dc3374f26ddb8a9f3da5d091 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day15/exercise03.py | 526 | 3.890625 | 4 | """
定义函数,在控制台中获取成绩的函数
要求:如果异常,继续获取成绩,直到得到正确的成绩为止
成绩必须在0--100之间
"""
def get_score():
while True:
str_result = input("请输入成绩:")
try:
score = int(str_result)
except Exception:
print("输入的不是整数")
continue
if 0 <=score<=100:
ret... |
689872870c6534c7f533b6a337af80fd8d9ebf6e | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day06/day05_exercise/exercise03.py | 843 | 3.796875 | 4 | """
(2)在控制台中购买一注彩票
提示
"请输入第1个红球号码:"
"请输入第二个红球号码:"
"号码不在范围内"
"号码已经重复"
"请输入蓝球号码"
"""
# 6个1 -- 33范围内的不重复红球号码
list_ticket = []
while len(list_ticket) < 6:
number = eval(input("请输入第{}个红球号码:".format(len(list_ticket)+1)))
if number < 0 or number > 33:
print("号码不在... |
dc43c026e969825fb07eb8b78f5c2b723e0ca16b | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day03/exercise06.py | 565 | 3.984375 | 4 | """
在控制台中获取一个月份
打印天数,或者提示输入有误
1--3--5--7--8--10--12 31
4--6--9--11 30
2 28
"""
month = eval(input("请输入月份:"))
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
print("{}是31天".format(month))
elif month == 4 o... |
7767a97234a1d1844958ce722829062a5ab802a6 | Dython-sky/AID1908 | /study/1905/month01/code/Stage5/day17/demo03_tf.py | 447 | 3.890625 | 4 | """
demo03_tf.py tensorflow基础
"""
import tensorflow as tf
a = tf.constant([1.0,2.0],name='a')
b = tf.constant([2.0,3.0],name='b')
print(a)
print(b)
result = a + b
print(result)
result = tf.add(a,b,name='Add')
print(result)
# 使用tf.Session()运行计算图
sess = tf.Session()
r = sess.run(result)
print(r)
print(type(sess.run(a)))... |
5797bdb6f72ae89c6e91198f8cd160eb448bdda8 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day18/demo02.py | 487 | 3.71875 | 4 | """
外部嵌套作用域
"""
def fun01():
# 是fun01函数的局部作用域
# 也是fun02函数的外部嵌套作用域
a = 1
def fun02():
b = 2
# 可以访问外部嵌套作用域变量
# print(a)
# 不能修改外部嵌套作用域变量
# a = 2 #创建了fun02的局部变量
# print(a) # 2
nonlocal a # 声明外部嵌套作用域
a = 2
print(a)
fun02()
... |
394858a1a2b6982d4f6371f09ee009e35b14ea8f | Dython-sky/AID1908 | /study/1905/month01/code/Stage5/day08/demo04_dataframe.py | 1,072 | 3.765625 | 4 | """
demo04_dataframe.py DataFrame基本操作
"""
import pandas as pd
import numpy as np
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
# 列访问
print(df['one'])
print(df[['one', 'two']])
# 列添加
df['three'] = pd.Series([2,3,4,5],ind... |
c96b1661d73078dba81a6e6b5617ec59c1be41b6 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day16/exercise01.py | 349 | 4.1875 | 4 | """
练习:使用迭代器原理遍历元组
("铁扇公主","铁锤公主","扳手王子")
"""
tuple01 = ("铁扇公主","铁锤公主","扳手王子")
# for item in tuple01:
# print(item)
iterator = tuple01.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break |
c3ec11d9f0725a2c970b38128f3cdad803f5dd22 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day10/exercise02.py | 371 | 3.921875 | 4 | """
定义对象计数器
定义老婆类,创建3个老婆对象
"""
class Wife:
count = 0
@classmethod
def print_count(cls):
print(cls.count)
def __init__(self,name,age):
self.name = name
self.age = age
Wife.count += 1
w01 = Wife("如玉",25)
w02 = Wife("婉儿",23)
w03 = Wife("九儿",21)
Wife.print_count() |
c81505bc80cce3cf21afd7e8f052543dff03fcf1 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day07/day06_exercise/exercise02.py | 942 | 3.546875 | 4 | """
存储全国各个城市的景区与美食,在控制台中显示出来
北京:
景区:故宫,天安门,天坛
美食:烤鸭,炸酱面,豆汁,卤煮
四川:
九寨沟,峨眉山,春熙路
美食:火锅,串串香,兔头
"""
dict01 = {
"北京":
{
"景区": ["故宫", "天安门", "天坛"],
"美食": ["烤鸭", "炸酱面", "豆汁", "卤煮"]
},
"四川":
{
"景区":["九寨沟", "峨眉山", "春熙路"],
"美食":["火锅", ... |
6771f75cf91c68f2677c7c6ab0fd02aa97d48ef6 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day13/exercise02.py | 626 | 4.25 | 4 | """
定义父类
车(数据:速度,品牌)
定义子类
电动车(数据:电池容量,充电功率)
创建两个对象,画出内存图
"""
class Car:
def __init__(self,brand,speed):
self.brand = brand
self.speed = speed
class Electrocar(Car):
def __init__(self,brand,speed,battery_capacity,charging_power):
super().__init__(brand,speed)
... |
d0984a4a4b77f090c307041aafbe4b838abe5613 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day14/day13_exercise/exercise01.py | 1,479 | 4 | 4 | """
定义员工管理器
1.管理所有员工
2.计算所有员工工资
员工
程序员:底薪+项目分红
销售:底薪+销售额*0.05
要求:增加新岗位,员工管理器不变
"""
class EmployeeManager:
def __init__(self):
self.__employees = []
def add_employee(self,emp):
self.__employees.append(emp)
def get_total_salary(self):
total_s... |
0ca89847156221519aca4292089c893c26a541d1 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day06/demo01.py | 472 | 3.78125 | 4 | """
列表推导式
"""
# list01中的元素,增加1后存入list02列表中
list01 = [5, 56, 6, 7, 7, 18, 19]
# list02 = []
# for item in list01:
# list02.append(item+1)
# print(list02)
# list02 = [item + 1 for item in list01]
# print(list02)
# list01中大于10的元素,增加1后存入list02列表中
# for item in list01:
# if item > 10:
# list02.append(ite... |
1ffbec71c87e095d441d9d8d675993f6aea31238 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day18/exercise03.py | 1,479 | 3.78125 | 4 | """
内置高阶函数
练习:内置高阶函数
1.([1,1,1],[2,2],[3,3,3,3])
获取元组中,列表长度最大的列表
2.根据敌人列表,获取所有敌人的姓名、血量、攻击力
3.在敌人列表中获取攻击力大于100的所有活人
4.根据防御力对敌人列表进行降序排序
"""
from common.list_helper import *
class Enemy:
def __init__(self,name,hp,atk,defense):
self.name = name
self.hp = hp
self.atk =... |
0ad2873d91c66bde219b413eff8c5d07e4ea3de1 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day17/exercise04.py | 1,988 | 3.5625 | 4 | """
参照day10/exercise02.py
完成练习
"""
class SkillData:
def __init__(self,id,name,atk_ratio,duration):
self.id = id
self.name = name
self.atk_ratio = atk_ratio
self.duration = duration
def __str__(self):
return "技能数据是:{},{},{},{}".format(self.id,self.name,self.atk_rat... |
717d31469e5a1230486009f719da5acb896cfef5 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/review_month01/demo05.py | 423 | 4.03125 | 4 | # 解释器会将方法定义到方法区(存储一份),连同默认参数一起创建
# 所以不指定参数时,使用的就是那一份列表对象
# 总结,默认参数,不要使用可变对象
def fun01(x,list_target = []):
print(id(list_target))
for index in range(x):
list_target.append(index)
print(list_target)
fun01(3) # [0,1,2]
fun01(3) # [0,1,2,0,1,2]
list01 = []
fun01(3,list01) |
d0f7c67a8ba8d2e7f4222459d6d60dbb2a10784d | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day02/sstack.py | 1,075 | 3.90625 | 4 | """
sstack.py 栈模型的顺序存储
重点代码
思路总结:
1.列表即顺序存储,但功能多,不符合栈的模型特征
2.利用列表,将其封装,提供接口方法
"""
# 自定义异常类
class StackError(Exception):
pass
# 顺序栈类
class SStack:
def __init__(self):
# 空列表就是栈的存储空间
# 列表的最后一个元素作为栈顶
self._elements = []
# 判断列表是否为空
def is_empty(self):
return self._elements =... |
a46350b8545988cec01b0db76a5cb3460a73c748 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day19/exercise01.py | 466 | 3.84375 | 4 | """
练习:再不改变原有功能(存取钱)的定义与调用情况下
增加验证账号的功能
"""
# 验证账号
def verify_account(func):
def wrapper(*args,**kwargs):
print("验证账号")
return func(*args,**kwargs)
return wrapper
@verify_account
def deposit(money):
print("存了{}钱".format(money))
@verify_account
def withdraw(login_id,pwd):
print("取... |
cc34680ffe5575714c4ae868fb463877e80089b7 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day04/day03_exercise/exercise02.py | 1,071 | 4.15625 | 4 | """
在控制台中获取年龄
如果小于0岁就打印输入错误
如果一个人的年龄小于2岁,就打印一条消息,指出他是婴儿
如果一个人的年龄为2(含)~13岁,就打印一条消息,指出他是儿童
如果一个人的年龄为13(含)~20岁,就打印一条消息,指出他是青少年
如果一个人的年龄为20(含)~65岁,就打印一条消息,指出他是成年人
如果一个人分年龄超过65(含)~150岁,就打印一条消息,指出他是老年人
150岁以上,打印"那不可能"
"""
while True:
age = eval(input("请输入年龄:"))
if age < 0:
prin... |
dabba5339d5a9e10d8d6ac85c8c162d2b4245fb8 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day04/exercise08.py | 240 | 3.765625 | 4 | """
累加10-50之间个位不是2,5,9的整数
"""
sum_value = 0
for item in range(10, 51):
unit = item % 10
# 个位是2,5,9的整数则跳过
if unit == 2 or unit == 5 or unit == 9:
continue
sum_value += item
|
517c6a7f8c867f2b318e89ed651ec1a4c9c17b7d | Dython-sky/AID1908 | /study/1905/month01/code/Stage5/day17/ann_classification.py | 2,187 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as mp
class ANNModel():
def __init__(self):
# 随机初始化权重[-1 1)
self.w0 = 2 * np.random.random((2, 4)) - 1
self.w1 = 2 * np.random.random((4, 1)) - 1
self.lrate = 0.1
# sigmiod 函数
def active(self, x):
return 1 / (1 + np.exp(-x... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.