text stringlengths 37 1.41M |
|---|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
h=Node(0,... |
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
res = []
x = path.split('/')
for i in x:
if i == '' or i == '.':
continue
elif i == '..':
if res:
... |
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
slow=fast=0
while 1:
slow = nums[slow]
fast = nums[nums[fast]]
if slow==fast:
break
fast=0
while 1:
... |
#coding=utf-8
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):#递归方法1
def __init__(self):
self.list = []
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: Li... |
#Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if ro... |
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
i=0
res = []
while i<len(nums1) and nums2:
if nums1[i] in nums2:
res.append(nums1[i])
... |
import heapq
class Solution(object):
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
outline_list=[]
for left,right,height in buildings:
outline_list.append([left,-height,right])
outline_list.a... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.max=float('-inf')
def mx(self,root):
if not root:
return 0
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
... |
class Caja:
estado = 'off'
precios = { 1:10.2, 2:25.6 , 3:38.3, 4:46.3, 5:56.7, 6:67.8 }
tickets = []
def __init__(self):
print("Iniciando caja...")
self.estado = 'on'
def getEstado(self):
return self.estado
def apagar(self):
print("Apagando caja...")
... |
class stack:
def __init__(self):
self.arr=[]
def insert(self,value):
self.arr.append(value)
def delete(self):
self.arr.pop()
def insertionSort(self,arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
... |
class Car():
def __init__(self):
self.engine = None
self.price = None
self.maxspeed = None
def __str__(self):
return '{} | {} | {}'.format(self.engine, self.price, self.maxspeed)
class AbstractBuilder():
def __init__(self):
self.car = None
... |
class TAXI:
def __init__(self, num):
self.num = num
def ride_along(self):
print("You may want to get in" + self.num)
class TAXIPool(TAXI):
def ride_along(self):
print("You want a pool ride? ")
print(self.num + " will take care of that with... |
# conventional way to import
import numpy as np
import pandas as pd
#import seaborn as sns
#import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn import linear_model
from skl... |
import json
import datetime
import requests
class Game(object):
def __init__(self):
self.date = datetime.datetime(2003,8,1,12,4,5) #do we need the hour?
def turn(self):
self.date += datetime.timedelta(days=1)
print(self.date) #reveal the new date
class Celebrity(object):
# this ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 18:04:31 2021
@author: bhavinpatel
"""
#
#Problem 1
l = ['*']
count = 4
for i in l:
for j in range(1,7):
if j != 6:
print(i*j)
else:
for k in sorted(range(4),reverse=True):
print(i*k)
... |
import argparse
# Argument parsers
parser = argparse.ArgumentParser(description='Compute c (Assignment 1)')
parser.add_argument('segments', metavar='N', type=int,
help='The total time of the voyage')
parser.add_argument('--time', required=True, type=int,
help='The total time of ... |
print('Welcome!')
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
city = []
city_df = []
month = []
day = []
def start():
start = input('Press enter to begin')
def city_f... |
my_list = range(16)
filter(lambda x: x % 3 == 0, my_list)
languages = ["HTML", "JavaScript", "Python", "Ruby"]
# Add arguments to the filter()
print filter(lambda x: x == "Python", languages)
squares = [x ** 2 for x in range(1, 11)]
print filter(lambda x: x >= 30 and x <= 70, squares)
... |
class Fruit(object):
"""A class that makes various tasty fruits."""
def __init__(self, name, color, flavor, poisonous):
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous
def description(self):
print "I'm a %s %s and I taste %s." % (self.color, self.name, self... |
# -*- coding: utf-8 -*-
"""Provide functions for the creation and manipulation of Planes.
Planes are represented using a numpy.array of shape (4,).
The values represent the plane equation using the values A,B,C,D.
The first three values are the normal vector.
The fourth value is the distance of the plane from the ori... |
class Body:
def __init__(self, name):
self.name = name
self.children = set()
self.parent = None
def add_child(self, child_name):
self.children.add(child_name)
def add_parent(self, parent):
self.parent = parent
def direct(self):
return len(self.children)... |
""" Module: Opponent
...
"""
class Opponent(object):
""" Opponent is an interface.
This is intended to be implemented by Player and Team, which are
capable of participating in Games.
"""
def __init__(self):
""" This constructor should never be called. Raise an error. """
rai... |
""" Module: exceptions
API Exceptions to throw.
"""
class InputError(Exception):
""" Exception raise when the incoming request has bad input.
Variables:
str reason an explanation for the error
"""
def __init__(self, parameter_name, parameter_value):
""" Construct an bad inp... |
x = int(input())
y = int(input())
soma = 0
if y > x:
for i in range(x, y + 1):
if i % 13 != 0:
soma += i
print(soma)
else:
for i in range(y, x + 1):
if i % 13 != 0:
soma += i
print(soma) |
vals = input().split()
a = int(vals[0])
b = int(vals[1])
c = int(vals[2])
if a < b and a < c:
print(a)
if b < c:
print(b)
print(c)
else:
print(c)
print(b)
if b < a and b < c:
print(b)
if a < c:
print(a)
print(c)
else:
prin... |
pi = 3.14159
R = float(input())
A = pi*R**2
print('A=%1.4f' %A) |
balance = 320000
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12
unPaid = balance
lowerBound = balance / 12
upperBound = (balance * (1 + monthlyInterestRate) ** 12) / 12.
monthlyPayment = 0
presion = 0.10
while balance >= presion:
monthlyPayment = (lowerBound + upperBound) / 2
for x in range(... |
import time
import math
import heapq
import queue
import numpy
# Customer arrives event
# When customer arrives, they'll check each teller choose the first one is idle.
# If there are none available, the customer (arrival time, work units) is pushed on the waiting line.
def customerArrives(time, windows, work... |
__author__ = 'shahryar_saljoughi'
def compute_sum(A):
"""
:param A: is of type list , containing numbers.
:return: sum of the numbers in A will be returned .
"""
result = 0
for i in A:
result += i
return result
def compute_maximum_subarray(A):
"""
:param A: A is a list ... |
#encoding: UTF-8
# Autor: Mauricio Alejandro Medrano Castro, A01272273
# Descripcion: Calcular la propina, el IVA y total de una cuenta.
# A partir de aqui escribe tu programa
subtotal = int(input("subtotal"))
propina = subtotal * 0.15
impuesto = subtotal * 0.16
totalAPagar = subtotal + propina + impuesto
prin... |
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.IN)
GPIO.setup(3,GPIO.OUT)
GPIO.setup(13,GPIO.IN)
GPIO.setup(5,GPIO.OUT)
c1=0
while True:
i=GPIO.input(11)
if i==0:
GPIO.output(3,1)
print("person entering")
c1=c1... |
def arithmetic_arranger(problems, B = None):
let = "abcdefghijklmnopqrstuvwxyz"
ans = ""
soln = 0
str = ""
opStr = ""
numspace = " "
dash = ""
if len(problems) > 5:
return "Error: Too many problems."
else:
for i in enumerate(problems):
if "+" not in i[1] a... |
import random
random.seed(3900)
MAX_COORDINATES = 1000
BUS_STOPS = 60
DIFFERENT = 3
NAMES = ["Square", "Stadium", "Bridge", "Washington", "Pool", "Road",
"Highway to bell", "KYPES", "Circus", "Church", "Town Hall",
"Zoo", "Pasalimani", "Tsoukaleika", "Vraxneika", "Kallithea",
"Summoners Rif... |
# class A(object):
# def __init__(self, name):
# self.name = name
#
# def __eq__(self, obj):
# return self.name == obj.name
# def __hash__(self):
# return
#
# if __name__ == '__main__':
# a = A("Leon")
# b = A("Leon")
# print(a == b)
# print(id(a),id(b))
class Foo:
... |
def area_triangle(base, height):
area = (base*height)/2
return area
def area_circle(pi, radius):
area = round((pi*(radius*radius)), 2)
return area
def memory_in_bits(target):
length = 0
while (target):
target >>= 1
length += 1
return(length)
def memory_in_bytes(target):
... |
'''
Created on Mar 5, 2013
@author: RDrapeau
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
# Returns 3 numbers multiplied toge... |
'''
Created on Mar 4, 2013
@author: RDrapeau
A palindromic number reads the same both ways. The largest palindrome made from the product of
two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
# Returns the largest palindrome made from the product of ... |
'''
Created on Mar 4, 2013
@author: RDrapeau
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
numbers_to_check = [11, 13, 14, 16, 17, 18, 19, 20]
# Returns ... |
import sqlite3
import csv
import json
DBNAME = 'choc.db'
BARSCSV = 'flavors_of_cacao_cleaned.csv'
COUNTRIESJSON = 'countries.json'
def init_db(db_name):
try:
conn = sqlite3.connect('choc.db')
cur = conn.cursor()
except:
print('an error was encountered')
statement = "SELECT COU... |
A, B, C = map(int, input().split())
sq_A=A*A
sq_B=B*B
sq_C=C*C
if sq_A+sq_B < sq_C:
print("Yes")
else:
print("No") |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: tylersschwartz
"""
import random
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
"""
in_file = open(WORDLIST_FILENAME, 'r')
line = in_file.readline()
wordli... |
import os
import sys
def rename(self_name,prefix,begin_offset,suffix):
#print self_name
path= os.getcwd()
num = int(begin_offset)
filelist = os.listdir(path)
for file in filelist:
# prevent from modifing the name of program self
if file in self_name:
continue
Olddir = os.path.join(path,file)
... |
import unittest
from app.models import Movie
class MovieTest(unittest.TestCase):
"""
Test Class to test the behaviour of the movie class
"""
def setUp(self):
"""Set up method taht will run before every Test
"""
self.new_movie = Movie(1234, 'Python must be crazy', 'A thrilling new python series', 'https://de... |
end = 6
totalSum = 0
for individualNumber in range(1, end + 1):
totalSum += individualNumber
print(totalSum)
|
# s = "azcbobobegghakl"
s = "abcbcd"
longestSubstring = ""
start = 0
tempSubstring = s[start]
while (start < len(s)-1):
for j in range(start+1, len(s)):
if s[j] >= tempSubstring[len(tempSubstring)-1]:
tempSubstring = tempSubstring + s[j]
start = j
else:
if len(t... |
from blinkstick.blinkstick import BlinkStick, blinkstick_remap_rgb_value_reverse
import asyncio
class AsyncBlinkStick(BlinkStick):
"""
Controls BlinkStick devices in exactly the same was as the BlinkStick
class, but uses asyncio.sleep instead of time.sleep so that it plays nice
with code written usin... |
import unittest
from typing import List
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
def diameter(edges: List[List[int]]) -> int:
start = -1
for i, l in enumerate(edges):
if l:
start = i
break
if start == -... |
import unittest
from Tree import Tree
from typing import List
def solve(root: Tree) -> bool:
queue: List[Tree] = [root]
meet_empty = False
while root:
node = queue.pop()
if node:
if meet_empty:
return False
queue.append(node.left)
queue.... |
'''
Stack is LIFO - implementing first using python List
Implement using Node later
'''
class Stack:
def __init__(self):
self._items = []
def push(self,item):
self._items.append(item)
print "pushing : {}".format(item)
# print "stack is now {}".format(self._items)
def pop(... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class FunctionRepresentation(nn.Module):
"""Function to represent a single datapoint. For example this could be a
function that takes pixel coordinates as input and returns RGB values, i.e.
f(x, y) = (r, g, b).
Args:
... |
x=input()
y=0
for i in range(len(x)):
if ord(x[i])>=2437 and ord(x[i])<=2443:
y=y+1
elif ord(x[i])==2447==2448==2482==2524==2525==2510==2527==2528:
y=y+1
elif ord(x[i])>=2451 and ord(x[i])<=2472:
y=y+1
elif ord(x[i])>=2474 and ord(x[i])<=2480:
y=y+1
elif ord(x[i])>=... |
# 7. 어떤 회사 자동차의 hwy(고속도로 연비)가 가장 높은지 알아보려 합니다.
# hwy(고속도로 연비) 평균이 가장 높은 회사 세 곳을 출력하세요.
class Car(object):
def __init__(self, car_data):
car_data = car_data.split(",")
self.manufacturer = car_data[0]
self.model = car_data[1]
self.displ = float(car_data[2])
self.year = int(car_... |
'Author: Ionwyn Sean'
def knapsack(items, weight):
table = [[0 for w in xrange(weight + 1)] for i in xrange(len(items) + 1)]
for i in xrange(1, len(items) + 1):
item_name, item_weight, item_value = items[i-1]
for w in xrange(1, weight + 1):
if (item_weight > w):
... |
A= [0,2,1,0]
B = sorted(A)
highest = B[-1]
print(highest)
i = 0
for a in A:
if a == highest:
print(i)
break
i += 1
|
#!/usr/bin/env python
'''
Numpy [Python]
Ejercicios de práctica
---------------------------
Autor: Inove Coding School
Version: 1.1
Descripcion:
Programa creado para que practiquen los conocimietos
adquiridos durante la semana
'''
__author__ = "Inove Coding School"
__email__ = "alumnos@inove.com.ar"
__... |
import pyscipopt as scip
def knapsack(weights, profits, capacity, name="Knapsack"):
"""Generates a knapsack MIP formulation.
Parameters:
----------
profits: list[float]
List of profits of each item
weights: list[float]
List of weights of each item
capacity:... |
import argparse
import egglib
import sys
def complement(seq_str):
comp_dict = {'A': 'T', 'G': 'C', 'T': 'A', 'C': 'G', 'N': 'N', '?': '?', '-':'-'}
complement_seq = ''
for base in seq_str:
complement_seq += comp_dict[base]
return complement_seq
parser = argparse.ArgumentParser(description=... |
def quick_sort(num):
if len(num)<=1:
return num
pivot = num[-1]
less, greater, equal = [], [], []
for i in num:
if i < pivot:
less.append(i)
elif i>pivot:
greater.append(i)
else:
equal.append(i)
return quick_sort(less)+equal+quick_s... |
import re
i = "Hello from Python"
#Find all lower case characters alphabetically between "a"and "m":
x = re.findall("[a-z]", i)
print(x) |
#############################################################################################################################
# This python file contains the main program, it will process the data, create the grammar and oov, get the parsed results. #
####################################################################... |
def find_cubes(n):
return [i**3 for i in range(n)]
def is_permutation(first, second):
if len(first) != len(second):
return False
for f in first:
if f not in second:
return False
second = second.replace(f, "", 1)
if len(second) == 0:
return True
def find_pe... |
# Consider sorting n numbers stored in array A by first finding the smallest element
# of A and exchanging it with the element in A[1]. Then find the second smallest
# element of A, and exchange it with A[2]. Continue in this manner for the first n 1
# elements of A.
# I think it means A[0]
def exchange_values(array,... |
def print_maximum(a, b):
if a > b:
return a
elif a == b:
print('both {} and {} are equal'.format(a, b))
return a,b
else:
return b
guess1 = int(input('enter number 1:'))
guess2 = int(input('enter number 2:'))
print(print_maximum(guess1, guess2))
|
guess = int(input('enter a number:'))
i = 1
for i in range(i, guess+1):
print('print count {}'.format(i))
if i == 3:
print('done')
break
else:
print('not done')
else:
print('else for')
|
from state import *
import random
import math
from csv import *
class Node():
"""Documentation for node
"""
def __init__(self, ident, father, children, state, reward, n_visit):
self.ident = ident
self.father = father
self.children = children
self.state = state
sel... |
from microbit import *
def minmax(number, min, max):
if number < min:
return min
elif number > max:
return max
else:
return number
while True:
if (accelerometer.is_gesture("up")):
display.show(Image.ARROW_N)
elif (accelerometer.is_gesture("down"... |
from copy import deepcopy
import pdb
def is_palindrome(num: int) -> bool:
return str(num) == str(num)[::-1]
def separate_2_three_digits_number(num: int) -> bool:
result = False
for i in range(100, 1000):
if num % i == 0 and len(str(int(num / i))) == 3:
result = True
break
... |
from os import name
import sqlite3 as sq
from sqlite3.dbapi2 import Cursor
#pasos para usar y manipular una base de datos:
# 1) Conectarme
# 2) Definir cursor y modificar
# 3) Guardar o asigna esa modificación
# 4) Cerrar la conexión
#conectarme a una base de datos
conexion = sq.connect('ejemplo.db')
print('Conecta... |
import numpy as np
data = np.array([1, 2])
ones = np.ones(2, dtype=int)
# suma
print("suma",data + ones)
# resta
print("resta",data - ones)
# mult
print("multiplicación",data * ones)
# div
print("división",data / ones)
# se puede multiplicar todos y cada uno de los elementos por un entero o flotante
print("ente... |
import numpy as np
# una manera de crear un array desde una lista
a = np.array([1, 2, 3, 4, 5, 6])
# Acceder a posiciones
print(a[3])
# o también es posible crear matrices
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(b[2,1])
# crear un array de ceros
print(np.zeros(2))
# crear un array de u... |
# escriba un código que transforme una lista de entrada con palabras
# en una variable tipo string con las palabras separadas por
# espacios.
# ejemplo:
# entrada: ["Hola", "a", "todos"]
# salida: "Hola a todos"
# Sol 1
wordsList = ["Hola", "a", "todos"]
words = ""
for i in wordsList:
words = words + i + " "
print... |
# Stacks como listas
s = []
s.append("eat")
s.append("sleep")
s.append("code")
print(s)
input("Press Enter to continue...")
# Extraer último elemento en ingresar
le = s.pop()
print(le)
print(s)
input("Press Enter to continue...")
# extraer más...
s.pop()
s.pop()
print(s)
# Stacks como dequeue (más rápidas y robusta... |
# Creación de diccionario
my_dict = {} #empty dictionary
print(my_dict)
my_dict = {1: 'Python', 2: 'Java'} #dictionary with elements
print(my_dict)
input("Press Enter to continue...")
# Acceder a elementos
my_dict = {'First': 'Python', 'Second': 'Java'}
print(my_dict['First']) #access elements using keys
print(my_dict... |
import random
N = 3
grid = [['.']*N for _ in range(N)]
elements = ['1','2','3','4','5','6','7','8',' ']
def clear_grid():
for i in range(N):
for j in range(N):
grid[i][j] = '.'
def set_elements():
z = 0
for i in range(N):
for j in range(N):
while grid[i][j] == '.':
... |
from tkinter import *
from PIL import ImageTk, Image
import string
root = Tk()
root.title("UEFA EURO 2020")
root.iconbitmap("images/football.ico")
title = Label(root, text="UEFA EURO 2020 GROUPS")
title.grid(row=0, column=0)
# store teams and their photos
pictures = {
"italy": "images/italy.jpeg",
... |
import re
text = input()
phone_num_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
found = phone_num_regex.findall(text)
print(found)
text = input()
bat = re.compile(r'Bat(man|mobile|copter|bat|women)')
mo = bat.search(text)
print(mo.group())
|
def starts():
print("Jay Ganesh")
print("jay Ganesh")
print("jay Ganesh")
print("jay Ganesh")
def startsI():
icnt=1;
while icnt<=5:
print("Jay Ganesh")
icnt=icnt+1
def main():
print("sequence approach")
starts()
print("Iteration approach")
star... |
# object orientation in python
class Arithematic: # class definition
value = 111 # class variable or static variable in c cpp
def __init__(self, i, j): # class constructor
self.no1 = i # class instance variable
self.no2 = j # class ... |
#import Arithmetic -----------first Way
#import Arithmetic as AR -----------second way
#from Arithmetic import Addition,Substraction -------third way
from Arithmetic import * #----fourth way
def main():
print("__name__ from main is",__name__)
print("Enter the first number")
val... |
#add 2 Numbers
a = int(input("Enter the First Number :"))
b = int(input("Enter the Second Number :"))
c = a + b
print("The Sum of Two Numbers : ",c) |
#Write a program to use split and join methods in the string
a="hi, i am python programmer"
b=a.split()
print (b)
c=" ".join(b)
print (c)
|
#Max of two Numbers
a = int(input("Enter the First Number :"))
b = int(input("Enter the Second Number :"))
c = int(input("Enter the third Number :"))
if a>=b:
if a>=c:
print("Greatest Number :",a)
else:
print("Greatest Number :",c)
else:
if b>=c:
print("Greatest Number :",b)
else:
print("Greatest Number :... |
# Calc Grade Of Student for 5 Subjects Marks
def calcgrade(m):
if((m >= 85) and (m <= 100)):
return "AA"
elif ((m >= 75) and (m < 85)):
return "AB"
elif ((m >= 65) and (m <= 75)):
return "BB"
elif ((m >= 55) and (m < 65)):
return "BC"
elif ((m >= 45) and (m < 55)):
... |
'''
A date in Python is not a data type of its own,
but we can import a module named datetime to work with dates as date objects.
'''
#Import the datetime module and display the current date
import datetime
x = datetime.datetime.now() #date contains year, month, day, hour, minute, second, and microsecond
print... |
# perform Linear Search
a = flag=0
items = [5, 7, 10, 12, 15]
print("list of items is", items)
x = int(input("enter item to search:"))
while a < len(items):
if items[a] == x:
flag = 1
break
a = a + 1
if flag == 1:
print("item found at position:", a + 1)
else:
print("item not found")
# print('----ho... |
# function which takes result of 10 students and give top 3
l = [23,45,22,44,32,13,24,34,41,19]
def top3(l):
l.sort(reverse=True)
#x = l
return l
print(top3(l)[:3])
'''
l = [23,45,22,44,32,13,24,34,41,19]
for i in range(0,50,10):
print(i)
'''
|
# Print Factors of Given Number
import math
n = int(input("Enter a Number Whose Factors Needs to Be Found : "))
# Approach 1 : 1 to n and if remainder 0 print it
# k = 1
# ans = []
# while(k <= n):
# if((n % k) == 0):
# ans.append(k)
# k = k+1
# for i in ans:
# print(i, end=" ")
# Approach 2 : 1 t... |
# Write a python program that combines two lists into a dictionary.
test_keys_list = ["Ram", "Shyam", "Ghanshyam"]
test_values_list = [3, 11, 29]
# Printing original keys-value lists
print("Original key list is : ", test_keys_list)
print("Original value list is : ", test_values_list)
dict1 = {} # Empty Dictionary
f... |
#find the maximum from a list of numbers
l=[]
n=int(input("enter the size of list: "))
for i in range(0,n):
a=int(input("enter number: "))
l.append(a)
maxno=l[0]
for i in range(0,len(l)):
if l[i]>maxno:
maxno=l[i]
print("The maximum number is: %d"%maxno)
|
nome = str(input('Qual é o seu nome? ')).strip()
if nome.title() == 'Thiago':
print('Que nome bonito!')
elif nome.title() == 'Isabella':
print('Você é uma delícia hein!')
elif nome.title == 'Manuella':
print('Que princesinha linda!')
elif nome.title() == 'Miguel':
print('Bonitão, malucole!')
elif nome.t... |
carro = int(input('Digite a que velocidade está o carro: '))
if carro > 80:
multa = (carro - 80) * 7
print('VOCÊ FOI MULTADO! O valor da MULTA é de R$ {:.2f}'.format(multa))
else:
print('Sua velocidade está boa, PARABÉNS!') |
p = float(input('Digite o valor do produto: R$ '))
print('Escolha a forma de pagamento:')
fp = int(input('''Digite:
[1] - À vista dinheiro/cheque: 10% de desconto
[2] - À vista no cartão: 5% de desconto
[3] - Em até 2x no cartão: preço normal
[4] - Em 3x ou mais no cartão: 20% de juros
sua opção: '''))
if fp == 1:
... |
maior = 0
for c in range (1, 6):
peso = float(input('Digite o peso da {} pessoa: '.format(c)))
if peso > maior:
maior = peso
if c == 1 :
menor = peso
if peso < menor:
menor = peso
print('O maior peso foi {:.1f}kg e o menor foi {:.1f}kg'.format(maior, menor)) |
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 + n2)/2
if m < 5:
print('Aluno \033[41mREPROVADO!\033[m')
elif 7 > m >= 5:
print('Aluno em \033[43;30mRECUPERAÇÃO!\033[m')
else:
print('Aluno \033[42;30mAPROVADO!\033[m')
|
dinheiro = float(input('Quanto de dinheiro tem em sua carteira?: '))
print('Você pode comprar {:.2f} doláres!'.format(dinheiro / 3.27)) |
tupla = (int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais outro número: ')),
int(input('Digite o último número: ')))
print(tupla)
|
frase = 'Curso em vídeo Python'
#.Fatiamento
print('-'*13)
print('{:^13}'.format('Fatiamento'))
print('-'*13)
print(frase[9:13])
print(frase[9:21])
print(frase[9:21:2])
print(frase[:5])
print(frase[15:])
print(frase[9::3])
print(frase[::2])
print()
#.Análise
print('-'*13)
print('{:^13}'.format('Análi... |
'''num = [2, 5, 9, 1]
num[2] = 3
num.append(7)
num.sort(reverse=True)
num.insert(2, 2)
if 5 in num:
num.remove(5) # varre do ínicio da lista ao final e remove o primeiro valor do indice
else:
print('Não achei o número 5')
print(num)
print(f'Essa lista tem {len(num)} elementos.') '''
'''valores = []'''
'''valore... |
print('THE 10 TERMS OF AN A.P.')
print('<><><><><><><><><><><><>')
i = int(input('Digite o primeiro termo da P.A. : '))
r = int(input('Digite a razão da P.A. : '))
c = 1
t = i
d = 10
counter = d
answer = False
while answer is False:
while c <= d:
if c < d:
print('{} → '.format(t), end='')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.