text stringlengths 37 1.41M |
|---|
# Given the names and grades for each student in a Physics class of n students, store them in a nested list
# and print the name(s) of any student(s) having the second lowest grade.
# Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
# Input F... |
grid=[]
for i in range(3):
temp=[]
for j in range(3):
temp.append(" ")
grid.append(temp)
def win(grid,char):
# Horizontal
for i in range(3):
j=0
while( j!= 3 and grid[i][j]==char):
j=j+1
if(j==3):
return True
# for i in range(3):
... |
def resolve():
'''
code here
'''
N = int(input())
res = ''
while N >= 1:
N-=1
res += chr(ord('a') + N%26)
N //= 26
print(res[::-1])
if __name__ == "__main__":
resolve()
|
def getNome():
nome = input('Insira o nome: ')
return nome
def getSobrenome():
sobrenome = input('Insira o sobrenome: ')
return sobrenome
def getSalmens():
sal_mens = 0.0
while(not float(sal_mens)):
try:
sal_mens = float(input('Insira o salário mensal: '))
except:... |
class Funcionario:
def __init__(self):
print('Sistema do Funcionário: ')
self.nome_func = input("Nome do Funcionário: ")
self.sobrenome_func = input("Sobrenome do Funcionário: ")
self.sal_func = []
self.gasto_func = []
self.poupanca = []
def showName(self):
... |
print("Enter a name for the X player:")
name1= input()
print("\nEnter a name for the Y player e r:")
name2= input()
print("Game Start:")
a = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
print("---------")
for i in range(0,3):
print('\n|',a[i][0],a[i][1],a[i][2],'|')
print("\n---------")
prin... |
class employee:
count=0
def __init__(self,empid,empname,empsal):
self.empid=empid
self.empname=empname
self.empsal=empsal
employee.count=employee.count+1
def display(self):
print("the employee id is:",self.empid)
print("the employee name is:",self.empname)
... |
#Name: Ashok Surujdeo
#Email: Ashok.Surujdeo65@myhunter.cuny.edu
#Date: March 2, 2021
#This program runs: Snow Count
import matplotlib.pyplot as plt
import numpy as np
name = input("Enter file name: ")
ca = plt.imread(name)
countSnow = 0
t = 0.8
for i in range(ca.shape[0]):
for j in range(ca.shape[1]):
i... |
#Name: Ashok Surujdeo
#Email: Ashok.Surujdeo65@myhunter.cuny.edu
#Date: March 23, 2021
#This program runs: Dinosaurs
import pandas as pd
filename = input("Enter file name: ")
dino = pd.read_csv(filename)
print("There are", dino['Name'].count(),"dinosaur genera.")
print("The number of dinosaur genera in each period:"... |
#Name: Ashok Surujdeo
#Email: Ashok.Surujdeo65@myhunter.cuny.edu
#Date: February 23, 2021
#This program runs: Marginal Tax Rate
income = int(input("Enter taxable income: "))
if income < 0:
print("Error")
elif 0 <= income <= 9700:
print("Marginal tax rate: 10%")
elif 9701 <= income <= 39475:
print("Margina... |
#Name: Ashok Surujdeo
#Email: Ashok.Surujdeo65@myhunter.cuny.edu
#Date: March 2, 2021
#This program runs: Square Spiral
import turtle
alex = turtle.Turtle()
length = 25
for i in range(100):
alex.right(5)
length = length*1.02
for i in range(4):
alex.forward(length)
alex.right(90)
|
#Name: Ashok Surujdeo
#Email: Ashok.Surujdeo65@myhunter.cuny.edu
#Date: February 23, 2021
#This program runs: Turtle Spiral
stamps = int(input("Enter number of stamps the turtle will print: "))
import turtle
alex = turtle.Turtle()
alex.shape('arrow')
alex.color('cyan')
alex.penup()
steps = 10
for i in range (0, sta... |
"""
Given a tower of [number] disks, initially stacked in decreasing size on
one of three pegs.
The objective is to transfer the entire tower to one of the other pegs,
moving only one disk at a time and never moving a larger one onto a smaller.
"""
from __future__ import print_function
def tower_of_hanoi(num, source, ... |
from math import atan2 # for computing polar angle
from random import randint # for sorting and creating data pts
import shapely # for checking intersection
from matplotlib import pyplot as plt # for plotting
from shapely import geometry
class Line():
def __init__(self):
self.line_cor = []
# Ret... |
import turtle
import math
wn = turtle.Screen()
turtle.screensize(900,900,"black")
turtle.speed(0)
colors = ["sea green","yellow","blue","orange","green","gray"]
sun = turtle.Turtle()
Mercury = turtle.Turtle()
Venus = turtle.Turtle()
earth = turtle.Turtle()
Mars = turtle.Turtle()
Jupiter = turtle.Turtle()
Sa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 13:34:55 2019
@author: hans
"""
from bs4 import BeautifulSoup
import urllib3
import certifi
def body_texter(url):
"""
input url and return teh text of the body
"""
# create pool
c=urllib3.PoolManager(cert_reqs='CERT_REQUIRED... |
#!python3.6.1
# -*- coding: utf-8 -*-
# author: https://github.com/vinlinch
# 第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,
# 例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
#
# 北京
# 程序员
# 公务员
# 领导
# 牛比
# 牛逼
# 你娘
# 你妈
# love
# sex
# jiangge
from collections import Counter
import os
import re
def get_filte... |
import random #for random numbers
def createBoard(rows, columns):
if rows <= 0: # if user puts bad input
raise NameError("need to have more than zero rows")
return [["-"]*columns for i in range(rows)] #return 2d array with all '-'
def putBomb(board,row,column):
board[row][column] = "*"
#TODO change to named option... |
if hasattr(__builtins__, 'raw_input'): #input now works for both python2.7 and python3
input=raw_input #Much better than sys.stdin.readline()
def between(start, end):
return list(map(int, range(start, end + 1))) #returns list of numbers between start and end
# will eventually combine this with other between(... |
num = int(input('digite um numero: '))
for n in range(1, num + 1):
if num % n == 0:
print(n)
|
class Employee:
"""
Employee object to represent an employee
"""
def __init__(self, id=0, first_name='', manager_id=0, salary=0):
# Store any employees under this employee
self._employees = []
# Basic data model for an employee
self.id = id
self.first_name = first... |
# Distance from zero
def distance_from_zero(num):
if num[0] == '-' or num.isdigit():
if len(num.split(".")) > 1:
return abs(float(num))
return abs(int(num))
return "Nope"
num = input("Please enter a value: ")
print(distance_from_zero(num)) |
#Tipos de elementos que son iterables
iterCadena = iter('cadena')
iterLista = iter(['l', 'i', 's', 't', 'a'])
iterTupla = iter(('t','u','p','l','a'))
iterConjunto = iter({'c','o','n','j','u','n','t','o'})
iterDiccionario = iter({'d': 1,'i': 2,'c': 3,'c': 4,'i': 5,'o': 6,'n': 7,'a': 8,'r': 9,'i': 10,'o': 11,})
print(i... |
lista = [1, 2, 3]
lista.append('cuatro')
lista[1] = 'dos'
for item in lista:
print(item)
a = [2, 4, 6]
b = a # Se asigna la variable por referencia
print(id(a))
print(id(b))
c = [a, b] # Lista que contiene a las listas a y b
print(c)
a.append(8) # Agrega el mismo elemento a las listas `a` y `b` porque acceden... |
a = [10,30,40,50]
max = 0
for i in a:
if max <= i:
max=i
print(max) |
from datetime import date
from time import sleep
dates=[]
d1=date(2018,4,17)
d2=date(1995,11,17)
d3=date(1995,11,4)
dates.append(d1)
dates.append(d2)
dates.append(d3)
dates.sort()
sleep(5)
print(dates)
for d in dates:
print(d)
|
"""
Name: Daniel Gladkov
Date: 27/05/2020
"""
import pygame
pygame.init()
base_color = (255, 165, 0)
text_color = (255, 255, 255)
hovered_base_color = (255, 0, 0)
font = pygame.font.SysFont('Comic Sans MS', 40)
class Button:
"""
A class that represents a button
Attributes
... |
#BMI值#
try:
s, t = eval(input("请分别输入身高体重用逗号隔开:"))
if s > 100:
s /= 100
if t > 85:
t /= 2
BMI = t/ s** 2
a, b = "", ""
if BMI < 18.5:
a, b = "偏瘦", "偏瘦"
elif 18.5 <= BMI < 24:
a, b = "正常", "正常"
elif 24 <= BMI < 25:
a, b = "偏胖", "正常"
elif 25 <= BM... |
def simple_numbers(a):
'''На входе-натуральные числа от 0 до 1000.
Функция проверяет числа на простоту.
'''
if 0<a<=1000:
for i in range(2,a+1):
if a%i==0: break
return a==i
def vse_deliteli(a):
'''На входе-натуральные числа от 0 до 1000.
Возвращает список всех делит... |
# coding: utf-8
# # Preliminaries
import copy
import itertools
from collections import defaultdict
from operator import itemgetter
# #### Our dataset format
# An event is a list of strings.
# A sequence is a list of events.
# A dataset is a list of sequences.
# Thus, a dataset is a list of lists of lists of strings... |
import pandas as pd
import gmplot
from IPython.display import display
data = pd.read_excel('Locations.xlsx')
# latitude and longitude list
latitude_list = data['LATITUDE']
longitude_list = data['LONGITUDE']
# center co-ordinates of the map
gmap = gmplot.GoogleMapPlotter(00.00000,0.0000000,0)
# ... |
import re
phoneRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
resume = 'some random resume with lot of phone numbers'
phoneRegex.search(resume) # Return the first match
phoneRegex.findall(resume) # Return list of matches as string
lyrics = '12 drummers drumming, 11 pipes piping, 10 lords a leaping, 9 ladies dancing'... |
value = 0
def sum( val, index ) :
return val + index
for i in range(2) :
value = sum(value, i)
print(value)
|
# 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 serialize(self, root):
def _serialize(root, l= []):
if root:
l.append(root.val)
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
k = []
count = -1
def traversal(root):
global count
count+= 1
if len(k)==2:
return
if root == None:
traversal(root.left)
traversal(root.right)
if root.left.... |
from itertools import groupby
def insert():
pass
# def remove(l,c):
# [x for x in l if ]
def sol(board, hand):
groups = groupby(board)
result = [[label, sum(1 for _ in group)] for label, group in groups]
return result
board = "WRRBBW"
hand = "RB"
board = "WWRRBBWW"
k = sol(board, hand)
p... |
# https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/
grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
from collections import deque
info = {}
for i in range(len(grid)):
for j in range(len(grid[0])):
info[(i,j)] = False
def is_valid(grid, index):
if index[0]<0 or inde... |
def number_of_vowels(my_string):
vowels = ["a","e","i","o","u", "A", "E", "I", "O", "U"]
def reverse(my_string):
s = " "
for i in my_string[::-1]:
s+= i
return s
def reverse_order(my_string):
s = " "
for i in my_string.split(" ")[::-1]:
s+= i+" "
return s
def rotate(s1... |
from Graph import Graph
from collections import defaultdict, deque
def add_edge(graph, vertex_a, vertex_b):
graph[vertex_a].add(vertex_b)
graph[vertex_b].add(vertex_a)
def build_graph(board_size):
graph = defaultdict(set)
for row in range(board_size):
for col in range(board_size):
for to_row, to_col in leg... |
print("my_dictonarys")
run = 1
while run == 1:
a = input("Введите данные словаря:")
b = input("Введите данные второго словаря:")
def mergedicts(a, b):
for key in b:
if isinstance(a.get(key), dict) or isinstance(b.get(key), dict):
mergedicts(a[key], b[key])
... |
print("Простий калькулятор")
a = float(input("Введіть перше число: "))
b = float(input("Введіть друге число: "))
operation = input("ВВедіть необхідну операцію:")
result = None
if operation == "+":
result = a + b
elif operation == "-":
result = a - b
elif operation == "*":
result = a * b
elif operation == "/... |
class sausage():
## OK NOW I AM HUNGRY!!!
def __init__(self, mince = "pork!", volume = 1):
self.mince = mince
self.size = eval(str(volume)) * 12
if len(mince) > 12:
self.mince_str = mince[:12]
else:
self.mince_str = mince * (12 // len(mince)) + mince[:12 %... |
from math import *
func = input()
A, B = eval(input())
x = A
while abs(eval(func)) > 0.0000001:
x = (A + B) / 2
if eval(func) < 0:
A = x
else:
B = x
print(x)
|
# Score: 15/15
def partition(arr, low, high): # Partition function
i = low-1 # Index of smaller element
pivot = arr[high][0] # Pivot which will be moved to the correct spot
for j in range(low, high):
if arr[j][0] <= pivot: # If the value is smaller than the pivot
i = i+1 # Increments i... |
# -*- coding: utf-8 -*-
#import some dope
import sys
import os
import re
import time
from random import randrange
from itertools import repeat
numbers = {
'adam' :"+41111111111",
'bob' :"+41222222222",
'chris' :"+41333333333",
'dave' :"+41444444444",
}
print "Gespeicherte Empfänger: "
for name in numbers:
... |
# Class for each individual node within the Linked List
# you do not need to change this class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Class for the list structure itself
class LinkedList:
# This method will run when you create a new
# linked li... |
###############################################
#File Name: Simple_Calc.py
#Created By: Ard Aunario
#Date Created: 8/31/19
#Description: Simple calculator that does basic math operations
################################################
################################################
KeepGoing = True
Num = in... |
#!/usr/bin/env python
""" Demo-ing argparse. """
import argparse
parser = argparse.ArgumentParser(description='This is a sample program')
parser.add_argument("user", help="user")
parser.add_argument("age", help="age for the user", type=int)
parser.add_argument("-v", "--verbose", help="verbose mode", action="store_tru... |
# Escribe tus funciones abajo de esta línea
def pies_cm(pies):
piescm=pies*30.48
return piescm
def pulgadas_cm(pulgadas):
pulgadascm=pulgadas*2.54
return pulgadascm
def yardas_cm(yardas):
yardascm=yardas*91.44
return yardascm
def main():
print ('1. pies a cm, 2. pulgadas a cm, 3. yardas a cm... |
#!/usr/bin/python3
def island_perimeter(grid):
"""
The amazing Five tas The amazing Five tas
"""
water = 0
land = 1
perimeter = 0
for col, level in enumerate(grid):
for row, parcel in enumerate(level):
if parcel == land:
if row == 0 or gri... |
from datetime import datetime, timedelta
from itertools import cycle
def timestamp_to_str(value):
return value.strftime("%Y-%m-%dT%H:%M:%S.000Z")
_now1day = [timestamp_to_str(datetime.now() + timedelta(minutes=i)) for i in range(1, 2400, 25)]
print(_now1day)
now1day = cycle(_now1day)
print(next(now1day))
for i ... |
# -*- coding: utf-8 -*-
"""Balance Checker
This script allows the user to check if the braces in the given string are balanced
The braces could be (), {}, [] or any combination of these
This file contains the following function:
* main - the main function of the script
"""
import json
import logging.config
d... |
'''
Which starting number, under one million, produces the longest chain?
'''
MAX = 1000000
def get_next_num(n):
if n%2 == 0:
n = n/2
else:
n = 3*n + 1
return n
max_len = 0
max_num = 0
for num in range(2, MAX):
count = 0
i = num
print num
while i!=1:
i = get_nex... |
"""
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
MAX = 1000
def check(a,b):
TP = 5*(10**5)
lhs = 1000*(a+b)
rhs = a*b + TP
if lhs == rhs:
print a,b, 1000-a-b
print a*b*(1000-a-b)
return True
else:
return False
f... |
"""
Smallest positive integer divisible by all in (1, 20)
"""
from math import sqrt
primes = {}
for i in range(2,21):
k = int(sqrt(i)) + 1
flag = True
for j in range(2, k):
if i%j == 0:
flag = False
break
if flag:
primes[i] = 1
for i in range(4,20):
for p i... |
# Leap year
# def is_leap(year):
# leap = False
# if year%400==0:
# leap=True
# elif year%100 ==0:
# leap=False
# elif year%4==0:
# leap=True
# return leap
# year = int(input())
# print(is_leap(year))
#initial matrix
if __name__ == '__main__':
x = int(input())
y = in... |
filename = input("please type file name: ")
try:
fhand = open(filename)
count = dict()
for line in fhand:
words = line.split()
if len(words) == 0: continue
if words[0] != "From" : continue
if words[1] not in count:
count[words[1]] = 1
else:
count[words[1]] += 1
print(count)
except:
print("T... |
# counts lines in text document
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count) |
celsius = input('Enter Degrees Celsius')
fahrenheit = int(celsius)*9/5+32
print(fahrenheit) |
fhand = open("data/words.txt")
keys = dict()
for lines in fhand:
words = lines.split()
for word in words:
if word not in keys:
keys[word] = 1
else:
keys[word] += 1
print(keys)
|
import string
fname = input("Enter the file: ")
try:
fhand = open(fname)
except:
print("File cannot be opened: ", fname)
exit()
counts = dict()
for line in fhand:
line = line.rstrip()
line = line.translate(line.maketrans(" ", " ", string.punctuation))
line = line.lower()
words = line.split()
for word in wor... |
hours = int(input('Enter Hours'))
rate = input('Enter Pay')
if hours > 40:
regpay = hours * float(rate)
overtime = (0.5 * float(rate)) * (hours - 40)
pay = regpay + overtime
else:
pay = hours * float(rate)
print(pay) |
# a and b are aliased meaning the are referenced together
a = [1,2,3,4]
a = b
print(b[0])
# changes made in one affect the other
b = [17,2,3,4]
print(a) |
#Jen Anderson
#anderjen@onid.oregonstate.edu
#CS311-400
#Homework2
#Question4
import sys
import math
numOfPrimes = int(sys.argv[1])
primeArray = []
#This function returns 1 if x is prime and 0 if x is not prime
def isPrime(x):
if x == 2 or x == 3:
return int(1)
if x%2 == 0:
return int(0)
if x%3 == 0:
retur... |
def _append_points(main_list, sublist):
for item in sublist:
main_list.append(item)
class VertexPoints:
def __init__(self):
self.x = []
self.y = []
self.z = []
def add_point(self, x, y, z):
self.x.append(x)
self.y.append(y)
self.z.append(z)
def... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# author:milittle
# Given a test score, grade returns the corresponding letter grade.
import bisect
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
# i = bisect.bisect(breakpoints, score)
print(i)
return grades[i]
def main():
print([grade(score) ... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# author: milittle
# index.py uses dict.setdefault to fetch and update a list of word occur‐
# rences from the index in a single line Example 3-4.
import re
import collections
import sys
WORD_RE = re.compile('\w+')
def test():
index = collections.defaultdict(list) #用什么作为默... |
from pulp import *
from pandas import DataFrame, read_csv
import pandas as pd
# Reading the data file
file = r'diet.xls'
df = pd.read_excel(file, index = True, nrows=64)
#print(df.tail())
# Defining the LP
model = LpProblem("The Diet problem",LpMinimize)
# Setting up the problem
foods = df['Foods'].values
price... |
# Fibonacci Sequence or Number
# 0 1 1 2 3 5 8 13 21
def feb(n):
a =0
b =1
print(a)
print(b)
for i in range(2,n):
c = a + b
a = b
b = c
print(c)
feb(10)
|
# def add(x,y):
# a = x+y
# print(a)
# add(90,80)
def calculator(x,y):
c = x + y
return c
num1 = int(input("Enter Num1 ?"))
num2 = int(input("Enter Num2 ?"))
final = calculator(num1,num2)
print(final)
|
import string
# x =int(input("Enter Any Number? "))
# r = x % 2
# if r==0:
# print("This is an even number")
# if x > 5:
# print("This is even and also greater than 5")
# else:
# print("This is even less than 5")
# else:
# print("This is odd Number")
# user = "admin"
# if (user == "a... |
d = {1:[1,2],2:[2,4]}
grid = [[True, True, True, True, True, False],
[False, False, True, True, True, False],
[True, True, True, False, True, True],
[True, False, False, True, True, False],
[True, False, True, True, False, True],
[True, False, True, True, True, False]]
n = 1
defM = []
matrix = []... |
import pygame
pygame.init()
win = pygame.display.set_mode((500,540))
#properties for character
x = 250
y = 400
radius = 20
vel_x = 10
vel_y = 10
jump = False
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
r... |
numero1 = 0
numero2 = 0
resultado = 0
operacao = ''
numero1 = int(input("Digite o primeiro número:"))
operacao = input('Coloque a operação:')
numero2 = int(input("Digite o segundo número:"))
if operacao =='+':
resultado = numero1 + numero2
elif operacao =='-':
resultado = numero1 - numero2
elif o... |
from enum import Enum
class ChoiceEnum(Enum):
@classmethod
def choices(cls):
choices = list()
# Loop thru defined enums
for item in cls:
choices.append((item.value, item.name))
# return as tuple
return tuple(choices)
def __str__(self):
return... |
"""RGB Flashing Lights
## Overview
This excercise will show you how to flash the LED's of the board
rotating through three different colors; Red, Green, and Blue.
## Setup
In this excercise there's no need to configure the board with anything
besides coping `code.py` onto the CPE board.
"""
import time
from adafru... |
a, b, c = input().split()
a = float(a)
b = float(b)
c = float(c)
lista = [a, b, c]
lista.sort(reverse = True)
a = lista[0]
b = lista[1]
c = lista[2]
if (a >= b + c):
print("NAO FORMA TRIANGULO")
else:
if(a ** 2 == b ** 2 + c ** 2):
print("TRIANGULO RETANGULO")
if(a ** 2 > b ** 2 + c ** 2):
... |
aux = 0
n1 = int(input("Numero 1: "))
n2 = int(input("Numero 2: "))
n3 = int(input("Numero 3: "))
if (n1 > n2):
aux = n1
n1 = n2
n2 = aux
if (n1 > n3):
aux = n1
n1 = n3
n3 = aux
if (n2 < n1):
aux = n2
n2 = n1
n1 = aux
if (n2 > n3):
aux = n2
n2 = n3
n3 = aux
if (n... |
from random import *
numUser = int(input("Tente adivinhar o número (de 0 a 5) que o computador está pensando... "))
numComputer = randint(0, 5)
if numUser == numComputer:
print(f""""Quanta sorte!
Seu numero {numUser}, numero computador {numComputer}""")
else:
print(f"""Mais sorte da próxima vez!
Seu n... |
#funcao zip
lista1 = [1, 2, 3, 4, 5]
lista2 = ["Pão", "Ovo", "Leite", "Sabonete", "Amaciante"] #mesma quantidade de itens da lista1
lista3 = ["R$4,00", "R$10,00", "R$3,00", "R$1,00", "R$12,00"]
# o zip serve para concatenar (juntar) duas ou mais listas em uma só
for numero, nome, valor in zip(lista1, lista2, lista3):... |
'''
Criar uma classe Carro com no mínimo 3 propriedades e métodos.
'''
# Criando a calsse Carro
class Carro:
# Definindo o construtor e passando os parâmetros da classe
def __init__(self, marca, cor, combustivel, kmRodado):
self.marca = marca
self.cor = cor
self.combustive... |
#--- Exercício 4 - Funções
#--- Crie uma função que imprima um cabeçalho de acordo com uma variável de nome da empresa (passada por parametro)
#--- A impressão deve ocorrer via multiplicação de strings
#--- A multiplicação deve ser feita com base em uma variável que contenha o caracter a ser multiplicado
#--- Crie uma... |
#Funcao enumarate
lista = ["abacate", "bola", "cachorro"]
#com o enumarate
for i, item in enumerate(lista):
print(i, "-", item)
#sem o enumarate:
#for i in range(len(lista)):
# print(i, "-", lista[i]) |
import sqlite3
conn = sqlite3.connect('clientes.db')
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM clientes
WHERE id = ?;
""", [1])
print(cursor.fetchone())
cursor.execute("""
SELECT * FROM clientes
WHERE idade > ?;
""", [21])
print(cursor.fetchall())
cursor.execute("""
SELECT * FROM clientes
WHERE cida... |
# https://www.youtube.com/watch?v=RhtsCbKyYoA
# Classes deixa o programador utilizar variáveis 'locais' fora do escopo delas
# Boa prática: Nomes de classes com letras maiúsculas
class DidaticaTech():
def __init__(self, valorAntigo: int, valorNovo:int):
self.valorAntigo = valorAntigo
self.valorNo... |
preco = 0
distancia = int(input("Qual a distância da viagem? "))
if distancia <= 200:
preco = distancia * 0.50
else:
preco = distancia * 0.45
print("O preço é {:.2f}".format(preco)) |
#######################################################################################################
# Faça um programa que simule um lançamento de dados. Lance o dado 100 vezes e armazene os resultados em um vetor.
# Depois, mostre quantas vezes cada valor foi conseguido. Dica: use um vetor de contadores(1-6) e u... |
def cadastroPessoa():
nome = input("Digite o nome: ")
if(nome.isspace() or nome == ''):
while(nome.isspace() or nome == ''):
nome = input("Nome em branco. Digite novamente: ")
sobrenome = input("Digite o sobrenome: ")
if(sobrenome.isspace() or sobrenome == ''):
while(sobreno... |
frase = input("Digite a frase: ")
letra = input("Digite a letra que você deseja pesquisar: ")
print(f"A letra {letra} aparece {frase.count(letra)} vezes")
# Tem como pesquisar uma letra específica -> frase.count('u')
# Tem como pesquisar uma apenas um pedaço da frase -> frase.count('u', 0, 13)
# Uma outra função lega... |
metros = float(input("Entre com os metros: "))
print("{}km".format(metros/1000))
print("{}hm".format(metros/100))
print("{}dam".format(metros/10))
print("{}dm".format(metros*10))
print("{}cm".format(metros*100))
print("{}mm".format(metros*1000)) |
#######################################################################################################
# Faça um Programa que peça os 3 lados de um triângulo.
# O programa deverá informar se os valores podem ser um triângulo.
# Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escale... |
from random import randint
movimentos= 0
casa = 1
venceu = 0
jogada= 0
while venceu == 0:
if movimentos >= 6:
print("Você atingiu o limite de movimentos!")
break;
else:
while casa == 1 and movimentos <7:
print("Você esta na casa: ",casa)
print("Você ainda tem", 7-movimentos,"movimentos")
... |
# 题目:将一个列表的数据复制到另一个列表中。
list=[1,5,6,40]
m=list[:]
print(m) |
class Module:
def __init__(self, nom, voulumeHoraireTotal):
self.nom = nom
self.voulumeHoraireTotal = voulumeHoraireTotal
def ajouterModule (self, my_liste):
nom = input("\n Nom : \n")
voulumeHoraireTotal = input("\n voulume Horaire Total : \n")
... |
# source: https://cses.fi/problemset/task/1071
def find(y, x):
hightest = max(x, y)
lowest = min(x, y)
if ((y == hightest and y % 2 == 0) or (x == hightest and x % 2 != 0)):
return hightest ** 2 - lowest + 1
return hightest ** 2 - 2 * hightest + lowest + 1
n = int(input())
inputs = []
for i i... |
name = input("enter your name")
print(name)
a= """My name is Lekshmi
I work for IBS Software.
I am working in Traveldoo"""
print(a) |
thisset = {"apple", "banana", "cherry"}
print(thisset)
thisset = set(("apple", "banana", "cherry"))
print("banana" in thisset)
thisset.add("orange")
print(thisset)
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
thisset.pop()
print(thisset) |
# -*- coding = utf-8 -*-
# Author:ZhouShuyu
# @Time : 2021/8/19 15:10
# @File : p6_while_loop.py
'''
i = 0
while i< 5 :
print("当前是第%d次执行循环" %(i+1))
print("i=%d" %i)
i+=1
'''
#1-100求和
#我自己写的
i=0
a = 0
while i<100 :
i += 1
a += i
print(a)
n = 100
sum = 0
counter = 1
while... |
# -*- coding = utf-8 -*-
# Author:ZhouShuyu
# @Time : 2021/8/19 14:54
# @File : p6_for_loop.py
'''
for i in range(5): #for循环的基本使用方式,可以打印 0 1 2 3 4
print(i)
'''
'''
for i in range(0,10,3): #表示从 0 开始到 10 ,步进值为 3 .打印结果 0 3 6 9 ,每次加 3 相当于 for(int i=0;i<10;i+=3)
print(i)
'''
'''
for i in range(... |
# -*- coding = utf-8 -*-
# Author:ZhouShuyu
# @Time : 2021/9/15 14:56
# @File : def.py
#函数的定义
'''
def printinfo():
print("----------------------")
print(" 人生苦短,我用python ")
print("----------------------")
#函数的调用
printinfo()
'''
#带参的函数
'''
def add2Num(a,b):
c = a+b
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.