text stringlengths 37 1.41M |
|---|
heads = int(input("Enter Heads: "))
legs = int(input("Enter Legs: "))
chicken = 0;
rabbit = 0;
for a in range(0,(heads)) :
b = heads - a
x = (a*2)+(b*4)
if x == legs:
chicken = a;
rabbit = b;
print("Chickens: "+str(chicken)+" , Rabbits: "+str(rabbit)) |
import random
def number_wang():
answer = random.randint(1,10)
guesses = 0
while True:
guess = int(input("What is your number, scrub?: "))
guesses += 1
if guess == answer:
print ("Yup, that's it alright.")
break
else:
if guess < answer:
... |
# this file contain features function that we'll be used to put features in the right
# format for the machine learning algorithms to work
from basic_ml import *
import sys
sys.path.append('..')
from basic import *
#TODO: simplify the 3 lines of code that append to the feat name list
# valid values for some attribu... |
#!/usr/bin/python3.4
# python file to make test related to the files given to me
from insertion import *
# constants
# maximum number of values a column possess
MAX_DIFF_VALUES = 100000
def study_row(row, index, diff_values):
"""
analyses if the column with given index in the row passed presents a value
... |
'''18. Faça um Programa para um caixa eletrônico. O programa deverá
perguntar ao usuário a valor do saque e depois informar quantas notas de
cada valor serão fornecidas. As notas disponíveis serão as de 1, 5, 10, 50 e
100 reais. O valor mínimo é de 10 reais e o máximo de 600 reais. O
programa não deve se preocupar ... |
'''21. Faça um programa que faça 5 perguntas para uma pessoa sobre um
crime. As perguntas são:
"Telefonou para a vítima?"
"Esteve no local do crime?"
"Mora perto da vítima?"
"Devia para a vítima?"
"Já trabalhou com a vítima?" O programa deve no final emitir uma
classificação sobre a participação da pessoa no cri... |
# Ex.31 Python Progressivo
# O Sr. Manoel Joaquim expandiu seus negócios para além dos negócios de 1,99 e agora possui
# uma loja de conveniências. Faça um programa que implemente uma caixa registradora rudimentar. O programa deverá
# receber um número desconhecido de valores referentes aos preços das mercadorias. U... |
# Exercicio 1 de Funções
# Escreva um script que pergunta ao usuário se ele deseja converter uma temperatura de grau
# Celsius para Farenheit ou vice-versa. Para cada opção, crie uma função. Crie uma terceira, que é um menu para o
# usuário escolher a opção desejada, onde esse menu chama a função de conversão corret... |
# Decorator concept practice
class Testing_decorator:
def __init__(self) -> None:
pass
def decorator(self,fun):
def dec():
print('Before function to be decorated')
fun()
print('After the function decorated')
return dec
def dec_fun():
... |
from _collections import deque
stack = deque()
# print(dir(stack))
stack.append('500')
stack.append('600')
# print("Stack : ", stack)
class Stack:
def __init__(self):
self.container = deque()
def push(self, value):
self.container.append(value)
def pop(self):
r... |
#TASK SEVEN: CLASSES AND ONJECTS
'''
1. Write a program that calculates and prints the value according
to the given formula:
Q = Square root of [(2*C*D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program
in a comma-separated sequence.
'''
impor... |
"""Q.1- Print anything you want on screen."""
print('Hello World') #String always writeen in double or single quotes
print(1) #The numeric value can be printed with or without double or single quotes
"""Q.2- Join two strings using '+'.E.g.-"Acad"+"View”"""
a = "Acad" #"Acad" is being assigned to variable a ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 31 16:55:59 2019
@author: user4
"""
# Importing required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing the dataset
df = pd.read_csv('Position_Salaries.csv')
X = df.iloc[:,1:2].values
y = df.iloc[:,2].values
# Creating a l... |
import sys
from functools import wraps
_caches = []
class _Cache(dict):
"""A dict() subclass that appends a self-reference to _caches"""
def __init__(self, *args, **kwargs):
super(_Cache, self).__init__(*args, **kwargs)
_caches.append(self)
def cache(*keys):
"""cache decorator
Caches input and output of a... |
"""Toosl dealing with time, such as timing a function and plotting a progress bar."""
import time as _time
import datetime as _datetime
import sys as _sys
class Progress(object):
"""Simple progress bar implementation"""
def __init__(self, message, number_of_iterations, output_period=1.0):
self._message... |
miles = float(input())
cost_per_gallon = float(input())
miles20 = 20 * (1.0 / miles) * cost_per_gallon
miles75 = 75 * (1.0 / miles) * cost_per_gallon
miles500 = 500 * (1.0 / miles) * cost_per_gallon
print('{:.2f} {:.2f} {:.2f}'.format(miles20, miles75, miles500))
|
# 获取元组的一些基本信息
tuple1 = (9, 1, -4, 3, 7, 11, 3)
print('tuple1的长度 =', len(tuple1))
print('tuple1里的最大值=', max(tuple1))
print('tuple1里的最小值 =', min(tuple1))
print('tuple1里3这个元素一共出现了{}次'.format(tuple1.count(3)))
# 元组的改变????
# tuple2 = ('a', 'c', 'd')
#
# tuple2[1] = 2
# 元组翻转 ??
# tuple3 = (1, 2, 3)
# tuple3.reve... |
# import pickle
#
#
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def sayhi(self):
print("Hi, my name is {}, and I'm {}".format(
self.name, self.age
))
#
#
# p1 = People(name='Jack', age=30)
# f = open('p1', 'wb')
# pickle.dump(p1, f)... |
a = [1, 2, 3, 4]
# def f(x, y):
# return x + y
# print([item for item in map(lambda x: x * x, a)])
# from functools import reduce
#
#
# a = reduce(lambda x, y: x + y, a)
#
# print(a)
# a = filter(lambda x: x % 2 == 1, a)
#
# print([item for item in filter(lambda x: x % 2 == 1, a)])
#
print([item for item in... |
# a = [1, 2, 3, 4]
#
# print(max(a))
def demo():
print('hello world')
print('demo')
def demo1(a, b):
print(a, b)
def sum(a, b):
return a + b
def my_max(a):
if not a:
return None
max_value = a[0]
for item in a:
if item > max_value:
max_value = item
retu... |
ghit = int(input("Enter Your Height(cm) ? "))
weight = int(input("Enter Your Weight(kg) ? "))
height = ghit / 100
BMI = weight / (height*height)
if BMI < 16 :
print("You are Severely underweight!")
elif 16 < BMI < 18.5 :
print("You are underweight!")
elif 18.5 < BMI < 25 :
print("You are normal!")
elif BM... |
numb_1 = int(input("Введите первое целое число: "))
numb_2 = int(input("Введите второе целое число: "))
if numb_1 != numb_2:
print("Числа не равны")
if numb_1 > numb_2:
print("Первое число больше второго")
elif numb_2 < numb_1:
print("Первое число меньше второго")
elif numb_1 == numb_2:
... |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
import json
import sys
# In[4]:
#Returns the team higher in the ladder and the difference in places between the pair.
def bestestTeam (teamIDs, standings):
homeName=""; awayName=""; #Clunky, generate a team/ID lookup table to be imported into all bots.
ho... |
#!/usr/bin/env python3
#
# egg.py
# Egg timer program in Python.
# Does not employ using C executables exported functions
#
import time
import sys
import os
PATH_FILE = "/tmp/egg.data"
menu = """
1. Start Egg Timer
2. Elapsed Time
3. Time Remaining
4. Stop Egg Timer
Enter Choice: """
def get_menu_s... |
#!/usr/bin/env python3
# -*- config: utf-8 -*-
from tkinter import *
root = Tk()
text = Text(width=100, height=10)
text.pack(side=LEFT)
scroll = Scrollbar(command=text.yview)
scroll.pack(side=LEFT, fill=Y)
text.config(yscrollcommand=scroll.set)
root.mainloop()
|
# implementation of selection sort
# s is the array to be sorted
def selectionsort(s):
for i in range(len(s)):
min = i;
for j in range(i, len(s)):
if s[j] < s[min]:
min = j
s[i], s[min] = s[min], s[i]
return s
# driver code to test above
s = [10, ... |
slova=[]
s=input('Введите слово:')
while s:
slova.append(s)
s=input('Введите слово:')
with open ('freq.txt','r+',encoding='utf-8') as f:
t=f.readlines()
for slovo in slova:
x=0
for line in t:
c=0
for i in line:
if i=='|':
c+=1
... |
"""
Plot Bands of Satellite Imagery with EarthPy
==================================================================
Learn how to use the EarthPy ``plot_bands()`` function to quickly plot
raster bands for an image. ``Plot_bands()`` can be used to both
plot many bands with one command with custom titles and legends OR
t... |
"""
Calculate and Classify Normalized Difference Results with EarthPy
==================================================================
Learn how to calculate and classify normalized difference indices in Python using EarthPy.
This example shows how to calculate and classify the normalized difference vegetation
index... |
from math import *
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('请输入正确的年龄')
if x > 70:
return '你老了'
elif x > 30:
return '你成年了'
else:
return '小孩别闹'
# y = int(input('age'))
# print(my_abs(y))
def quadratic(a, b, c):
delta = b**2 - 4 * a * c
... |
# coding=utf-8
"""
Created on 2017-11-28
@author: Palesnow
功能:访问者模式
网址:https://yq.aliyun.com/articles/71075?utm_campaign=wenzhang&utm_medium=article&utm_source=QQ-qun&2017315&utm_content=m_13628
实例:药房业务系统
"""
# 药品类
class Medicine:
name = ""
price = 0.0
def __init__(self, name, price):
self.name... |
#导入库
import turtle
import random
p = turtle
#定义画圆函数
def drawCircle(x, y, c='red'):
p.pu() # 抬起画笔
p.goto(x, y) # 绘制圆的起始位置
p.pd() # 放下画笔
p.color(c) # 绘制c色圆环
p.circle(30, 360) #绘制圆:半径,角度
#绘制雪花
def snow(snow_count):
p.hideturtle()
p.speed(500)
p.pensize(2)
for i in range(snow_... |
def NextWordProbability(sampletext,word):
splited_memo = sample_memo.split()
counted = {}
for i in range(1,len(splited_memo)):
#finding the key in dict
this_word = splited_memo[i]
word_before = splited_memo[i-1]
if word_before == word:
if counted.ge... |
def membership():
'''
Function to register the user as a member
Takes in user input to determine which membership to register the user under
'''
user_membership=None #User has no membership yet
try:
if user_status=='new user':#if the user is a newly registered user
... |
from typing import List, Tuple
def get_numbers(input_filename: str) -> List[int]:
with open(input_filename, 'r') as f:
return [int(i) for i in f.readlines()]
def find_complements_to(n: int, into: List[int]) -> Tuple[int, int]:
while into:
f = into.pop()
try:
i = into.inde... |
import password
def test_password_is_valid_according_to_occurency_policy():
input = '1-3 a: abcde'
policy, pwd = input.split(': ')
assert password.validate_occurences(policy, pwd)
def test_password_is_invalid_according_to_occurency_policy():
input = '1-3 b: cdefg'
policy, pwd = input.split(': ')... |
# Name: Royer V. Zamudio
# UCID: rvz2
# Section: 003
# Programming Assignment 3: Simple HTTP Client and Server using TCP sockets
# Server
from socket import *
import datetime, time
import os.path
serverIP = "127.0.0.1"
serverPort = 12000
responseLen = 1000000
# Welcome client contact
# Create socket
serverSocket = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# basic data tye: string, byte, floating, integer, boolean(True/False), None
print("hello, world")
print(123e15)
print('I\'m "ok"')
print('\\\\ok')
print(r'\\\\ok')
print('''different
lines
ok?''')
print(r'''different
lines
ok?''')
print(3 > 2)
print(3 > 2... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import defaultdict
#type : list multidict
d=defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['a'].append(2)
d['b'].append(4)
print d
#type : set multidict
b=defaultdict(set)
b['a'].add(1)
b['a'].add(2)
b['a'].add(2) #set not same... |
#####################################################################
#
# ORIGINAL PROBLEM:
# Sum the digits of an integer N, printing out each summation until
# N is only one digit in length.
#
# For more information, see the original prompt at
# http://www.reddit.com/r/dailyprogra... |
#####################################################################
#
# ORIGINAL PROBLEM:
# Given an inclusive range of years, count the number of years with no repeated digits.
# BONUS: Count the number of years in the longest consecutive run of years with
# repeated digits and years wit... |
#####################################################################
#
# ORIGINAL PROBLEM:
# Given an N-valued coin that converts to 3 coins of values N/2,
# N/3 and N/4, calculate the number of 0-valued coins eventually
# received for that coin if all positive-valued coins are converted.
#
# ... |
#####################################################################
#
# ORIGINAL PROBLEM:
# Calculate the perimeter of a polygon, given that it has N sides
# and a circumradius of R (the distance between the center of the
# polygon to any of its vertices).
#
# For more information,... |
#####################################################################
#
# ORIGINAL PROBLEM:
# Write a program that prints out each step that McCarthy's function
# will perform for a given integer N.
#
# For more information, see the original prompt at
# http://www.reddit.com/r/daily... |
#define dictionaries to be stored in shelves
locations = {0: {"desc": "You are sitting in front of a computer learning Python",
"exits": {},
"namedExits": {}},
1: {"desc": "You are standing at the end of a road before a small brick building",
"exits": {... |
from bs4 import BeautifulSoup
import requests
import sys
import os
def show_lyrics():
artist = input("enter the name of the ARTIST : ")
artist = artist.lower().replace(" ","-")
track = input("enter the name of the TRACK : ")
track = track.lower().replace(" ","-")
url = 'http://www.metrolyrics.com/... |
# Launch the interactive pyspark shell
# $ pyspark
# Declare column variables
auctionid = 0
bid = 1
bidtime = 2
bidder = 3
bidderrate = 4
openbid = 5
price = 6
itemtype = 7
daystolive = 8
# Load the data
auctionRDD = sc.textFile("/headless/Desktop/next-level-python-big-data/spark-dev3600/data/auctiondata.csv").map(la... |
#!/usr/bin/env python
from datetime import datetime
from datetime import time
welcome_message = ""
def main():
global welcome_message
global request_heading
welcome_message = get_welcome_heading()
def get_welcome_heading():
name = "Joe"
today = datetime.now()
month ... |
import turtle
screen_width = 400
screen_hieght = 400
turtle.setup(screen_width, screen_hieght)
the_turtle = turtle.Turtle()
white = (255,255,255,)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
window = turtle.Screen()
turtle.colormode(255)
window.title("Turtle Graphics Screen")
print("Please en... |
# function explode(string, separator)
# Menghasilkan Array substring dengan memisahkan string oleh separator
# Contoh : explode("a.bc.d.efg.h", ".") -> ["a", "bc", "d", "efg", "h"]
def explode(string, separator):
# KAMUS LOKAL
# arr : list
# el : string
# char : string (1-character string)
# ALGOR... |
import random
guesses = 10
number = (random.randint(1, 100))
guess = None
print(f"The computer has generated a number, you have {guesses} guesses")
while guess != number:
valid = False
while not valid:
guess = input(f"Enter a whole number between 1 and 100. \n")
try:
guess = int(gu... |
digits = []
starting = 2**1000
print(starting)
while starting > 0:
digits.append(starting%10)
starting = starting//10
print(digits)
print(sum(digits))
|
from fractions import Fraction
# too slow
primes = {2: 3, 3: 5}
def gen_primes():
i = 2
yield i
while True:
if i in primes:
yield primes[i]
i = primes[i]
continue
is_prime = True
for k,v in primes.items():
if i % k == 0:
... |
# Coverts images with the JPG extension and saves them as PNG
# Takes 2 imputs from terminal
# 1. Folder Name of where the image is located
# 2. File name of the size that you want
# 3. File name of that you want to resize
# Terminal command example:
# python JPGtoPNGConverter.py FolderName\ fileName.jpg fileN... |
import matplotlib.pyplot as plt
class Circle(object):
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
def add_radius(self, r):
self.radius = self.radius + r
return self.radius
def draw_circle(self):
plt.gca().add_patch(plt.Circ... |
w1 = "Hello"
w2 = "World"
print(w1, w2)
w3 = "Hello World"
print(w3)
print("Hello" + "World")
list = [1, 2, 3, 4]
print(list) |
i = 1
while(i < 10):
print(i)
i += 1
# do - while
q = 1
w = 1
while (q < 10):
while (w < 10):
print("w = ", w)
w+=1
if (w == 8):
continue
q+=1
print("q = ", q) |
# Thomas Marshall
# SalesForce.py
# Purpose - This program builds a class that gets a person's ID number, name
# and list of sales made, set a person's name, add more sales to an individual, calculate
# a person's total sales, decide if an individual's quota was met, and compare the total
# sales of two sales ... |
from matplotlib import pyplot as plt
from matplotlib import style
x = [1,2,3,4,5,6]
y = [7,5,6,7,8,9]
x2 = [1,2,3,4,5,6]
y2 = [3,6,5,7,8,6]
#algoritma
style.use('dark _background')
plt.plot(x,y,label = 'LIne one')
plt.plot(x2,y2,label = 'LIne two')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('Simple Chart')... |
# raising and exception
def fun(level):
if level < 1 :
raise Exception(level)
return level
try :
# l = fun(5)
l = fun(-5)
print ("level : ",l)
except Exception as e:
print ("Error in level argument",e.args[0])
else :
print ("no exception caught")
finally :
print ("In finally block")
|
a = input("enter your first name:")
b = input("enter your surname:")
print (a,b)
|
# function return example
def sum (arg1,arg2):
total = arg1+arg2
print ("Inside the fun:",total)
return total
total = sum (10,20)
print ("outside the function :",total)
|
# Program to sort alphabetically the words form a paragraph provided by the user
my_str = "Hello this Is an Example With cased letters"
#my_str = input("Enter a paragraphs: ")
words = my_str.split()
words.sort()
print("The sorted words are:")
for word in words:
print(word)
|
# TODO: Convert the 'what' script to a 'normal' formula.
# TODO: Modify for practice.
# Add Function
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
# Subtract Function
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
# Multiply Function
def multiply(a, b):
print ... |
"""****************************************************************************
* File: RSA_key_generator.py
* Project: RSA Key, Generation and Decryption
* Author: Everest Brooks (everest1@umbc.edu)
RSA Key Generation
This program will generate RSA public and private keys. The program will
accept the desired modulus ... |
""" Write code that asks the user to provide a score for an exam as input, and checks what grade the score is
associated with. (Example: a score higher than 90 is an A.)"""
# gather input from the user
grade = int(input("enter a grade:\n"))
# checking my work to see if the proper data type is set which is confirmed s... |
class menuItem:
""" Represents a single menu item, that stores the item number, the description of the item and the prie of the item """
def __init__(self, itemNum, itemDescription, itemPrice):
"""
Creates a menu item using the constructor parameters
:param itemNum: Order number
... |
from collections import defaultdict
class Graph():
''' Defines a graph instance '''
def __init__(self, adj_list=defaultdict(list)):
self.amnt_vertices = len(adj_list.keys())
self.adj_list = adj_list
self.amnt_components = 0
def init_pajek_graph(self, filename):
''' Rea... |
""" This program display a triangle with rigth angle.
*
**
***
****
*****
******
*******
********
*********
"""
size = int(input("Enter the size of the triangle (> 1) \n"))
cpt = 1
print("Your rigth trinagle")
print("=======================")
while cpt <= size:
print(cpt*"*")
cpt += 1
|
# This program draw a square of certain side according the entered value by the user
#import signal
from turtle import *
side = int(input("Enter the side of the square :\n"))
color('blue')
width(5)
cpt = 1
while cpt <= 4:
forward(side)
left(90)
cpt += 1
# We can put the program on pause using signal.pause()
sto... |
#!/usr/bin/python3.6
#-*- coding:utf8 -*-
#This program draw multiple lines
from random import randrange
from tkinter import *
# Functions definitions
def drawline():
""" Function to draw a line. """
global x1, y1, x2, y2, color
canv.create_line(x1,y1,x2,y2,fill=color)
y1, y2 = y1 + 10, y2 -10
def change_color... |
import sys
class Library:
def __init__(self, list_of_books):
self.availablebooks = list_of_books
def displayAvailablebooks(self):
print("The books we have in our library are as follows:")
print("================================")
for book in self.availablebooks:
pr... |
# 从第一个非安全局面出发,根据规律往后找新的非安全局面,
# 直到查找范围到达了目标石头数,然后判断是否符合非安全局面
import time
import copy
# 对于先取者来说是否安全
def nim(n, m):
if n == m:
return True
# 保持n小于m
if n > m:
n = n + m
m = n - m
n = n - m
exist = [0]
recursion = 1
a = 0
b = 0
while a < n:
# find min which doesn't exist in the list
n_min = find_lack_... |
class Employee:
company = "Google"
def __init__(self, name, salary,subunit):
print("Emplpyee is created ")
self.name = name
self.salary = salary
self.subunit = subunit
def getdetails(self):
print(f"the name of employee is {self.name}")
print(f"the salary of ... |
a = 54 #global variable
def func1():
global a
print(f"print statement 1:{a}")
a=8 #local variable if global keyword is not used
print(f'print statement 2:{a}')
func1()
print(f'print statement 3:{a}')
|
myDict = {
"fast":"in quick manner",
"Kaif":"a coder",
"marks":{1,2,3},
"anotherdict":{'Kaif':'player'}
}
print(myDict['fast'])
print(myDict['Kaif'])
myDict['marks']=[22,44]
print(myDict['marks'])
print(myDict['anotherdict']['Kaif']) |
# a=34
# b="Kaif's" #use this if you have single quotes in your strings
# b='''Kaif"s i's''' #use this if you have single quotes in your strings
# print(a,b)
# # print(type(a))
# print(type(b))
# greeting = " Good morning "
# name = "Kaif bhai"
# print(type(name))
# conatenating the string
# c=greeting + name
# print(... |
fruits = ['banana','watermealon','grapes','mangoes']
for item in fruits:
print(item)
|
# def farh(cel):
# return (cel*(9/5))+32
# c=0
# f = farh(c)
# print("Farehenite temperature is" + str(f))
# print("hello", end=" ")
# print("hello", end=" ")
# print("hello", end=" ")
# print("hello", end=" ")
def natural_liter(n):
sum = 1
for i in range(n):
sum = sum + (i+1)
return su... |
a= [3,6,9,2,4,23,343,45,44,66]
# b=[]
# for item in a:
# if item%2==0:
# b.append(item)
# print(b)
b= [i for i in a if i%2==0]
print(b)
# set comperihenison
t = [1,2,3,4,1,4,3]
s= {i for i in t}
print(s)
|
# Add two numbers
# a = 4
# b=455
# print( "the sum of a and b",a+b)
# # Reminder when a is divided by b
# a=458
# b=15
# print("The remainder when a is divided by b is",a%b)
# # use comaprison operator
# a=45
# b=4
# print(a<b)
# average of two numbers
a = input("Enter the first number:")
# b = input("Enter the ... |
try:
a= int(input("Enter a number"))
c=1/a
print(c)
except ValueError as e:
print("Please enter the valid value")
print(e)
except ZeroDivisionError as e:
print("Make sure you are not dividing by zero")
print(e)
print('thanks for using this code')
|
# for i in range(1,8):
# print(i)
for i in range (10):
print(i)
else:
print("This is inside else of for")
|
class complex:
def __init__(self,r,i):
self.real = r
self.imaginary = i
def __add__(self,c):
return complex(self.real+c.real, self.imaginary+c.imaginary)
def __mul__(self,c):
mulReal = self.real*c.real - self.imaginary*c.imaginary
mulImg = self.real*c.imaginary ... |
#coding: utf-8
peso = float(input("Digite o peso do boxeador: "))
if (peso < 65):
print("Categoria Pena")
elif (peso >= 65 and peso < 72):
print("Categoria Leve")
elif (peso >= 72 and peso < 79):
print("Categoria Ligeiro")
elif (peso >= 79 and peso < 86):
print("Categoria Meio Médio")
elif (peso >= 86 and pes... |
#coding: utf-8
n = int(input("Digite um número inteiro: "))
total = 0.0
i = 0
while i < n:
valor = float(input("Digite um número real positivo: "))
if (valor > 0):
total += valor
i += 1
print("Total: {}").format(total)
|
planets = ["earth", "saturn", "jupiter", "mars", "pluto", "venus"]
# The first and second items (index zero and one)
first = planets[0:2]
# Third and fourth items (index two and three)
middle = planets[2:4]
# The last two items (index four and five)
last = planets[4:6]
print(planets)
print(first)
print... |
num = int(input("Enter a number: "))
if num % 3 == 0:
print ("The inputted integer is divisible by 3")
else:
print ("The inputted integer is not divisible by 3") |
import random
def read(file_path):
"""
This function is used to read file.
Convert file format into my data structure.
Each element in x list is a line in the file.
"""
x = []
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
# print(li... |
def reorderArrayWithEvenFirst(reorderedArray):
next_even, next_odd = 0, len(reorderedArray) - 1
while next_even < next_odd:
if reorderedArray[next_even] % 2 == 0:
next_even += 1
else:
reorderedArray[next_even], reorderedArray[next_odd] = reorderedArray[next_odd], reorder... |
def bouncing_balls(height, bounce, window):
bounce_count = 1
if float(height) <= 0 or float(bounce) >= 1 or float(bounce) <= 0 or float(window) >= float(height):
return -1
else:
while height > window:
height = height * bounce
if height > window:
bounc... |
def openOrSenior(data):
"""Senior members must be 55 years or older, handicap greater than 7."""
category = []
for member in data:
age = member[0]
handicap = member[1]
if age >= 55 and handicap > 7:
category.append("Senior")
else:
category.append("Open... |
def FirstFactorial(num):
factorial = 1
for i in range(1, num+1):
factorial *= i
return factorial
print(FirstFactorial(22)) |
#!/usr/bin/env python3
# -*- coding utf-8 -*-
#循环
names=['king','lin']
for name in names:
print(name)
#计算1-10的整数之和
sum=0
for x in [1,2,3,4,5,6,7,8,9,10]:
sum+=x
print(sum)
# range(5) = [0,5)
# range(5)生成的序列是从 0 开始小于 5 的整数
print(list(range(5)))
#1+2+...+100
sum=0
for x in range(101):
sum+=x
pr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 使用dict和set
############ dict #################################
# 1. dict 全称 dictionary,在其他语言中也称为 map, 键-值( key-value)
# 2. dict 可以用在需要高速查找的很多地方
# 3. 需要牢记的第一条就是 dict 的 key 必须是不可变对象
# 在 Python 中,字符串、整数等都是不可变的,因此,可以放心地作为 key。而 list 是可变的,就不能作为 key.
dict={'king':9... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
try:
print('try...')
r=10/0
print('result:',r)
except ZeroDivisionError as e:
print('except:',e)
finally:
print('finally...')
print('END')
#可以有多个except来捕获不同类型的错误:
try:
print('try...')
r=10/int('a')
print('result:',r)
except ValueError as e:
print... |
#encoding = utf-8
"""
@version:0.1
@author: jorian
@time: 2020/12/4 13:20
"""
def find_prime(num):
if num > 1: # 查看因子
for i in range(2, num):
if (num % i) == 0:
print(num, "is not prime numer")
print(i, "*", num//i, "=", num)
break
else... |
#encoding = utf-8
"""
@version:0.1
@author: jorian
@time: 2020/12/4 16:25
"""
def levenshtein_distance(first_word, second_word):
if len(first_word) < len(second_word):
return levenshtein_distance(second_word, first_world)
if len(second_word) == 0:
return len(first_word)
previous_row = rang... |
import random
def busqueda_binaria(lista, start, end, objetivo):
print(f"Buscando: {objetivo} entre {lista[start]} y {lista[end - 1]}")
if start > end:
return False
medio = (start + end) // 2
if lista[medio] == objetivo:
return True
elif lista[medio] < objetivo:
return... |
words = "It's thanksgiving day. It's my birthday, too!" # finding and replacing
print words.find("day")
new_string = words.replace("day", "month")
print words
x = [2, 54, -2, 7, 12, 98] # finding min and max values
print min(x)
print max(x)
y = ['hello', 2, 54, -2, 7, 12, 98, 'world'] ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.