text stringlengths 37 1.41M |
|---|
import time as t
print('hello Python 3')
"""
多行注释
"""
'''
多行注释
'''
print('我喜欢"香蕉"') # 注释:单引号里是可以写双引号的字符串
print('we\' ar go to shopping.') # 如果要单引号内使用单引号,需要转义字符\
print("我们发现这个\"地方\"不一样")
print("hi" + "Tom") # 字符串采用加号连接
# print("Hi" + 5) # 字符和数字链接报错,提示5必须要是str,不能是int
print("Hi" + str(5))
print(int('8') + 5) # 字符... |
#!/usr/bin/env python
# coding: utf-8
# # Case Study: Wine Quality
# in this Jupyter notebook we will be analysing data of red and white wine from a dataset of the UCI - follow this [link](https://archive.ics.uci.edu/ml/datasets/Wine+Quality) to download the data, since it will not be stored in the repository.
# In[2... |
#Addition of Elements in the list
def AddInList(numOfElement):
arr = list()
for i in range(0, numOfElement):
number = int(input())
arr.append(number)
return arr
def Addition(arr):
sum = 0
for i in range(0, len(arr)):
sum += arr[i]
return sum
a = int(inpu... |
# Day 18: Operation Order
import pytest
import re
# Evaluate the expression on each line of the homework; what is the sum of the resulting values?
def part1(data):
total = 0
for line in data.split('\n'):
tokens = tokenize(line)
program = parse(tokens)
val = calc(program)
# print(val, '=', line)
... |
# Day 23: Crab Cups
import pytest
# Using your labeling, simulate 100 moves. What are the labels on the cups after cup 1?
def part1(data, moves = 100):
nums = list(map(int, data))
max_num = max(nums)
min_num = min(nums)
# Each move, the crab does the following actions:
for i in range(moves):
# The crab ... |
# To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set.
# For example, suppose you have the following list:
# 1-3 a: abcde
# 1-3 b: cdefg
# 2-9 c: ccccccccc
# Each line gives the password policy... |
# 3. Write a program to test if the input number by a user is in between 100 - 1000.
# Sample output :
# Enter a number: 150
# The number 150 is in between 100 - 1000.
print("We are testing here if the number you input is in between 100 - 1000 "
"or not")
num = int(input(("So, Please enter a Number: ")))
... |
import classes
import functions
import random
playing = True
def main():
global playing
print("Welcome to Blackjack")
player_name = input("What's your name? ")
player_hand = classes.Hand(player_name)
dealer_hand = classes.Hand("dealer")
while True:
try:
player_total = int... |
from vocabulary import vocab
print("Input word to check against dictionary")
print("Input 'quit' or 'q' to quit")
while True:
checkedWord = input("Please input word: ")
if checkedWord.lower() == "q" or checkedWord.lower() == "quit":
break
elif checkedWord in vocab:
with open("checked.txt"... |
import matplotlib.pyplot as plt
# Plots a single function
def plot(x, y, title, xlabel, ylabel):
plt.plot(x, y, linestyle='--', marker='o')
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
# Plots two functions for Adult and Bike Sharing data sets
def plotTwo(x, y1, y2, title, xl... |
def Prime(n):
k=1
while (True):
if( n<3):
break
elif ( ( n % 2 ) == 0) :
n = n/2
factors.append(2)
elif ( ( n % 3 ) == 0) :
n = n/3
factors.append(3)
elif ( ( n % (6*k -1) ) == 0) :
n = n/(6*k... |
def unionD(a,b):
a.sort()
b.sort()
i=0
j=0
c=[]
while(i+j<=len(a) + len(b) -2):
if((i <len(a) )and (len(b)>j)):
if ( a[i] == b[j]):
c.append(a[i])
i=i+1
j=j+1
else:
c.append(a[i])
c.appen... |
result = [1]
def unique(a):
""" return the list with duplicate elements removed """
return list(set(a))
def intersect(a, b):
""" return the intersection of two lists """
return list(set(a) & set(b))
def union(a, b):
""" return the union of two lists removing the duplicates"""
return list(set(... |
# this program sends each line of a text file to the serial monitor
# for an arduino program to read in, and then it prints out the
# output of that Arduino program to the terminal
# for use with the Arduino sketch bpm_from_file.ino
import serial
# the name of the arduino serial port, the baud rate
ser = serial.Ser... |
print("Basic dictionary")
myPet = {"size": "short", "species": "royal", "intelligence": "stupid"}
print(myPet["species"])
input()
print("Dictionary with numbers as keys")
myPet = {1: "short", 5: "royal", 2: "stupid"}
print(myPet[2])
input()
print("Dictionary with strange keys")
key = "species"
myPet = {None: ... |
print("Hello", end="-")
print("World")
input()
def myFunctionWithKwargs(first=1, second="two", third=False):
print(first, second, third)
myFunctionWithKwargs()
myFunctionWithKwargs(first=1, second="two", third=True)
myFunctionWithKwargs(1, "two", True)
myFunctionWithKwargs(first=2, second="one")
myFunctionWithKw... |
def ratsNest():
x = 10
def secondLevel():
def thirdLevel():
# x = 30
print(x)
thirdLevel()
secondLevel()
ratsNest()
input()
def timesTwo(x):
print(x * 2)
delayedFunction = timesTwo
delayedFunction(10)
input()
def closure():
... |
__author__ = 'effy'
from tkinter import *
from PIL import Image, ImageTk
## create all the necessary object to form a window.
root = Tk()
root.title("Welcome to GO BANANAS!!!")
root.geometry("500x450")
root.grid()
## open image for the background
bg_start = Image.open("start.jpg")
BG_Start = ImageTk.PhotoImage(bg_st... |
#!/usr/bin/env python
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
class Plots:
"""
Creates plots for text columns: word_dist_plot()
and for categorical columns: count_plot()
----------
Input: method(dataframe, first column to process, last column to process)
---... |
#!/usr/bin/env python
# for homework:
# identify what type of data each value is, and cast it
# to the appropriate type, then print the new, properly-typed
# list to the screen.
# I.e. ['0.04741', '0.00', '11.930', '0', '0.5730', '6.0300', '80.80', '2.5050', '1', '273.0', '21.00', '396.90', '7.88', '11.90']
# becomes:... |
from numbers import Real
from sympy import Add, Mul
from sys import modules
def mult_tuples(x, y):
ind = 0
ind0 = min(len(x), len(y))
while (ind < ind0) and (x[-ind-1] == y[ind]):
ind += 1
if ind == 0:
return x + y
else:
return x[:-ind] + y[ind:]
def chomp_empty(seq):
... |
"""
Problem Statement:
Given an array of intervals intervals where intervals[i] = [starti, endi],
return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example:
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest ... |
# coding=utf-8
# 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
#
# 示例:
#
# 输入:
# [
# 1->4->5,
# 1->3->4,
# 2->6
# ]
# 输出: 1->1->2->3->4->4->5->6
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKList... |
# coding: utf-8
# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
#
# 有效字符串需满足:
#
# 左括号必须用相同类型的右括号闭合。
# 左括号必须以正确的顺序闭合。
# 注意空字符串可被认为是有效字符串。
#
# 示例 1:
#
# 输入: "()"
# 输出: true
# 示例 2:
#
# 输入: "()[]{}"
# 输出: true
# 示例 3:
#
# 输入: "(]"
# 输出: false
# 示例 4:
#
# 输入: "([)]"
# 输出: false
# 示例 5:
#
# 输入: "{[]}"
# 输出: true
class So... |
import os
import csv
import docx
## This python script converts a *.csv file that contains application fault code content into
## a word table.
# A. Ensure our working directory is set to where the python file exists.
# 1) Find the path where the script is run from and set the absolute path to this.
# ... |
from Board import Board
from Ship import Ship
import time, random
def is_integer(n):
try:
float(n)
except ValueError:
return False
else:
return float(n).is_integer()
def proper_coords(input):
inp = input
if inp == "": #no input
return False
format_count = 0... |
x=input()
s=0
for i in range (0,len(x)):
s=s+(int(x[i])**3)
s=str(s)
if(x==s):
print("yes")
else:
print("no")
|
self.art.Calificar(m3,5)
assert self.art.Calificaciones == [1,4,5] ,"falla colocando la tercera puntuacion"
assert self.art.Jurado == [m1,m2,m3] , "falla colocando al tercer jurado"
# prueba para verificar que un jurado pueda votar dos veces o mas
self.assertEqual(self.... |
#q3 lst=[2,3,5]
#o/p =[8,7,5]
#2+3
lst=[2,3,5]
res=sum(lst)
for i in lst: #2, 3, 5
print(res-i) #10-2=8, 10-3=7
#num=total-i
#op.append(num)
#sum() to find total of list |
class Student:
college="BITS"
def __init__(self,roll_no,name,course,total):
self.roll_no=roll_no
self.name=name
self.course=course
self.total=total
def printStudent(self):
print("roll_no=",self.roll_no)
print("name=",self.name)
print("course=",self.cou... |
from functools import *
class employee:
cname = "luminar"
def __init__(self, empid, name, sal, desig):
self.id = empid
self.name = name
self.sal = sal
self.desig = desig
def printVal(self):
print(" id :", self.id)
print(" name :", self.name)
print(... |
#calculate sum of odd and even numbers
low=int(input("enter lower limit"))
upp=int(input("enter upper limit"))
sumeven=0
sumodd=0
for i in range(low,upp):
if(i%2==0):
sumeven=i+sumeven
else:
sumodd=i+sumodd
i=i+1
print("sum of even number is",sumeven)
print("sum of odd number is",so... |
#read three numbers and print largest among three
number1=int(input("enter value for number1"))
number2=int(input("enter value for number2"))
number3=int(input("enter value for number3"))
if((number1>number2)&(number1>number3)):
print("number1 is the largest number")
elif((number2>number1)&(number2>number3)):
... |
names=["kkr","dc","kxp","mi","csk"]
data=list(map(lambda string:string.upper(),names))
print(data)
#reduce
from functools import *
numbers=[10,11,12,13,14]
total=reduce(lambda num1,num2:num1+num2,numbers)
print(total)
max=reduce(lambda num1,num2:num1 if num1>num2 else num2,numbers)
print(max)
... |
class Employee:
def __init__(self,id,name,salary,desig):
self.id=id
self.name=name
self.salary=salary
self.desig=desig
def printEmployee(self):
print("id=", self.id)
print("name=", self.name)
print("salary=", self.salary)
print("desig=", self.desig... |
#list
#we can define list by using[] or we can define empty list by usinglst()
# lst=list() or lst=[]
#print(type(lst))
#we can store same and diffrnt types of data
#we can store duplicate vale
#list object is mutable(update is possible)
#ex:
#lst=["luminar technolab",2017,True]
#print(lst)
lst=["ajay",29,25000]
lst[0... |
class Parent:
def phone(self):
print("i have nokia5310")
class Child(Parent):
def phone(self):
print("iphone")
c=Child()
c.phone()
#perent-->child
#superclass-->subclass
#base clas-->derived class
|
#create a student dictionary with total
student={"role no":5,"name":"samvi","total":50}
print(student)
print(student["name"])
print("college" in student)
student["college"] ="luminar technolab"
print(student)
student["total"]=100
print(student)
#for key in student:
#print(key) -->only key value roleno, name, to... |
#Display “My Name Is James” as “My**Name**Is**James”...
name1=input("enter your name")
print("My","**","Name","**","is","**",name1) |
#input list or array
#step sor
ar=[6,4,5,2,1,3]
#step sorting
ar.sort()
print(ar)
low=0
upp=len(ar)
flag=0
element=int(input("enter element for searching"))
while(low<=upp): #0<6 4<6
mid=(low+upp)//2 # mid=3 4+6//2=5
#[1,2,3,4,5,6]
#case1
if(element>ar[mid]): #5>ar[3] 5>4 5>5
low=mid+1 #low=3... |
# -*- coding: utf-8 -*-
"""
@authors : Calbert Julien & Godfriaux Maxime
"""
import numpy as np
# This class defines the neuralNetworks
class NNetwork:
# This function defines the Neural Network. p indicates if its the first
# generation, NeuralNetworkArchitecture is an array representing the number
... |
from PIL import ImageDraw
from PIL import Image, ImageEnhance
from PIL import ImageFont
img= Image.open("forsk-logo.png")
str_name = input("enter the name")
str_coll = input("enter the college name")
str_branch = input("enter the branch")
str_batch = input("enter the batch")
def ReduceOpacity(im, opacity):
as... |
# Interactive Guess the Number Game
"""
Challenge 1
The computer will think of a random number from 1 to 10 as secret number
Then ask you ( Player ) to guess the number and store as guess number
Compare the guess number with the secret number
If the player guesses the right number he wins,
... |
class User:
def __init__(self,nombre,correo):
self.nombre = nombre
self.correo = correo
self.account = BankAccount(int_rate=0.02, balance=0)
def situacion(self):
return self.nombre, self.correo, self.account.balance
def make_deposit(self, amount):
self.account.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 17:55:44 2018
@author: lifanhong
Example
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
failed test case:
s = "3[z]2[2[y]pq4[2[jk]e1[f]]]ef", return "zzzyypqjkjkefjkjkefjkjke... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 6 21:14:35 2018
@author: lifanhong
A valid IP address must be in the
form of xxx.xxx.xxx.xxx,
where xxx is a number from 0-255.
"""
class Solution:
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 30 19:52:47 2018
@author: lifanhong
"""
class Solution:
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
v = ['a','e','i','o','u','A','E','I','O','U']
vsaver = []
pos = []
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 7 10:13:25 2018
@author: lifanhong
"""
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
output = str(x)[::-1]
if output[-1] == '-':
output = '-' + output[:-1]
... |
doc = input()
txt = input()
cnt = 0
if not (txt in doc):
print(cnt)
else:
while(txt in doc):
doc = doc[ doc.find(txt) + len(txt) : ]
cnt += 1
print(cnt) |
import sys
from queue import PriorityQueue
input = sys.stdin.readline
queue = PriorityQueue()
for _ in range(int(input())):
value = int(input())
if value:
queue.put(-1 * value)
elif not queue.empty():
print(-1 * queue.get())
else:
print(0)
|
def gcd(a,b):
while b!= 0:
tmp = a % b
a = b
b = tmp
return a
val = list(map(int, input().split(' ')))
x = val[0]
y = val[1]
res = gcd(x,y)
for i in range(res):
print(1, end='')
|
binary = input()
length = len(binary)
eight_dict = {'000' : '0', '001' : '1', '010' : '2', '011' : '3', '100' : '4', '101' : '5', '110' : '6', '111' : '7'}
while length % 3 != 0:
binary = '0' + binary
length += 1
result = ''
for number in range(0, length, 3):
result = result + eight_dict[binar... |
"""
file: run.py
autor: @David
"""
from misvariables import *
# Uso de condicional simple
# Pedimos las notas
nota = input ("Ingrese la nota 1: \n")
nota2 = input ("Ingrese la nota 2: \n ")
# Transformamos a enteros las notas
nota = int(nota)
nota2 = int(nota2)
# Uso del condicional para evaluar la nota
if not... |
from typing import List
def quick_sort(a:List) -> List:
if len(a) <= 1:
return a
else:
pivot = a[0]
low = [x for x in a[1:] if x <= pivot]
high = [x for x in a[1:] if x > pivot]
return quick_sort(low) + [pivot] + quick_sort(high)
array = [7, 5, 9, 0, 1, 6, 2, 4, 8]
prin... |
#!/usr/local/bin/python
from mathTools import *
#maxInteger = 10
maxInteger = 20
primeList = [2]
while primeList[-1] <= maxInteger:
primeList = nextPrime(primeList)
primeList = primeList[:-1]
print primeList
cumProd = 1
for val in primeList:
cumProd *= val
print 'initial cumultaive product :',cumProd
for i ... |
import unittest
if __name__:
import sys
sys.path.append('..')
from NeuralNetworks import perceptron
class NeuronTests(unittest.TestCase):
def setUp(self):
self.sut = perceptron.Neuron([0,1,1])
def tearDown(self):
pass
def test_should_has_as_many_inputs_as_the_initial_vector_pa... |
#!/usr/bin/env python3
import math
def triangleArea(base, height):
return (0.5 * base * height)
def rectangeArea(width, length):
return (length * width)
def circleArea(radius):
return (math.pi * radius * radius)
def main():
while(True):
userInput = input("Choose a shape (triangle, rectangle... |
dic = {"Nome": '',
"Idade": '',
"Telefone": '',
"Endereço": ''}
def entrada(dic):
for i in dic:
dic[i] = input('%s: ' % i)
print(entrada(dic)) |
# a program that takes every second letter from a given word and stores them
print("Give me a word!")
userInput = input()
print(userInput[::2]) |
class Time:
def __init__(self, h, m, s):
# save the given time
self.h = h
self.m = m
self.s = s
def hours(self):
# return the hour part of the time
return self.h
def minutes(self):
# return the minute part of the time
return self.m
def s... |
from circle import Circle
from rectangle import Rectangle
from point import Point
def main():
points = []
points.append(Point(0,0))
points.append(Point(0,5))
points.append(Point(3,0))
points.append(Point(3,5))
rectangle1 = Rectangle(points)
print("The width of the rectangle is:", rectangle1... |
from vehicle import Vehicle
from values import Terrain
class Plane(Vehicle):
def __init__(self, x, y):
super().__init__(3, x, y)
self.name = "Lentokone"
self.symbol = "L"
def InitAllowedTerrains(self):
''' Määrittää millaisessa maastossa ajoneuvolla voi ajaa. Arvot values.Terra... |
#Faça um programa em Python que recebe um número inteiro e imprime seu dígito das dezenas.
n = input("Digite um número inteiro:")
while n
|
#Escreva um programa que receba um número natural na entrada e imprima n! (fatorial) na saída.
n = int(input("Digite o valor de n: "))
if n == 1:
print(n)
if (n < 0):
print("Números fatoriais devem ser positivos, somente :-(")
if (n == 0):
print(1)
if n > 1:
resu = 0
while n > 1:
if res... |
valor = float(input("Insira o valor total da compra:"))
parcelas = str(input("Insira como será realizado o pagamento:"))
uma = valor / 1
duas = valor / 2
tres = valor / 3
quatro = valor / 4
cinco = valor / 5
parcelas = uma
parcelas = duas
parcelas = tres
parcelas = quatro
parcelas = cinco
print ("Deverá ser pago",parc... |
for x in range(1,101):
if (x%15 == 0):
print "FizzBuzz"
elif (x%3 == 0):
print "Fizz"
elif (x%5 == 0):
print "Buzz"
else:
print x
|
import math
def kotak():
print('Insert the dimmension is multiple of 3 separated by space, ex : 11 33')
row, col = map(int, input('Insert here : ').split())
col_mid = math.ceil(col / 2)
row_mid = math.ceil(row / 2) - 1
data = [[j for j in range(1, col + 1)] for i in range(1, row + 1)]
new_data ... |
""" By JFF. From Markov Project.
This is the main module for markov chain Forgotten Morissey Song. It will:
- Get artist/web
- Check if file input for probalistics exists.
- If not, run fetch_data
- If yes, continue to next
- Setup Markov probalistics
- get complete list of words (unique)
- for each ... |
import PyPDF2
import sys
# 1. Merge various pdf files in a folder
inputs = sys.argv[1:]
def pdf_combiner(pdf_list):
merger = PyPDF2.PdfFileMerger()
for pdf in pdf_list:
print(pdf)
merger.append(PyPDF2.PdfFileReader(open(pdf, 'rb')))
merger.write('merged.pdf')
pdf_combiner(inputs)
# 2. ... |
def solution(participant, completion):
participant.sort()
completion.sort()
answer = participant[len(participant)-1]
for i in range(len(completion)):
if(participant[i] != completion[i]):
answer = participant[i]
break
return answer
def main():
print(solution(["leo... |
'''
输入两棵二叉树A,B,判断B是不是A的子结构。
我们规定空树不是任何树的子结构。
样例
树A:
8
/ \
8 7
/ \
9 2
/ \
4 7
树B:
8
/ \
9 2
返回 true ,因为B是A的子结构。
算法
(二叉树,递归) O(nm)O(nm)
代码分为两个部分:
遍历树A中的所有非空节点R;
判断树A中以R为根节点的子树是不是包含和树B一样的结构,且我们从根节点开始匹配;
对于第一部分,我们直接递归遍历树A即可,遇到非空节点后,就进行第二部分的判断。
对于第二部分,我们同时从根节点开始遍历两棵子树:
如果树B中的节点为空... |
'''
Edit Distance Given two text strings A of length n and B of length m, you
want to transform A into B. You are allowed to insert a character, delete a
character and to replace a character with another one. An insertion costs ci, a
deletion costs cd and a replacement costs cr.
'''
def edit_distance(ar... |
'''
从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
8
/ \
12 2
/
6
/
4
输出:[8, 12, 2, 6, 4]
算法:
1. 我们从root开始按照bfs(宽度优先) 顺序遍历整棵树,首先访问left child, 然后是right child
2. 然后在从左到右扩展第三层节点
3. 一次类推
时间复杂度
BFS时每个节点仅被遍历一次,所以时间复杂度... |
class Solution(object):
"""docstring for Solution"""
def sum(self, arr, val):
arr.sort()
i = 0
j = len(arr) - 1
while (i < j):
if arr[i] + arr[j] == val:
return True
elif arr[i] + arr[j] > val:
j -=1
else:
i +=1
return False
arr = [1,2,31,23,1,4,1,24,5,6,2,2]
s = Solution()
res = s.su... |
# 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 find_path(self, root, path, des):
if not root:
return False
if root == des:
path.appen... |
'''
1.using maximum heap to find top K smallest number
2.using minimum heap to find top K largest number
'''
def adjust_heap(arr, i, length):
tmp = arr[i]
k = 2 * i + 1
while k < length:
#maximum heap
if k + 1 < length and arr[k + 1] > arr[k]:
k += 1
if arr[k] > tmp:
arr[i] = arr[k]
i = k
k = 2 *... |
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low,... |
'''
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
Note:
直接操作链表,merge sort,先局部有序再整体merge。首先对每个部分找到中点,然后对左半部分跟右半部分
分别进行递归merge sort(divide and conquer)
'''
# Definition for singly-l... |
# 101. Symmetric Tree
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
stack = [root.left, root.right]
while (stack):
r = stack.pop()
l = stack.pop()
if not (r or l):
continue
... |
# Все задачи текущего блока решены с помощью генераторов списков!
# Задание-1:
# Дан список, заполненный нежелательными целыми числами.
# Получить новый список, элементы которого будут
# квадратами элементов исходного списка
# [1, 2, 4, 0] -> [1, 4, 16, 0]
array1 = [1, 2, 4, 0]
array2 = [x**2 for x in array1]
print(ar... |
def bigEliment(li):
for i in range(len(li)):
for j in range(i,len(li)):
if li[i]>li[j]:
b = li[i]
break
return b
if __name__ == "__main__":
li = []
print('enter eliments in list\nenter exit when finish!')
while True:
e = input(':')
... |
print ('Hello, who are you? ')
name = input ()
s = name
s.lower ()
s.capitalize ()
name_1 = s.capitalize()
print ('Hello, ' + name_1 + '. It is good to meet you')
|
def ni():
while 1:
nii = input('Enter a word: ')
input_entered = nii.lower()
print(input_entered)
if input_entered == 'ni!':
print('correct')
exit()
else:
print('Incorrect, please try again')
ni() |
#person.py
class Person(object):
def __init__(self,h):
self.height = h
def printHeight(self):
print "Height: ",self.height
def main():
guy = Person(5)
guy.printHeight()
if __name__ == "__main__":
main()
|
from cs1lib import *
from math import cos, sin
class Robot:
def __init__(self, x, y, theta):
self.x = x
self.y = y
self.v = 2
self.w = 1
self.theta = theta
self.image_height = 132
self.image_width = 140
self.radius = 30
def draw_robot(self):
... |
'''
Programmer: Cody McNealy
Last Edited: 05/07/2018
Program: Treasure Generator Functions File
'''
import random
import sys
minorTreasures = "a Ring of Health~a Amulet of Attack~some Boots~some Gloves~a Cape of Origins~a Shortsword~a Longsword~a Broadsword~a Off-hand Shortsword~a Shieldbow~a Crossbow~a Two-Handed Cro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 20 17:49:22 2017
@author: bugs
"""
import re
class Rule:
def __init__(self, string):
self.var = string[0:string.find("->")].strip()
self.replacements = []
start_index = string.find("->") + 2
end_ind... |
"""
создайте класс `Car`, наследник `Vehicle`
"""
from .base import Vehicle
from .engine import Engine
class Car(Vehicle):
engine = None
def __init__(self, weight, fuel, fuel_consumption):
super().__init__(weight, fuel, fuel_consumption)
def set_engine(self, engine: Engine):
self.engine ... |
a = input('Enter the first number')
b = input('Enter the second number')
a,b=b,a
print 'swapped numbers are', a,b
|
months=['Jan','Feb','Mar','Apr']
months.append ('May')
months.append ('July')
print 'Adding May & July', months
months.insert (5,'Jun')
print 'Print current list',months
print 'Index of May is:',months.index ('May')
months.remove ('Jun')
print 'Jun is removed.The new list is',months
months.sort ()
print 'Sorted list i... |
from collections import defaultdict
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rowMap=defaultdict(list)
columnMap=defaultdict(list)
boxMap=defaultdict(list)
def recursion(row,index):
nonlocal flag
if not flag:
... |
import itertools
def answer(x, y, z):
'''1 <= x, y, z <= 99'''
valid_dates = set("%02d/%02d/%02d"%t for t in itertools.permutations([x, y, z], 3) if is_valid_date(*t))
if len(valid_dates) == 0 :
return "Invalid"
elif len(valid_dates) == 1 :
return list(valid_dates)[0]
else :
... |
#analise se uma frase eh um palindromo (ler de tras pra frente o mesmo de frente pra tras)
x = str(input('Digite uma frase: ')).strip().upper()
words = x.split() #dessa maneira tiro os espacos entre palavras
sentence = ''.join(words)
inverse = ''
for l in range(len(sentence) - 1, -1, -1): # uma maneira mais simples eh ... |
# dado um angulo, descubra o seno, coseno e tangente dessa merda
import math
ang = float(input('Digite o angulo: '))
sin = math.sin(math.radians(ang))
cos = math.cos(math.radians(ang))
tan = math.tan(math.radians(ang))
print('O angulo de {} tem o SENO de {:.2f}\nO COSSENO de {:.2f}\nE a tangente de {:.2f}'.format(ang, ... |
#calcule idade atraves de ano de nascimento e calcule se deve ou nao se alistar ou se ja passou do tempo
from datetime import date
today = date.today().year
dob = int(input('Qual o ano de nascimento?: '))
age = today - dob
print('Quem nasceu no ano de {} tem {} anos no ano atual de {}'.format(dob, age, today))
if age <... |
#coloque 3 medidas e analise se pode formar um triangulo. existencia de triangulo se baseia em um dos segmentos tem de ser menor que os outros 2
print('-=-' * 20)
print('ANALISADOR DE TRIANGULO')
print('-=-' * 20)
a = float(input('Digite o valor da primeira reta: '))
b = float(input('Digite o valor da segunda reta: '))... |
#verifique se existe Silva dentro de um nome completo/frase
name = str(input('Digite seu nome completo: ')).upper().strip().split()
print('Existe "Silva" no seu nome?: {}'.format('SILVA'in name))
|
# tabuada refeita com laco for do ex 09
n = int(input('Digite um numero pra sua tabuada: '))
for c in range(1, 11):
print('{} x {:2} = {}'.format(n, c, n*c))
#comparacao com ex09
'''n = int(input('Digite um valor: '))
print('Levando em consideracao que todo numero multiplicado por zero sempre sera zero:\n{... |
# escreve um programa que pergunte a qtdade de dias e km rodados de um carro alugado e de o valor a ser pago. 60/dia e 0,15/km
x = int(input('Insira o valor de dias em que o carro foi alugado: '))
y = float(input('Insira qtos Km foram rodados nesses dias de aluguel: '))
z = (x * 60) + (y * 0.15)
print('De acordo com a ... |
# ex 5 - faca um programa que leia um numero inteiro, e mostre na tela o numero, o antecessor e o sucessor
x = int(input('Digite um valor:'))
a = x - 1
s = x + 1
print('Baseado no valor {}, seu antecessor eh {} e seu sucessor eh {}'.format(x, a, s))
# vc tb pode fazer tudo com apenas uma variavel e dentro do .format co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.