text
stringlengths
37
1.41M
#find the union and intersection of two sorted array #brute force def find_union_intersection_brute(arr1, arr2): inter=[] for i in arr1: if i in arr2: inter.append(i) return inter, arr1+arr2 #ths doesnt handle dups if found in any array def find_union_intersection(arr1, arr2): l=0 ...
# iterative solution #O(N) def reverse_iterative(array): size = len(array) start=0 end=size-1 while start<end: array[start],array[end] = array[end],array[start] start+=1 end-=1 return array # recursive solution #O(N) def reverse_recursive(array, start, end): if start>=en...
import datetime currentDate = datetime.datetime.now() while True: deadline= input ('Plz enter your date of birth (dd/mm/yyyy) ') try: deadlineDate= datetime.datetime.strptime(deadline,'%d/%m/%Y') break except ValueError: print ("Invalid input please try agai...
#print power of 2 n=0 total=0 while n <= 11 : print ("Power of 2 is {} " .format(total**2)) total=(n) n += 1 #for loop for i in range(1, 11): print ("Power 2 of is : " +str((i,i**2)))
#input a number, calculate grade #A 90-100% #B 80-90% score =int(input("Please enter your score from (0-100):")) if 90< score <=100: print("Your score is: A ") elif 80< score <89: print("your score is: B") elif 70< score <79: print("Your score is: C") elif 60< score <69: print("your score is D , k...
#Inheritance - Is- A relation #Class Mammals #Class Man #Aggregation - Has -A relation #Aggregation implies a relationahip where the child can exist independently of the parent #Example: Class(parent) and Student(child). #Delete the Class and the Students still exists. #Composition - Has -A relation #Composition impl...
import pygame import sys import numpy import math import time import random import Controller1 import controllerleft import test_opponent #MAIN script for self made robocup simulation. Main idea is that a controlcode scans the field and assigns requests the bots to go to a position,rotation,and action. # the classes i...
list_names = list(map(str, input().split("-"))) # split by "-" short_variation = list(map(lambda name: name[0], list_names)) # get first letter(s) from list of names output = ''.join(short_variation) # convert list to string print(output)
#Aug 21, 2019 #Michael Zabawa #Python Assignment 2 for NCSU from TicTacToeClasses import * ################################################################################ #driving function def main(): print("\n \nWould you like to play\nTic-Tack_Toe?") play = input("Type (Y)es or (N)o: ") play = str.uppe...
""" This file contains the different clustering routines. """ import numpy as np from .helpers import compute_correlation_coefficients, normalize_data def cluster_by_correlation(correlation_matrix): """ Performs a single renormalization step (clustering neurons into pairs). The clustering is performed based...
for a in(1,2): for b in (3,5): if a*b>2: c=True print(a*b) if c: print("r")
#!/usr/bin/env python3 import math number = 600851475143 # solution 1 def is_prime(n): for i in range(2, int(n**0.5)+1): if n % i == 0: return False return True limit = int(math.sqrt(number)) for i in range(limit, 2, -1): if is_prime(i) and not number % i: print(i) break
#!/usr/bin/env python power = 1000 # solution 1 num = 2**power s = 0 while num > 0: s += num % 10 num = num // 10 print(s)
import sys def bubbleSort(arr): for i in range(0, len(arr)): for j in range(0, len(arr)-i-1): if(arr[j] > arr[j+1]): tmp = arr[j] arr[j] = arr[j+1] arr[j+1] = tmp return arr def main(): try: f = open(str(sys.argv[1]),'r') ...
#example 1 def gen_print(n): num = 0 while num < n: print(num) num += 1 (gen_print(5)) #example 2 def gen_print(n): num = 0 while num < n: if num%2==0: print(num) num+=1 else: num += 1 (gen_print(5))
from Expression import Expression class Equation: def __init__(self, lhs, rhs): self.lhs, self.rhs = lhs, rhs def __str__(self): return str(self.lhs) + " = " + str(self.rhs) def debug_string(self): return self.lhs.debug_string() + " = " + self.rhs.debug_string() # ~~~~~~ TESTI...
class Greetings: def __init__(self, name): self.name = name def display(self): print(f'Hello there {self.name}.') if __name__ == '__main__': i = input('Enter your name: ') g = Greetings(i) g.display()
from math import sqrt import numpy as np def main(): import pandas as pd data = pd.read_csv("alldata.csv") y_arr = data['Price'] x_arr = data['Sentiment'] date_arr = data['Date'] # normalize BTC price from sklearn.preprocessing import MinMaxScaler mmscaler = MinMaxScaler(feature_rang...
# #----------1. define a simple function--------- # # 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()。 # # 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。 # # 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。 # # 函数内容以冒号起始,并且缩进。 # # return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。 # # def 函数名(参数列表): # # 函数体 # # def show(stuff): # print("show stuff:...
#-----------1. 字符串操作-------- mystr = "hello and world and bitch" #find("str"), 从左向右找 能找到返回下标,否则返回-1 #rfind("str"),从右向左找 能找到返回下标,否则返回-1 #index("str"),从左向右找 能找到返回下标,否则发生错误 #rindex("str"),从右向左找 能找到返回下标,否则发生错误 #count("str"),统计字符串中含有str的个数 #replace("source", "destination"[, count]),返回字符被替换后的新的字符串,替换count个 #split(sep=None...
# #-------1. traverse a list--------- # nums = [11, 22, 33, 44, 55] # # while # len = len(nums) # i = 0 # while i < len: # print(nums[i], end = " ") # i += 1 # print("") # # # for # for num in nums: # print(num, end = " ") # print("") # #---------2. for - else--------- # nums = [11, 22, 33] # #nums = [] # ...
import calendar import sys '''name=input("enter your name\n") for x in range(1,9): if name.isalpha()==True or ' ' in name: if len(name)>=3: pass break else: print("error") name=input("enter your name\n") else: print("error") name=in...
import re timeStr = "^(?P<hour>[0-2]?[0-3]):(?P<minute>[0-5]?[0-9]):(?P<second>[0-5]?[0-9])$" #date = "^(?P<month>[0-3]?[0-9])/(?P<day>[0-3]?[0-9])/(?P<year>[0-9]{4})$" dateStr = "^(?P<year>[0-9]{4})\-(?P<month>[0-3]?[0-9])\-(?P<day>[0-3]?[0-9])$" date1 = "2009-12-12" match = re.search(dateStr, date1) if match: ...
def main(): L=[1,3,4.5,"hi"] # تستخدم for loop لطباعه كل عنصر قي سطر في for item in L: print(item) if __name__ == '__main__': main()
#Tasks task1 = {'todo': 'call John for AmI project organization', 'urgent': True} task2 = {'todo': 'buy a new mouse', 'urgent': True} task3 = {'todo': 'find a present for Angelina’s birthday', 'urgent': False} task4 = {'todo': 'organize mega party (last week of April)', 'urgent': False} task5 = {'todo': 'book summer ho...
def get_bin_from_user(): bin_string = input('请输入一个二进制数:') while True: is_valid_bin = True for bin_number in bin_string: if bin_number not in ['0', '1']: is_valid_bin = False if is_valid_bin: return bin_string else: bin_string = ...
alphabet = ["a", "b", "c", "d"] l = len(alphabet) cypher = 1 def encode(word): position = 0 res = "" for char in word: if char == alphabet[position]: position += cypher while position >= l: position -= l res += alphabet[position] ...
""" Module for currency exchange This module provides several string parsing functions to implement a simple currency exchange routine using an online currency service. The primary function in this module is exchange. Author: Oscar So (ons4), Jee-In Lee (jl3697) Date: September 11, 2019 """ import json import i...
# ''' Problem Given: A file containing at most 1000 lines. Return: A file containing all the even-numbered lines from the original file. Assume 1-based numbering of lines. Sample Dataset Bravely bold Sir Robin rode forth from Camelot Yes, brave Sir Robin turned about He was not afraid to die, O brave Sir Robin And ...
def print_monthly_savings_accumulation(rm, amount_saved, initial_balance = 0): bal = initial_balance # interest = balance * monthly interest rate. print("Month Interest Amount Balance") for i in range(12): mon_int_earn = bal*rm bal+=amount_saved bal+=mon_int_ea...
def print_rect(ch,width,height): for i in range(height): print ch*width def print_upper_left_triangle(ch,height): for i in range(height): print ch*(height-i) def print_upper_right_triangle(ch, height): #broken for i in range(height): print (' '*i)+(ch*(height-i)) def print_low...
# a01_four_fours.py - Assignment 1 # your name: Sam Murray # your email: smur@bu.edu # Computes the integers 0 through 4 using exactly 4 fours, and a # creative combination of arithmetic operators. # # this statement creates a variable called 'zero' which is the result of the expression 4 + 4 - 4 - 4 zero = 4 + 4 - 4...
""" Implementation of a Fibonacci generator as a class """ class FibGen: def fibn(self, n): a, b = 0, 1 for i in range(n): a, b = b, a+b return b def __getitem__(self, n): return self.fibn(n)
""" Find the value and position of the largest number in a list. Implemented using range() and len() built-ins. """ numlist = (1000,0.22, 34, 4, -12, 13.01, 140.45, 111) maxnum = numlist[0] maxpos = 0 for idx in range(len(numlist)): if numlist[idx] > maxnum: maxnum = numlist[idx] maxpos = idx...
import decimal D = decimal.Decimal amount = D(input("enter amount: ")) print(amount) for i in map(D,['20', '10', '5', '1', '0.25', '0.1', '0.05', '0.01']): print(' {} ${:.2f} bill/coin'.format(amount//i, i)) amount = amount % i
# coding=UTF-8 from math import exp, sqrt import sys h = 0.001 def eprint(*args, **kwargs): print(*args, file=sys.stderr, ** kwargs) exit(84) def f(t, ducks): """ Function :param t: :param ducks: :return: """ a = ducks return a * exp(-t) + (4 - 3 * a) * exp(-2 * t) + (2 * a...
import pygame pygame.init() import numpy as np import matplotlib.pyplot as plt class Neuron: def __init__(self): self.balance = 0.7 self.power = np.random.random() self.limit = 0.6 self.braking_speed = 0.2 self.acceleration_speed = 0.1 self.input_signal = np.zeros...
num1 = 2 num2 = 3 num3 = .25 print(num1 + num2) print(num1 * num2) print(num1 - num2) print(num2 / num1) print(num1 + num3) print(num1 * num3) print(num1 - num3) print(num2 / num3) print(num2 % num1) num1 += 2 print(num1) num1 *= 2 print(num1) num1 -= 2 print(num1) num1 /= 2 print(num1)
#!/usr/bin/env python def ispalindrome(s): length = len(s) for i in range(length/2): if s[i] != s[length - 1 - i]: return False return True
# # Your code here with open(r"C:\Users\galfa\Desktop\CODING\Lambda\unit-6\week-1\cs-module-project-hash-tables\applications\histo\robin.txt") as f: words = f.read() def histogram(words): filtered_chars = '":;,.-+=/\\|[]{}()*^&' filtered_string = ''.join(filter(lambda x : x not in filtered_chars, wor...
# Aloha.py, Python simulation example: a form of slotted ALOHA # here we will look finite time, finding the probability that there are # k active nodes at epoch m # usage: python Aloha.py s p q m k import random, sys class node: # one object of this class models one network node # some class variables s = ...
# tic tac toe game # without design, print x and o. a1 = "_" a2 = "_" a3 = "_" b1 = "_" b2 = "_" b3 = "_" c1 = "_" c2 = "_" c3 = "_" def grid(): print(" 1 2 3") print(f"A {a1} {a2} {a3}") print(f"B {b1} {b2} {b3}") print(f"C {c1} {c2} {c3}") def find_loc_user(): ...
# Head ends here from collections import defaultdict def next_move(posr, posc, board): trash = [] for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == "d": if (i,j)==(posr,posc): print("CLEAN") return ...
#!/usr/bin/env python3 """Find the proportion of non-null values in each column of a CSV.""" import click import pandas as pd @click.command() @click.argument('input-file', default='-', type=click.File('r')) @click.argument('output-file', default='-', type=click.File('w')) def null_proportion(input_file, output_file...
import sys import heapq import unittest class HuffmanData(object): """ Description: Object to store every character and its associated Huffman code """ def __init__(self, c): self.c = c self.code = None class HuffmanNode(object): """ Description: Adds frequency context to huffm...
import unittest import random def _get_min_max(ints, left, right): """ Recursive helper to find min and max from left and right halves and to compare the two min/max Args: ints(list): list of integers containing one or more integers left(int): Left index within which to look for min/max ...
''' Örnek 5.5: 100’lük sisteme göre girilen başarı notunu harfli sisteme dönüştüren programı kodlayalım. ''' Nt = int (input("0-100 arası not gir.:")) if Nt>=90 and Nt<=100: #100<=Nt<90 print("AA") elif Nt>=80 and Nt<90: print("BA") elif Nt>=70 and Nt<80: print("BB") elif Nt>=60 and Nt<70: print("CB") e...
''' Örnek 10.3: Kullanıcının girdiği bir cümleyi listeye dönüştüren ve bu listeden sesli harfleri çıkaran (sessiz harflerden bir liste oluşturan) programı kodlayalım. ''' L = [] #boş liste cumle=input('Bir Cümle Giriniz.:') L=list(cumle) #listeye dönüştür print ("Sessiz Harfler Listesi.:") for k in L: if k in 'aeıi...
''' Örnek 20.7: Hilesiz bir madeni para N=10 defa atıldığında 7 kere ‘tura’ gelmesinin olasılığı nedir? Programda ‘tura’ durumunu ‘1’, ‘yazı’ durumunu ‘0’ ile ifade edersek, toplam N atışta bu değerlerin gelme olasılığını inceleyen programı kodlayalım. ''' from random import * from math import * from statistics import ...
''' Örnek 23.15: 2012-2020 yılları arasındaki aktif Facebook kullanıcı sayısını gösteren tabloyu nokta (scatter) ve çizgi (plot) grafikleri ile birlikte gösteriniz ''' # %% import numpy as np import matplotlib.pyplot as plt yil = np.arange(2012, 2021) #2021 dahil değil kSay = [1056, 1228, 1393, 1591, 1860, ...
''' Örnek 4.5: Girilen üç sayı içerisinden en büyük olanı ekranda gösteren programı kodlayalım. ''' a = int (input("1.sayı.:")) b = int (input("2.sayı.:")) c = int (input("3.sayı.:")) enb = max (a, max(b,c)) print ("En büyüğü.:",enb)
''' Örnek 9.14: Sezar Şifrelemesi Konsoldan girilen bir kelimedeki her harfi, o harften sonra 3 harf atlayarak (gerektiğinde ‘Z’ den ‘A’ ya atlayacak şekilde) şifreleyen ve şifrelenmiş kelimeyi ekranda gösteren programı kodlayınız. ''' #Sezar fonksiyonu def sezar(s): tKar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" donus = ...
''' Örnek 4.4: Dik kenar uzunlukları kullanıcı tarafından girilen bir dik üçgenin hipotenüsünü, Pisagor teoremine göre hesaplayan programı kodlayalım. ''' b = int (input("1.dik kenar.:")) c = int (input("2.dik kenar.:")) a = (b**2 + c**2)**0.5 print ("Hipotenüs.:", a)
''' Örnek 14.3: Verilen listeden sayı ile başlayan verileri çeken (alan) programı kodlayınız. ''' import re liste = ["1","22","A1", "333", "A2A"] regex = r"\d+" for s in liste: if re.match(regex,s): print(s)
''' Örnek 12.3: Daha önce Örnek 12.2’de verilen Fibonacci serisini hesaplayan programı yield komutu ile kodlayalım. ''' def fib(max): a, b = 0, 1 #a=0; b=1 oldu while a < max: yield a #a değerini döndürür #a değerini test amaçlı yazdıralım print ("a:",a) # a = b; b = a + b yer de...
''' Örnek 8.6 (OKEK Hesabı): Rastgele üretilen iki sayının en küçük ortak bölenlerini (OKEK) bulan programı kodlayalım. ''' #OKEK(a,b) = a*b / gcd(a,b) ile hesaplanabilir from random import * from math import * #Ana program a = randint(1,100) b = randint(1,100) obeb = gcd(a,b) #obebini al okek =(a*b)/obeb #okekini al ...
''' Örnek 2.1: İki sayının toplamını hesaplayan basit matematiksel işlemi yapalım. ''' A = int (input("1.sayıyı gir:")) #hatalı kullanım: A = input("1.sayıyı gir:") B = int (input("2.sayıyı gir:")) T = A + B print ("Toplam= ", T)
''' Örnek 21.3. (Matrise (1D >> 2D ) Dönüştürme): “d= [1,2,3,4,5,6,7,8,9,10,11,12]” şeklindeki tek boyutlu diziyi 4*3 lük bir matrise dönüştüren programı yazınız. ''' import numpy as np #Tek boyutlu d dizisi (1-12) d = np.arange (1, 13) # d dizisi 4*3 lük matrise dönüştü. A = d.reshape(4,3) print (A)
''' Örnek 17.8: JSON formatında veri oluşturup, bu veriden istenilen değerleri alan programı kodlayalım ''' import json #json formatına dönüşebilecek veri #sözlük yapısına benzer şekilde tasarlanır veri = '''[ {"plaka" : "01", "il" : "Adana" }, {"plaka": "24", "il" : "Erzincan" } ]''' #'.loa...
''' Örnek 7.2: 4 işlem yapan menülü basit bir hesap makinesi programını kodlayalım. ''' #Menü fonksiyonu def menu(): print ("[+]-Toplama\n") print ("[-]-Çıkarma\n") print ("[*]-Çarpma\n") print ("[/]-Bölme\n") #Hesapla fonksiyonu def Hesapla (a, b, op): if (op == '+'): return a+b if (op == '-'):...
''' Örnek 9.1: Bir stringin içeriğini (belli bir karakterden sonrasını değiştiren) güncelleyen programı kodlayalım. ''' ad = 'Galata Saray' yeniAd= ad[:7 ] + 'Bahçe' #Alternatifi: #yeniAd= ad.replace( 'Galata Saray', 'Galata Bahçe') print ("Adres Güncellendi: ", yeniAd)
''' Örnek 13.7: Soyut sınıf ve metot kavramını bir önceki örnek uygulama üzerinden açıklayalım. ''' from abc import * class Pizza(ABC): #üst soyut sınıf icerik = ['Peynir', 'Zeytin'] @classmethod #sınıf metodu @abstractmethod #soyut metot def getMalzeme(cls): return cls.icerik #DiyetPizza ...
''' Örnek 8.8 (Seri toplamı): f(x) = x + x2 + x3 + x4 + ……… + xn şeklinde verilen serinin toplamını bulan programı kodlayalım. ''' from math import * X = int (input ("X değeri.:")) Fx = 0 #seri toplam değişkeni N = int (input ("Seri terim sayısı.:")) for us in range (1, N+1): Fx = Fx + pow(X, us) print ("Toplam.:"...
''' Örnek 13.6: Soyut sınıf ve @abstractmethod kullanımını Pizza örneği üzerinden açıklayan programı kodlayalım. ''' from abc import * class Pizza(ABC): #üst soyut sınıf icerik = ['Peynir', 'Zeytin'] @abstractmethod def getMalzeme(self): #soyut metot pass #Eşdeğeri: return #DiyetPizza sınıfı P...
''' Örnek 15.14: String veri tipinde tarih verilerinin tutulduğu bir listeyi tarih-zaman tipinde farklı saat dilimlerine (“Tokyo”, “İstanbul” gibi) dönüştüren uygulamayı kodlayınız ''' import pendulum tarihList = ["01.01.2020","01.02.2020", "01.03.2020","15.07.2021"] #bölgesel tarih-saat formatında listele b = [] t = [...
# -*- coding: utf-8 -*- """ Created on Mon Mar 13 12:40:23 2017 @author: dewandaru@gmail.com """ from itertools import product import pandas as pd import numpy as np from pandas import DataFrame ''' Original problem: Monty Hall hosts a quiz, in it hidden one prize behind one door. There are three doors: A,B,...
# Create a class called NumberSet that accepts 2 integers as input, and defines two instance variables: num1 and num2, which hold each of the input integers. Then, create an instance of NumberSet where its num1 is 6 and its num2 is 10. Save this instance to a variable t. class NumberSet: def __init__(self, num1, n...
def square(x): return x*x L = [square, abs, lambda x: x+1] print("****names****") for f in L: print(f) print("****call each of them****") for f in L: print(f(-2)) print("****just the first one in the list****") print(L[0]) print(L[0](3)) # 1. Below, we have provided a list of lists. Use indexing t...
class Produto: def __init__(self, id, nome, descricao, valor): if id != 0: self.id = id else: raise ValueError('O identificador deve ser diferente de zero') self.nome = nome self.descricao = descricao self. valor = valor class Endereco: def __ini...
''' Copyright: Mohammad Safeea, 9-Oct-2019 About: fadingBlinky.py is a microPython script for ESP8266. It is used to blink the built-in led (with fading effect) using PWM signal. ''' from machine import Pin from machine import PWM from time import sleep # Initiate output pin LedBuiltin=2 p=Pin(LedBuilti...
import turtle #turtle.shape('turtle') triangle=turtle.clone() triangle.shape('triangle') #triangle.goto(0,100) #triangle.goto(100,0) #triangle.goto(0,0) turtle.shape('turtle') square=turtle.clone() square.shape('triangle') square.goto(0,100) square.goto(100,0) square.stamp() square.goto(0,0)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 26 09:59:07 2020 @author: Elzette """ import numpy as np def get_neighbours(a): x = a[0] y = a[1] return [[x-1,y-1],[x-1,y],[x-1,y+1],[x,y+1],[x,y-1],[x+1,y-1],[x+1,y],[x+1,y+1]] def is_in(position): #This is a cheat x = int(a...
# int, float, complex a=3 b=2.5 c=5+8j print(a, type(a)) print(b, type(b)) print(c, type(c)) # string name="aushafy" print(name, type(name)) # boolean # also implement typeCasting isName=bool(name) print(isName, type(isName))
''' Find the sub array which produces the largest sum ''' def largestSumOfSubArray(arr): current_max = None global_max = None if len(arr) > 0: current_max = arr[0] global_max = arr[0] for i in range(1, len(arr)): if current_max < 0: ...
# Let us first create the required node and # then created the linkedListStructure from it class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printNodes(self): temphead = self.head in...
def update_dictionary(d, key, value): # if key in d: # проверка наличия ключа в словаре(в случае соответствия проваливаюсь) d[key].append(value) # добавление элемента в существующие значение по переданному ключу elif key not in d: # если в наличии...
''' В первой строке дано три числа, соответствующие некоторой дате date -- год, месяц и день. Во второй строке дано одно число days -- число дней. Вычислите и выведите год, месяц и день даты, которая наступит, когда с момента исходной даты date пройдет число дней, равное days. Примечание: Для решения этой задачи испол...
a = int(input()) b = int(input()) x1 = a if a == b: print(a) elif a % b == 0 or b % a == 0: if a > b: print(a) else: print(b) else: while x1 % b != 0: x1 += a if x1 % b == 0: print(x1)
f = float(input()) s = float(input()) o = input("") if (o == '/' or o == 'mod' or o == '%' or o == 'div' or o == '//') and s == 0: print("Деление на 0!") elif o == '+': print(f + s) elif o == '-': print(f - s) elif o == '*': print(f * s) elif o == '/': print(f / s) elif o == 'mod' or o == '%': p...
''' Вам дана последовательность строк. Выведите строки, содержащие "cat" в качестве слова. Примечание: Для работы со словами используйте группы символов \b и \B. Описание этих групп вы можете найти в документации. Sample Input: cat catapult and cat catcat concat Cat "cat" !cat? Sample Output: cat catapult and cat "cat"...
import math for n in range(2, 250, 2): x=pow(2,-n) print(n,"\t", math.sqrt(pow(x,2)+1)-1,"\t",x**2/(math.sqrt(pow(x,2)+1)+1))
class Car: def __init__(self, name, company, year, price): self.price = price self.name = name self.company = company self.year = year self.owner = None def print_details(self): print('name: ' + self.name + '\tyear: ' + str(self.year) + '\tprice: ' + str...
# If file name does not exist? # If a path is not valid # If a key is not valid # import os class ConfigKeyError(Exception): def __init__(self, this, key): self.key = key self.keys = this.keys() def __str__(self): return 'key "{}" not found. Availabe keys: ({})'.format(se...
import math class PrimeCounter: def __init__(self, max_number): self.max_num = max_number self.prime_set = [] # self.number_set is a Bool list where all==True and it's length==max. By the end, only Primes will still==True self.number_set = [True for i in range(self.max_num+1)] #Thi...
def temp_converter(): temp_value= float(raw_input("Please enter the temperature value:")) conversion = raw_input("Enter F if converting to fahrenheit and C to celsius: ") n= int(raw_input('Enter the value of n:')) while(n>0): n=n-1 if(conversion=='F'): intermediate = float((1...
""" Exercicio 27 - Escreva um programa que, dada a idade de um nadador, classifique-o em uma das categorias. Infantil A - Idade (5 a 7) Infantil B - Idade (8 a 10) Juvenil A - Idade (11 a 13) Juvenil B - Idade (14 a 17) Sênior - Idade (Maiores de 18 anos) """ class Nadador: def __init__(self, idade): sel...
""" Exercicio 10 """ sexo = input("Digite seu sexo M/F: ") sexo = sexo.upper() altura = float(input("Digite sua altura: ")) if sexo == 'M': print(f"peso ideal = {72.7*altura-58}") elif sexo == 'F': print(f"Peso ideal = {62.1*altura-44.7}") else: print("sexo informado não esta definido.")
""" Exercicio 32 - Escreva um programa que leia o código do produto escolhido do cardápio de uma lanchonete e a quantidade. O programa deve calcular o valor a ser pago por aquele lanche. Considere que cada execução somente será calculado um pedido. O cardapio da lanchonete segue o padrão abaixo: Produto -------- Codig...
""" Exercicio 14 """ import sys nota_final = 0 i = 0 while i < 3: nota = float(input("informe a nota: ")) if 0 <= nota <= 10: i = i + 1 if i == 1: nota_final = nota_final + nota * 2 elif i == 2: nota_final = nota_final + nota * 3 else: nota_fi...
""" Exercicio 39 - """ salario = float(input("Digite o salario do funcionario: ")) tempo = int(input("Digite o tempo de serviço desse funcionario em ano(s), 0 caso ainda sejam meses: ")) if salario <= 500: salario = salario * 1.25 elif salario > 500 and salario <= 1000: salario = salario * 1.20 elif salario ...
import time def timeit(method): def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() print '%2.2f sec' % \ (te-ts) return result return timed class Timer(object): def __init__(self): self.startTimes = {} self....
#WRITE YOUR CODE IN THIS FILE #define function #add parameter def factorial(x): y = 1 for i in range (1, x + 1): y = i * y return y #run function print(factorial(5))
from random import choice import matplotlib.pyplot as plt class RandomWalk(): """"一个生成随机漫步数据的类""" def __init__(self, num_points=5000): """"初始化随机漫步的属性""" self.num_points = num_points # 所有随机漫步都始于(0, 0) self.x_values = [0] self.y_values = [0] def get_step(self): ...
from shape import Shape from labeling import Labeling class Square(Shape): def __init__(self, canvas, name, top_left, bottom_right, color='black'): super().__init__(name, canvas, color) self.start = top_left self.end = bottom_right # Labelingクラス集約(コンポジション) self.labeling = La...
x = 8 if x>5: print("The vaue is greater than 5") else: print("The value is smaller")
def add(a,b): m=a+b print(m) def prime(i): fact=0 for j in range(1,i+1): if i%j==0: fact=fact+1 if fact==2: print("true") else: print("false") def prime_factors(n): for i in range(1,n+1): if n%i==0: prin...
#TODO: how to do optional arguments? import os, sys import Image import shutil from directory_walker import DirectoryWalker def check_image_sizes(images_dir, w, h, out_dir=''): ''' Checks all the images inside images_dir, and compares their dimensions to width and height. If an image is found whose d...
from collections import defaultdict def iterable(obj): try: iter(obj) except: return False return True flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x] def group_count(list): d = defaultdict(int) for key in list: d[key] += 1 return d
import glob import cv2 import matplotlib.pyplot as plt import numpy as np # utility function to show an image in a separate window def sh(img, title="img"): cv2.imshow(title, img) cv2.waitKey(0) # utility function for plotting a greyscale image inline def plotG(img): plt.imshow(cv2.cvtColor(img, cv2.CO...
''' Created on 13 May 2016 @author: Sam ''' # Python 3.5 if __name__ == '__main__': cipher = input() newstr = "PER" days = 0 for eachchar in enumerate(cipher): if eachchar[1] != newstr[eachchar[0] % 3]: days += 1 print(days)