text
stringlengths
37
1.41M
# LEVEL 4 # http://www.pythonchallenge.com/pc/def/linkedlist.php # 12345 # 44827 # 45439 # 94485 # 72198 # http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345 # and the next nothing is 44827 import re import urllib.request nothing = '12345' finish = False while not finish: response = urllib.request...
# LEVEL 28 # http://www.pythonchallenge.com/pc/ring/bell.html from PIL import Image img = Image.open('data/bell.png') R, G, B = 0, 1, 2 w, h = img.size # w, h = 20, 20 print(img.mode) print(img.size) print(img.info) # the picture shows vertical stripes, let's try the horizontal differences by pairs for y in range(h)...
"""RL Policy classes. """ import numpy as np import attr import random class Policy: """Base class representing an MDP policy. Policies are used by the agent to choose actions. Policies are designed to be stacked to get interesting behaviors of choices. For instances in a discrete action ...
fname=input("enter file name") fopen=open(fname) dic=dict() for line in fopen: words=line.split() for word in words: dic[word]=dic.get(word,0)+1 highestcount=0 highestword=None for k,v in dic.items(): if v>highestcount: highestcount=v highestword=k
def get_name(): name = input("What's your name? ==> ") return name def greet_name(your_name): print("Hello, %s!" % your_name)
def part_one(data): expenses = strings_to_integers(data) first, second = find_two_sum(expenses, 2020) return first * second def strings_to_integers(data): return list(map(int, data.split())) def find_two_sum(integers, target_sum): integers = sorted(integers) low_index = 0 high_index = -1 ...
#Uma escola te contratou para desenvolver um programa em Python para que o #professor gerencie as notas de seus alunos. Seu programa deve apresentar o seguinte #menu: #0. Sair #1. Exibir lista de alunos com suas notas (cada aluno tem uma nota) #2. Inserir aluno e nota #3. Alterar a nota de um aluno #4. Consultar nota d...
#Faça um programa que leia dez conjuntos de dois valores, # o primeiro representando o número do aluno e o segundo representando a sua altura em centímetros. # Encontre o aluno mais alto e o mais baixo. Mostre o número do aluno mais alto e o número do aluno mais baixo, junto com suas alturas. num_aluno = [] altura_...
class conta(): def __init__(self,titular, saldo): self.titular = titular self.saldo = saldo def depositar(self,valor_deposito): self.saldo = self.saldo + valor_deposito def sacar(self, valor_saque): if valor_saque > self.saldo: print('saldo insuficiente'...
#Crie um programa onde você cadastre a data de nascimento (dd/mm/aa) de algumas #celebridades em um dicionário. Ao escolher uma celebridade, seu programa deve #retornar a data completa. Não esqueça de validar se a celebridade escolhida está #presente em seu dicionário. celebridades = {'Albert Eisntein': '14/03/1979',...
#08 - Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionário. # Se por acaso a CTPS for diferente de 0, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente , # além da idade, com quantos anos a pessoa vai se aposentar. Consid...
#Escreva um programa que determine todos os números de 4 algarismos que possam ser separados em dois números de dois algarismos que somados e # elevando-se a soma ao quadrado obtenha-se o próprio número. for x in range(1000,10000): n1 = x // 100 n2 = x % 100 if(n1+n2)**2 == x: print(x)
def most_prolific(dict): year = [] occurences = {} maxnumber = 0 for items in dict.values(): year.append(items) # print(year) for y in year: if y in occurences: occurences[y] = occurences[y] + 1 else: occurences[y] = 1 for o in occurences: ...
#find maximum profit of the stock prices stock_prices=[23,44,53,11,2,3,178,98] #21+9+1+175 profit=0 for i in range(1,len(stock_prices)): if stock_prices[i]>stock_prices[i-1]: profit+=stock_prices[i]-stock_prices[i-1] print(profit)
numbers1 = [1,2,5,7]; numbers2 = [2,3,7,9]; for num in numbers1: if num in numbers2: print(str(num) + "在numbers中"); else: print(str(num) + "不在在numbers中");
# 不可变的列表称为元组 areas = (10,20); print(areas[0]); print(areas[1]); # area[0] = 1; print(areas[0]) for val in areas: print(val); # 区别Java的final 修饰变量 ages = (22,23); print(ages); ages = (30,32); print(ages);
# Python # By Kulter Ryan # https://github.com/kulterryan/ # Calculating Download Speed of A File # Last Edit: 09/04/2021 # import Libraries import time # Welcome Screen print("Hi There") print("Download Time Calculator") print("** Only 'mbps' to 'MBps' is currently available. ** ") # Input Screen downloadspeed = ...
import copy import gc class AppendException(Exception): pass class ForEachException(Exception): pass class RecordKeyError(Exception): pass class Store: """ This is the class for stores in the database Attributes: store (dict({string: string | dict | list)): The records stored i...
def twoCitySchedCost(costs: [[int]]) -> int: sum=0 sorted_cost=sorted(costs,key=lambda x: x[0]-x[1]) for i in range(len(costs)): if(i<len(costs)//2): sum+=sorted_cost[i][0] else: sum+=sorted_cost[i][1] return sum print(twoCitySchedCost([[10,20],[30,200],[400...
class Trie_Node: def __init__(self): self.endofword=False self.children={} class Trie: def __init__(self): """ Initialize your data structure here. """ self.root=Trie_Node() def insert(self, word: str) -> None: """ ...
def arrangeWords(text) -> str: words = text.split() str=" " words.sort(key=len,reverse=False) return (str.join(words).capitalize()) # for w in words: # print(w) print(arrangeWords("Leetcode is cool"))
from tkinter import * from tkinter import messagebox as ms import sqlite3 win = Tk() win.geometry('800x800') win.title("Login Form") #field for gui UserName=StringVar() Password=StringVar() def database(): un=UserName.get() print(un) ps=Password.get() print(ps) #connection...
#!/usr/bin/env python # coding: utf-8 # # Scales in Python # In[2]: import pandas as pd # In[ ]: s = pd.Series(['Low', 'Low', 'High', 'Medium', 'Low', 'High', 'Low']) s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True) # # Cut Data into bins to build interval data # In[3]: s = pd.Se...
nu1 = float(input("Enter First Number: ")) nu2 = float(input("Enter Second Number: ")) nu3 = float(input("Enter Third Number: ")) if (nu1 >= nu2) and (nu1 >= nu3): largest = nu1 elif (nu2 >= nu1) and (nu2 >= nu3): largest = nu2 else: largest = nu3 print("The Largest Number Between", nu1,...
from Matrix import Matrix from Vector import Vector from Algebra import * class EigenVector: ''' Helper Functions to Compute Eigenvectors ''' @classmethod def orig_mat(cls, diagonal_matrix, eigenvectors): ''' Given the Diagonal Matrix D and Eigenvectors, compute the origina...
feet = float(input("Please enter a number of feet to convert to meters: ")) meters = feet * .305 print (meters)
Rows = int(4) A = int(1) print("a a^2 a^3") for row in range(Rows): a2 = int(A**2) a3 = int(A**3) print(A, ' ',a2,' ',a3) A+=1
name=input("enter name:") age=input("enter age:") print("name:" +name) print("age:" +age) x=100-age if()
import re from typing import Optional, List, Set class Bag(object): color: Optional[str] = None outer_bag = None bags: {} = {} def __init__(self, color: str = None, bags=None, outer_bag=None) -> None: super().__init__() if bags is None: bags = {} self.color = str...
#!/bin/python from typing import List, Set def max_dist(x: int) -> int: distance: int = 0 while x > 0: distance += x if x > 0: x -= 1 elif x < 0: x += 1 return distance def calc_height(y: int, target_y: List[int]) -> int: height: int = 0 while ...
#!/use/bin/env python from sys import argv from typing import List, Tuple def read_file(file: str) -> List[List[int]]: with open(file, 'r') as f: trees: List[List[int]] = [] for line in f.readlines(): line = line.strip() row: List[int] = [] for l in line: ...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @author: ran @file: counting_bits_338.py @time: 2021/6/13 19:52 @desc: 给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i , 计算其二进制数中的 1 的数目并将它们作为数组返回。 """ class Solution(object): def countBits(self, n): """ :type n: int ...
def ALG(list1, list2, k): #BASE CASES #If one list is empty, the kth smallest element (where #k starts at 0) must be at index k in the other list. if len(list1) == 0: return list2[k] elif len(list2) == 0: return list1[k] #RECURSIVE CASES #The list1 is of...
class ListNode: def __init__(self,x): self.val = x self.next = None def createList() -> ListNode: n = int(input()) head = None tail = None for i in range(0,n): ele = int(input()) tempnode = ListNode(ele) if tail == None: head = tail = tempnode else: tail.next = tempnode tail = tail.next ...
#!/usr/bin/env python3 # Designing Algorithms /// top-down design ## What is smallest value? This code tells us just that - it is the data for past 10 years counts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476] print (min(counts)) ## If we want to know in which year the population bottomed out, we can use list...
#!/usr/bin/env python3 # Reading and Writing Files # To check the current directory import os print(os.getcwd()) # To look for file in different directory file = open('file_examples/file_example.txt', 'r') contents = file.read() file.close() print(contents) # Another way look for file in different directory with ...
#!/usr/bin/env python3 import math type(math) print(math.sqrt(9)) print(math.pi) radius = 5 print('area is', math.pi * radius ** 2) import temperature celsius = temperature.convert_to_celsius(90.1) print(celsius) print(temperature.above_freezing(celsius)) import panda_print print('__name__ is ',__name__) import ma...
class Fruit: #class __secret_var ="40" #hidden variable def __init__(self, calorie=0, color=""): self.calorie = calorie #field/attribute self.color = color __confidential = "abc" # private variable meant to be hidden from outsiders, concept of encapsulation #print(self.__confid...
def get_number(lower, upper): while (True): try: user_input = int(input("Enter a number ({}-{}):".format(lower, upper))) if user_input < lower: print("Number too low.") elif user_input > upper: print("Number too large.") else: ...
# list of positive integer numbers from statistics import mean # list the numbers in the order data1 = [1, 2, 3, 4, 5, 6] # assume x that is the mean value of the list x = mean(data1) # Printing the mean print("Mean is :", x)
""" Write a function that takes an integer and prints the numbers from that down to 0. Hint: while or for or recursion eg. print_num(5) output: 5 4 3 2 1 0 """ def print_num_recursion(x): print(x) if x == 0: return else: print_num_recursion(x-1) def print_num_while(x): while x >= 0: ...
user_input = input("Enter your name:") while user_input == "": user_input = input("Enter your name:") print(user_input[::2])
"""This file should have our order classes in it.""" from random import randint import time import datetime class AbstractMelonOrder(object): """Tracks melon orders and calculates totals.""" def __init__(self, species, quantity, country_code): """Initialize melon order attributes.""" self.sp...
# Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. # The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. # The program creates a Python dictionary that maps the sender's mail address to a count ...
# TODO:pagenumber:123 s = {} # this creates a empty dictionary print(type(s)) # to create set s1 = set("vinaychowdary") s2 = set("VinayChowdary") print(s1, s2) print(s1 | s2) # union print(s1-s2) # difference print(s1 & s2) # intersection print(s1 ^ s2) # x-y U y-x print(s1 > s2) # superset print(s1 < s2) # sub...
import random # lists are nothing but arrays but these can hold different types of data # lists are mutable friends = ["a", "b", "c", "d", 0] list2 = [1, 80, 2, 3, 10, 24, 5, 6] sample = [0]*5 print(sample) # range() function gives list of values from 0 upto value specified in python2 # but in python 3 range() gives it...
import arcade y = 0 x = 0 def draw_section_outlines(): color = arcade.color.BLACK # Bottom squares arcade.draw_rectangle_outline(150, 150, 300, 300, color) arcade.draw_rectangle_outline(450, 150, 300, 300, color) arcade.draw_rectangle_outline(750, 150, 300, 300, color) arcade.draw_rectangle_o...
from CalculatorMethods import * from Packages import * # is used when using eval to run equations from math import * def router(choice, total): print("\n" * 50) if 1 <= choice <= 4: statement, total = basicmath_driver(choice, total) print(statement) elif choice == 5: statement, to...
#!/usr/bin/env python # coding: utf-8 # **Collecting and Importing the data** # In[10]: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import math # In[3]: titanic_url = "D:\My Work\Otherthan Syllabus\Data Science...
# -*- coding: utf-8 -*- from fractions import gcd def lcm(numbers): def lcm(a, b): return (a * b) // gcd(a, b) return reduce(lcm, numbers) print lcm(range(1,21))
# -*- coding: utf-8 -*- print(sum([x for x in range(1,1000) if x%3==0 or x%5==0]))
# this is all of ETL to split the customers csv into first name, last name and age and add to the person table on SQL! import pymysql from os import environ from datetime import date from ETL.Extract.extract import csv_load title_list = ["miss","ms","mrs","mr","dr"] def process_customers(data): temp_list=[] ...
import math x = 3400 empirico = x + (0.3*x) * ( (0.7*x) + (0.7*x * math.log2(x)) + (0.7*x) + (0.7*x)) print("Custo empirico: ", empirico) assintotico = x**2 * math.log2(x) print("Custo assintotico: ", assintotico) proporcao = empirico/assintotico print("Proporcao: ", proporcao)
#If change in parameter can't enhance the model greatly, cross validation will be forewent. from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn import preprocessing diabetes=lo...
#coding: utf-8 age = 20 name = 'Swaroop' #format格式化参数,变量的设置 print('{0} was {1} years old when he wrote this book'.format(name, age)) print('why is {0} playing with that python?'.format(name)) #对于浮点数,保留小数点后三位 print('{0:.3f}'.format(1.0/3)) #下划线填充文本,使字符串位于中间 #使用(^)定义字符串长度 print('{0:_^7}'.format('hello')) #print会自带一个'...
""" 687. 最长同值路径 给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。 注意:两个节点之间的路径长度由它们之间的边数表示。 示例 1: 输入: 5 / \ 4 5 / \ \ 1 1 5 输出: 2 示例 2: 输入: 1 / \ 4 5 / \ \ 4 4 5 输出: 2 注意: 给定...
#2 Write a program to find the biggest of 3 numbers (Use If Condition) num1=int(input('Enter first number:')) num2=int(input('Enter second number:')) num3=int(input('Enter third number:')) if (num1>num2 & num1>num3): print('{0} is greatest)'.format(num1)) elif (num2>num1 & num2>num3): print('{0...
#9.Write program to Add, Subtract, Multiply, Divide 2 Complex numbers. a=input('Enter the part a of number:') b=input('Enter the part b of number:') c=("Complex number:",str(a)+' + '+str(b)+' '+'j') print(c)
#7.Create a list with at least 10 elements having integer values in it; #Print all elements #Perform slicing operations #Perform repetition with * operator #Perform concatenation with other list. List = [1,2,3,4,5,6,7,8,9,10] print(List)#Print all elements print(List[1:4]) #Perform ...
def number_tally(numbers): tally = {} for number in numbers: if number not in tally: tally[number]=0 tally[number]+= 1 print (tally) return tally numbers = "123475661264" number_tally(numbers)
arr = [4, 3, 2, 1] for elements in range(len(arr),0,-1): print(arr[elements])
string = input("enter the string") list = string.split(",") print(list) result = {} count = 1 for elements in range(0, len(list)): result[list[elements]] = count if list[elements] in result.keys(): result[list[elements]] = +1 print(result)
from collections import Counter s = 'aabbccdde' dict = {} for element in s: if element not in dict: dict[element] = 1 else: dict[element] += 1 print(dict) values = dict.values() list = [] for val in values: list.append(val) print(list) print(Counter(list))
# from math import floor # # # def activityNotifications(expenditure, d): # print(expenditure) # median_list = [] # sorted_list = [] # mid_value = floor(d / 2) # notice_count = 0 # print("mid_value:", mid_value) # # for index in range(0, len(expenditure)): # slice_range = index + d #...
print(" Welcome to Hangman!") print("Guess your letter") Guess_word = str("CAT") list = [] guess_list = [] for letter in Guess_word: value = ord(letter) list.append(value) for blank in range(0, len(Guess_word)): print('- ', end='') game = str(input()) guess_value = ord(game) guess_list.append(guess_value) f...
print(" Welcome to Hangman!") print("Guess your letter") guess_Word = str("CAT") print("- " * len(guess_Word)) guess_Dict = {} for letter in range(0, len(guess_Word)): key = guess_Word[letter] value = ord(guess_Word[letter]) guess_Dict[key] = value print(guess_Dict) user_input = input("Enter any alphabet t...
#komentarz print("Hello world!") print('Hello "world"!') number = 3 number_str = "3" print(number_str) print(number) print(type(number_str)) print(type(number)) print(type(3.14)) print(0.1+0.1+0.1) print(type(True)) print(type(None)) number = number + 1 print(number) hello = "Hello" world = "world" ex = "!" #konk...
#!/usr/bin/python # # Juan Carlos Perez # perepardojc@gmail.com # @perezpardojc # # Program: # # Program to convert in any bases # How to use: execute # python alltogether.py # # #imports import os import sys import re import datetime import time import argparse import itertools def Palindrome_Number(n): ...
#!/usr/bin/python # # Juan Carlos Perez # perepardojc@gmail.com # @perezpardojc # # Program: # # Get help python palindromic.py -h # # #imports import os import sys import re import datetime import time import argparse # functions #def palindrome(num): # return num == num[::-1] # print "es palindromo" def...
import csv import json #Read the input.csv and convert it to output.json csvfile = open('input.csv', 'r') jsonfile = open('output.json', 'w') #Sort each row with cooresponding attribute to json format fieldnames = ("") csvReader = csv.DictReader(csvfile, fieldnames) for csvRow in csvReader: json.dump(csvRow, json...
import random import math import time import sys def simulation(n, k, alpha_low, alpha_high, alpha_step): """Run the simulation on the complete graph of size n. For each value of alpha perform k simulations Note that here beta = alpha / n and the critical point should occur at alpha = 1 """ #vary alpha from smal...
friends = ["Asad", "Fawad", "Sadaf", "Hammad"] for text in friends: print(text) print() for friend in range(len(friends)): print(friends[friend]) print() for index in range(1, 200): print(index) for index in range(5): if index == 0: print("First") else: print("Not First")
""" Write an efficient function that checks whether any permutation of an input string is a palindrome. I'm assuming here that 'efficient' refers to an algorithm that runs in O(n) time. """ import unittest def is_permutation_palindromic(instr): # if string has even number of chars, # all should appear in pa...
# -*- coding: utf-8 -*- ### dict ### #dict就是key-value存储 dict_test = {'a': 1, 'b': 2, 'c': 3} print(dict_test['a']) print(dict_test.get('a')) print(dict_test.get('aa')) print('aa' in dict_test) ###增 dict_test['d'] = 4 print(dict_test) ###改 dict_test['d'] = 666 print(dict_test) ###改增 dict_test_temp = {'dd': 888} dict...
#PROGRAMACION ORIENTADA A OBJETOS EN PYTHON class Character: #__init__ es el constructor, importante el objeto "self" es objeto y no variable #las variables del constructor son name e initial_health #self es lo mismo que "this" en C# o "me" en VB.NET def __init__(self, name, initial_health): se...
nums=[-7,-3,2,3,11] def square_num(nums): return sorted([x**2 for x in nums ]) print(square_num(nums))
def cons_num(nums): cnt, res = 0, 0 for i in nums: if i == 1: cnt += 1 else: res = max(res, cnt) cnt = 0 return res print(cons_num([1,1,1,1,0,1]))
''' Prints the total value of all sites ''' def task_four(websites): total = 0 for website in websites: try: total += website['value'] except: print('Website does not have "value" key or invalid value type.') continue print(total) return total
import keyboard def pfun(): print("you pressed p") def rfun(): print("you pressed r") while True: if keyboard.read_key()=="p": #pfun() print(" you pressed p") if keyboard.read_key()=="r": print(" you pressed r") #rfun() if keyboard.read_key()=="q": ...
# Authur: Nasir Lawal # Date: 23-Nov-2019 """ Description: Tutorial on the difference between "Syntax and Exception" """ while True: try: number = int(input("What is your fav number?\n")) print(18/number) break except ValueError: print("Make sure you enter a number") except ZeroDivisionError: print("Don't...
from heapq import heappush, heappop def execution_time(tasks, cool_down): """ Calculate the total execution time of a given task with cool down :param tasks: a string denoting tasks :param cool_down: cool down time for the same task :return: total execution time """ task_index_dict = {} #...
def min_subarray_sum(n, s): """ Find the minimum size of sub array which has sum greater than or equal to s :param n: array with positive integers :param s: target sum :return: minimum size of sub array """ n_len = len(n) min_size = n_len + 1 if n_len == 0: return 0 sum_...
class Solution(object): def find_sub_string(self, s, words): indices, num_words = [], len(words) if num_words == 0: return indices str_len, word_len = len(s), len(words[0]) word_count_dict = dict() # Get frequency of each word. Words may contain duplicates ...
from collections import deque def longest_path_in_BST(root): max_path = 0 def longest_path_in_BST_helper(root): """Return the maximum depth of a BST""" nonlocal max_path if not root: return 0 left_depth = longest_path_in_BST_helper(root.left) right_depth = ...
from heapq import heappush, heappop, heapify def find_median(nums_list): """ Find median of a list of sorted arrays :param nums_list: :return: """ index = [0] * len(nums_list) total_nums = sum(list(map(lambda x: len(x), nums_list))) heap = [] for i, nums in enumerate(nums_list): ...
class ticket(object): def __init__(self,price,start = '',destination = '',date = '',Class = 'economy'): """initialize the ticket field""" self.start = start self.destination = destination self.date = date self.Class = Class self.price = price def __str__(self): ...
from Mars import MarsLandingArea from Rover import Rover import sys def navigate(commands,rover,landingArea): # This is the knowledge the Rover uses to read its commands. # If the rover does not read an 'L', 'R', or 'M' then it sends an Error message, returns to its initial position and requests a new set of c...
import re # On 'None' method, you cannot invoke group method str = "Take up one idea. one idea at a time." str1 = "Take 1 up one 23 idea. one idea 45 at a time." result1 = re.search(r'o\w\w', str) print(result1.group()) result2 = re.findall(r'o\w\w', str) print(result2) # 'match' only looks at the beginning result3...
x = 10 y = 20 print(x + y) s1 = "Hello!" s2 = " How are you?" print(s1 + s2) lst1 = [1, 2, 3] lst2 = [4, 5, 6] print(lst1 + lst2)
#创建一个表示汽车的类,存储有关汽车的信息,还有一个总汇这些信息的方法-get_descriptive_name class Car(): #一次模拟汽车的简单尝试 def __init__(self,make,model,year): #初始化描述汽车的属性 self.make = make self.model = model self.year = year def get_discriptive_name(self): #返回整洁的描述信息 long_name = str(self.year) + ' ...
prompt = "\nTell me somthing, and I will repeat it it to you:" prompt += "\nEnter 'quit' to end the program." message = 1 while message != 'quit': print(prompt) message = input()
cars = ['bmw','audi','toyota','subaru'] cars.sort() #顺序归纳 print(cars) cars.sort(reverse = True) print(cars)
#Práctico 5: Usando como base el programa anterior, crear un programa que permita seleccionar un rectángulo de una imagen. # Con la letra “g” lo guardamos a disco en una nueva imagen y salimos. # Con la letra “r” restauramos la imagen original y volvemos a realizar la selección. # Con la “q” salimos. import cv2 img =...
#공포도 별 모험가 그룹 나누기 #내 코드 n=int(input("모헙가의 수 입력하세요")) data=list(map(int,input().split())) data.sort() #5명 공포도 3이하의 공포도를 가진 사람들(3명)으로 구성 count=0 max_scared=max(data) while(True): if ( len(data) >= max_scared ): for _ in range(max_scared): del data[n-1] n-=1 count+=1 if len(data)==0: break ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 22 21:55:13 2018 @author: liran """ class A(type): def __call__(c,arg): c.xyz=900 print("A",arg) return super(A,c).__call__(arg) class B(object): def __call__(c,arg): print("B") def fn(self): pri...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat May 13 22:24:10 2017 @author: parallels """ class Account: numCreated = 0 def __init__(self, initial): self.__balance = initial self.list = [1,2,3] Account.numCreated += 1 self.__name="Avi" def deposit(self...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import random # An enumeration type: class Outcome: def __init__(self, value, name): self.value = value self.name = name def __str__(self): return self.name def __eq__(self, other): return self.value == other.value Outcome.WIN ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- class Account(object): def __init__(self, initial): self._balance = initial def deposit(self, amt): self._balance = self._balance + amt def withdraw(self,amt): self._balance = self._balance - amt def getbalance(s): retur...
import copy class Country(object): index = {'name':0,'population':1,'capital':2,'citypop':3,'continent':4, 'ind_date':5,'currency':6,'religion':7,'language':8} # Insert your code here # 1a) Implement a constructor def __init__(self, row): self.__attr = row.split('...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu May 11 13:40:33 2017 @author: parallels """ def make_multiplier_of(n): def multiplier(x): return x * n return multiplier # Multiplier of 3 times3 = make_multiplier_of(3) # Multiplier of 5 times5 = make_multiplier_of(5) # O...