text
stringlengths
37
1.41M
# Copyright (c) 2020 Lorenzo Martinez # # This program takes as input the name of an input file and output file # keeps track of the total the number of times each word occurs in the text file # excluding white space and punctuation is case-insensitive # print out to the output file (overwriting if it exists) the ...
from cs50 import get_float # cents: 25, 10, 5 , 1 while True: print('How much change is owed?') n= get_float() if n>=0: break money_coins = round(n*100) count = 0 while money_coins>=25: money_coins -= 25 count+=1; while money_coins>=10: money_coins -= 10 count+=1; while money_c...
# 装饰器,用来计算函数运行时间 def print_run_time(func): def wrapper(*args, **kw): start_time = time.time() res = func(*args, **kw) end_time = time.time() use_time = end_time - start_time # # 以下时间转换 # s = int(use_time) # h = s / 3600 # m = (s - h * 3600) / 60 ...
#사용자가 입력한 이름이 명단 리스트에 있는지 검색 후 결과를 출력 members = ['홍길동', '이몽룡','성춘향','변학도'] name = input('이름 입력 : ') for member in members: if name == member: find = True break else: find = False if find == True: print('명단에 있습니다.') else: print('명단에 없습니다.')
#집합 만들기 : {} 사용 s1 = {1,2,3,4} print(s1) #{1, 2, 3, 4} print(type(s1)) #<class 'set'> #list형과 tuple형을 set형으로 변환 s2 = set([10,29,30]) print(s2) #{10, 29, 30} s2 = set((19,2390,230)) print(s2) #{19, 2390, 230} #set는 중복값이 있으면 제거하고 출력한다 s4 = {1,2,3,3,4,5,} print(s4) #{1, 2, 3, 4, 5} #set내에 list포함시 에러가 발생한다 # s5 = {1,2,3...
n = [1,2,3,4,5,6,6,4] n.remove(4) #가장 앞에 존재하는 4를 삭제하고 원본 반영됨 print(n) # [1, 2, 3, 5, 6, 6, 4] #n list에서 원소값이 6인 원소를 모두 제거하시오 #6의 개수 확인 count = n.count(6) print(count) for i in range(count): n.remove(6) print('6삭제',n) print(n) # n1 = [1,1,1,3,2,4] # n1.remove(1) # n1.remove(1) # n1.remove(1) # n1.remove(1) # p...
#7을 입력하면 종료되는 프로그램 num = int(input('숫자 입력: ')) while num != 7: num = int(input('다시 입력 : ')) print(num,'입력, 종료!')
""" Regression algorithm used to predict the number of points each player on a given team will score against a specific opponent. Data pulled from nba_stats_prod mysql database instance. """ import numpy as np import pandas as pd import pymysql import datetime import matplotlib.pyplot as plt import seaborn as sns imp...
import math class Node(object): def __init__(self, nodeType): """ type: 0 is bias, 1 is input, 2 is output parentList will be a list of tuples pairing nodes and weights """ self.nodeInput = None self.nodeType = nodeType if nodeType == 2: self.parentList = [] def setInput(self, nodeInput): ...
number = int(input("请输入数字")) if number %2 == 0: print("是偶数") elif number%2 != 0: print("是奇数")
while True: a = int(input("请输入一个数字:")) b = int(input("请输入一个数字:")) sum = 0 if a < b: for c in range(a,b+1): print(c) sum = sum + c print(sum) break else: print("重新输入")
''' #5! = 5*4*3*2*1 #4! = 4*3*2*1 #3! = 3*2*1 i = 1 a = 1 while i <= 5: a*=i i+=1 print(a) ''' def xxxx(num): def xxx(num): num*xxxx(num-1) 5*xx def get_num(num): 5*4! 5*xxx(num-1)
#定义一个函数,声明一个函数 def kill(): print("*"*60) print("择国江山,入战图".center(50," ")) print("生民何计,乐樵苏".center(50," ")) print("凭君莫话,封候事".center(50," ")) print("一将功成,万古枯".center(50," ")) print(60*"*") kill()#调用
#For this lab, any exponent less than 0 should return 1 as its default behavior. def pow_rec(base, power): #base case if power<=0: return 1 elif power % 2==0: #if power is an even number return pow_rec(base, power/2)**2 #recursive call not less than or equal to zero, not even and number...
# rock paper scissors import random import const as c from Functions import * def main(): first_play = True # sets the score at 0 to start the game. userWins = 0 computerWins = 0 tieCount = 0 while first_play: displayInstructions() second_play = True while second_play:...
# a CreditCard class that contains information about a credit account, # and a Person class which contains basic biographical information about a person. class Person: # Initialization # each of which defaults to an empty string def __init__(self, first_name="", last_name="", address=""): self._fir...
# There are certain things in here that I define as stacks. No doubt I am using the term wrongly as stacks mean something else. Howevver, this was the most appropriate name I could think of at the time import copy class autogame: def __init__(self,og,iterations): self.og = og self.repeats = iterat...
import json import sys # A partir de un json devuelve un diccionario aplanado de todos los campos de un json yendo de abajo a arriba en la jerarquía, # para establecer el nombre de cada campo concatena cada nombre de cada jerarquía y el nombre mismo del campo. def flatten_json(nested_json): out = {} def flatt...
with open('input.txt') as f: lines = f.read().splitlines() def calcErrorRate(lines): data = "rules" rules = [] nearTicket = [] for line in lines: if line == "": continue if line == "your ticket:": data = "ticket" continue if line == "nearby t...
import unittest class Submarino(object): def coordenada(self, comando=''): return '2 3 -2 SUL' # return '0 0 0 NORTE' class SubmarinoTest(unittest.TestCase): def testCoordenada(self): sub = Submarino() self.assertEqual('2 3 -2 SUL', sub.coordenada("RMMLMMMDDLL")) # def t...
class tree(): def __init__(self, dis=-1): self.dis = dis def make(self, i, page_list): page_tree = [] page_tree.append([i + 1, page_list]) # print(page_tree) self.id = i + 1 self.son = page_list ''' tree_list = [] list1 = [[3, 4], [0], [2, 4], [3]] for i ...
i1 = input() i2 = input() i1 = int(i1) i2 = int(i2) list1 = [] list2 = [] for i in range(i1): i3 = input() list1.append(i3) for i in range(i2): i4 = input() list2.append(i4) print(list1) for ii1 in list1: for ii2 in list2: print(f'{ii1} as {ii2}')
p_a = 100 p_b = 100 for i in range(int(input())): str1 = input() list1 = str1.split(' ') list1[0], list1[1] = int(list1[0]), int(list1[1]) if list1[0] > list1[1]: p_b -= list1[0] elif list1[0] < list1[1]: p_a -= list1[1] else: pass print(p_a) print(p_b)
class User: def __init__(self, users): self.name = users self.account_balance = 0 def make_deposit(self, amount): self.account_balance += amount print(f"{self.name}, deposited {amount}") def make_withdrawl(self, amount): self.account_balance -= amount print(...
class BankAccount: def __init__(self, int_rate, balance): self.int_rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): if self.balance >= amount: self.balance -= amount ...
""" 6kyu: Split Strings https://www.codewars.com/kata/split-strings/train/python Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). Examples:...
import sys print ''' A flock of birds is flying across the continent. Each bird has a type, and the different types are designated by the ID numbers , , , , and . Given an array of integers where each integer describes the type of a bird in the flock, find and print the type number of the most common bird. If two or ...
from typing import List class Subject: """Represents what is being observed. Needs to be monitored.""" def __init__(self, name: str = "") -> None: self._observers: List["TempObserver"] = [] self._name: str = name self._temperature: int = 0 def attach(self, observer: "TempObserver...
from abc import ABC, abstractmethod from typing import Sequence, List class Component(ABC): """Abstract interface of some component.""" @abstractmethod def function(self) -> None: pass class Child(Component): """Concrete child component.""" def __init__(self, *args: str) -> None: ...
from abc import ABC, abstractmethod class Shape(ABC): """Interface that defines the shape.""" @abstractmethod def draw(self) -> str: pass class ShapeError(Exception): """Represent shape error message.""" pass class Circle(Shape): """Concrete shape subclass.""" def draw(self)...
#CLASSES# #es para representar un punto en el espacio #estoy definiendo una nueva calse de cosas llamada "Point" class Point: # El "init" sirve para decirle a python, despues de crear la clas, que es lo que necesito para esta #self es el objeto de la clase que recien cree y despues con x, y defino atributos para ese...
#variable x que guarda el numero 28 x = -28 #funciones condicionales #si x es mayor que cero, imprimi "x es positive" if x > 0: print("x is positive") #en otro caso, si x es menor que cero, imprimi "x is negative" elif x < 0: print("x is negative") #en cualquier otro caso, imprimi "x is zero" else: ...
#sorting characters in a string string = str(input()) def alphabet_soup (string): create_list = string get = list (create_list) get.sort() join = ''.join(get) return join print (alphabet_soup(string))
#add items to list and then sort from largest to smallest number. Shout out to AR items = [4,1,2,12,98,58] #user to add items to list def user_input (items): user_in = (int(input("Enter an integer: "))) items.append(user_in) return items #sort function with AR def sort(items): empty_list = []...
import random def lev_del(word): r = random.randint(0, len(word) -1) w = word[:r] + word[r+1:] assert(len(w) == len(word) - 1) return w def lev_add(word): l = chr(ord('a') + random.randint(0,25)) r = random.randint(1, len(word) -1) w = word[:r] + l + word[r:] assert(len(w) == len...
print('calResult') a = float(input('Please Enter a:')) b = float(input('Please Enter b:')) c = float(input('Please Enter c:')) Result = ((4.2*a)+(2.8*b))/(((5*b)/a)-(7*c)) print('Result is '+str(Result))
import psycopg2 import sys #connect to the database conn=psycopg2.connect(database='tcount', user="postgres", password="pass", host="localhost", port="5432") curs=conn.cursor() #if there is no argument on the command line get the words and counts in ascending order if len(sys.argv) == 1: sql = "SELECT word, count F...
"""File with implementation of StartWriter and EndWriter classes.""" import turtle from constants import BLOCK_PIXEL_SIZE class StartWriter(turtle.Turtle): """A class to write informations for the player at the start of the game.""" def __init__(self, maze_size): turtle.Turtle.__init__(self) s...
from enum import IntEnum class HasState(object): """ This interface allows a read-only access to states of a Thing. All implementations of this interface must to have a 'state' property and declare a concrete list (enumeration) of all states possible. Also it's needed to mention that if the ...
""" This module contains definition of Has Color Temperature capability """ class HasColorTemperature(object): """ Color Temperature devices are devices that have the "color temperature" property. The color temperature is expressed in Kelvins and can take integer values from 1000 to 10000 including. T...
""" This module contains definition of Has Volume capability """ class HasVolume(object): """ Has Value devices are devices that have the "volume" property - the measure of loudness, i.e. of how loud its sound is. Volume is an integer value in the range from 0 (zero) to 100 including. Actuator Ha...
""" This module contains definition of Has Color HSB capability """ from .has_brightness import HasBrightness class HasColorHSB(HasBrightness): """ Has Color HSB devices are devices that have a "color" property. The current color is specified using three components: hue, saturation and brightness. Ea...
a = 'é' b = 'MELHOR' c = 'que' d = 'FEITO' e = 'perfeito' print(f'{a.upper()} {b.lower()} {d.upper()} {c.lower()} {e.lower()}')
#!python # 2018 - Alessandro Di Filippo - CNR IMAA """ This function calculates the datalogger uncertainty for a specific temperature value using the calibration coefficients and the datalogger id. First it finds the resistance of the PRT using the calibration coefficients and the quadratic equation. An if statement d...
""" Checks if a specific word exists in ANY of the ground truth or machine results. """ import os import sys import json import argparse from tqdm import tqdm from collections import Counter from typing import List, Dict, Any, Tuple import preproc.util def main(args): if not os.path.exists(args.machine_dir): ...
""" This script converts the ground truth transcriptions from TXT format into a structured JSON format, matching the Google Speech API format. """ import os import re import json import argparse import pandas as pd from typing import Dict, Tuple, List from tqdm import tqdm from pandas import DataFrame import preproc.ut...
#content def c_peg(): return "O" def c_empty(): return "_" def c_blocked(): return "X" def is_empty(e): return e==c_empty() def is_peg(e): return e==c_peg() def is_blocked(e): return e==c_blocked() #position #Tuple(line,column) def make_pos(l,c): return (l,c) def pos_l(pos): ...
from matplotlib import pyplot as plt import numpy as np from pathlib import Path """ The algorithm assumes that, under a white light source, the average colour in a scene should be achromatic (grey, [128, 128, 128]). You do not need to apply any pre or post processing steps. For the calculation or processing, you ar...
#!/usr/bin/env python listIndex = [9,19,25,100,200,321] mylist = [[],[],[],[],[],[],[]] def findIndex(index,data): min = 0 max = len(index) -1 while(min <= max): mid = (max + min) // 2 if data > index[mid]: min = mid + 1 else: max = mid -1 return max +...
#!/usr/bin/python import time import random # This function in mergesort algorithm divides the list into various sublists # and then sorts by later merging into give sorted array. def mergeSort(array): if len(array) > 1: mid = len(array)//2 leftArr = array[:mid] rightArr = array[mid:] ...
#!/usr/bin/python import unittest from .. import wordtree class TestWordTree(unittest.TestCase): def test_empty_dictionary(self): tree = wordtree.WordTree([]) self.assertEqual(0, tree.count()) def test_count_one_entry(self): tree = wordtree.WordTree(['as']) self.assertEqual...
# user = [] # list_user = [["ngoc","ngoc@gmail.com","123"]] # # def login(): # pass # # def register(): # username = raw_input("username: ") # username = nullValidator(username, "username") # # email = raw_input("email: ") # email = nullValidator(email, "email") # # # password= raw_input("passwo...
list_user = [] ["Ngoc", "ngoc@gmail.com", "123"] ["Uyen", "uyen@gmail.com", "123"] list_user = [["Ngoc", "ngoc@gmail.com", "123"], ["Uyen", "uyen@gmail.com", "123"]] # def none(input): # while True: # check=False # username=input("username:") # if username=="": # print("Khong duoc de trong") # check=True #...
import numpy as np import scipy.stats as st def mean_intervals(data, confidence=0.95, axis=None): """ Compute the mean, the confidence interval of the mean, and the tolerance interval. Note that the confidence interval is often misinterpreted [3]. References: [1] https://en.wikipedia.org/wiki/Con...
#### 람다 표현식 # # 일반 함수 # def add(a, b): # return a + b # print(add(3, 7)) # # 람다 표현식으로 구현한 add() 메서드 # print((lambda a, b: a + b)(3, 7)) # ## 내장 함수에서 자주 사용되는 람다 함수 # array = [('홍길동', 50), ('이순신', 32), ('아무개', 74)] # def my_key(x): # return x[1] # print(sorted(array, key = my_key)) # print(sorted(array, key ...
# Pirma užduotis class first: # Sukūriama klasė first def summing_function(self, n, a, b): # Sukūriama funkcija summing_function, kuriai perduodami trys parametrai n, a, b try: given_text=list(n) # given_text yra n kintamojo listas positive_symbols=list(a) # positive_symbols yra ...
# Prompt user for input integer = int(input("Enter an integer: ")) # Determine and display if integer is divisible by 2 and 5 if (integer % 2) == 0 and (integer % 5) == 0: print("Integer: " + str(integer) + ", is divisible by 2 and 5") else: print("Integer: " + str(integer) + ", is not divisible by 2 and...
# Prompt user to enter full name user_name = input("Enter your full name: ") # Validate to ensure user enters an input if len(user_name) == 0: print("You haven’t entered anything. Please enter your full name.") # Validate to ensure full name is not less than 4 characters elif len(user_name) < 4: prin...
#!/usr/bin/env python # coding=utf-8 import sys def fun(): offen = "" total = 0 vehicles = "" word = None for line in sys.stdin: word,count = line.strip().rsplit("\t",1) num = count.split(",")[0] vehicle = count.split(",")[1] if offen == word: total += i...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: # will be forwarding over at each step ...
#!/usr/bin/env python # coding=utf-8 class Node(object): def __init__(self, data=None): self.data = data self.next_node = None def get_data(self): return self.data def set_data(self, data): self.data = data def get_next(self): return self.next_node def s...
from os import system system("cls") satuan = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' ] def terbilang (n): if n % 1 > 0: cari_koma = str(n).find('.') angka_belakang_koma = str(n)[cari_koma+1:] angka_depan_koma = str(n)[0:cari_koma] ...
import unittest from aids.linked_list.linked_list import LinkedList class LinkedListTestCase(unittest.TestCase): ''' Unit tests for the Linked List data structure ''' def setUp(self): self.test_linked_list = LinkedList() def test_stack_initialization(self): self.assertTrue(isinstance(self.tes...
''' Implementation of Stack data structure ''' class Stack(object): def __init__(self): ''' Initialize stack ''' self.items = [] def is_empty(self): ''' Return True if stack if empty else False ''' return self.items == [] def push(self, item): ''' Push item to stack ''' ...
''' Implementation of queue data structure ''' class Queue(object): def __init__(self): ''' Initialize queue ''' self.items = [] def is_empty(self): ''' Return True if queue if empty else False ''' return self.items == [] def enqueue(self, item): ''' Push item to queue '''...
import unittest from aids.strings.is_palindrome import is_palindrome class IsPalindromeTestCase(unittest.TestCase): ''' Unit tests for is_palindrome ''' def setUp(self): pass def test_is_palindrome_true_empty_string(self): self.assertTrue(is_palindrome('')) def test_is_palind...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Mon Feb 2 20:34:12 2015 @author: Markus Pfundstein, Thomas Meijers, Cornelis Boon """ from argparse import ArgumentParser from collections import OrderedDict from collections import Counter import string def sort_ngrams(ngrams): return OrderedDict(sorted...
#Liam Collins #2/15/18 #favorites.py word = input('Enter your favorite word: ') num = int(input('Enter your favorite number: ')) i = 0 while i < num: print(word) i += 1 for i in range (0,num): print(word)
import math day1_data = open('day1_data.txt') """First, read the data and convert to list of integers. Next, convert the module masses to fuel. Finally, add all of the fuel to obtain the total for for the Fuel Counter Upper. """ def create_module_list(data): module_list = [int(i) for i in data] return module...
import sys from os import path from random import randint from binarySearch import binarySearch # Add algorithms directory to path sys.path.insert(0, \ r"D:\\github-projects\\algorithms\\quicksort\\python") from quicksort import quicksort sys.path.pop(0) ELEMENTS = 10 def testEmpty(): print("Running testE...
# bayesNet.py import itertools import util class CPT(): """ A table that represents the conditional probabilities. This has two components, the dependencyList and the probTable. dependencyList is a list of nodes that the CPT depends on. probTable is a table of length 2^n where n is the length of d...
from pygame.locals import * import sys import random class EventControl(): """ Controls the game's events, e.g. what happens when a mouse button is pressed, or when a keyboard key is pressed (well, for now it's only that). Later, if more events are used, it'd be a good idea to separate "user i...
drama = "Titanic" documentary = "March of the Penguins" comedy = "Step Brothers" dramedy = "Crazy, Stupid, Love" user_drama = input("Do you like dramas? (answer y/n) ") user_doc = input("Do you like documentaries? (answer y/n) ") user_comedy = input("Do you like comedies? (answer y/n) ") if user_drama == "y" and user...
#BEGINNING OF CALCULATOR # 1) use if-statements to complete this calculator program with 4 operations # Example run (what it should look like): # 0 - add # 1 - subract # 2 - multiply # 3 - divide # Enter a number to choose an operation: # 1 # Enter your first input: 10 # Enter your sec...
def min_max_number(A): #A is a list sorted_list= sorted(A) minimum = sorted_list[0] maximum = sorted_list[-1] if minimum==maximum: return len(A) else: return [minimum,maximum]
import sys def findGcd(x,y): gcd=1; factors=[]; for i in range(1,x+1): if x%i==0: factors.append(i); for f in factors: if (y%f==0) and (f>gcd): gcd=f; return gcd; def main(argv): gcd=findGcd(int(argv[1]),int(argv[2])); print gcd; if __name__ == '__main__': main(sys.argv);
def main(): text=raw_input("Enter text :"); text=text.lower(); position=int(raw_input('Shift By / Enter 0 to exit:')) while position!=0: shiftedText=''; if position<1 : position=position+26 for char in text: if char==' ': shiftedText=shiftedText+str(char); else: ascii=ord(char...
a = 98 b = 56 if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b)) else: print('not found')
# DESAFIO 039 # identificar tempo de alistamento militar # ENTRADA: ano de nascimento # SAÍDA: status / anos que faltam / anos que passaram from datetime import date anoN = int(input('Informe o ano de seu nascimento: ')) idade = date.today().year - anoN if idade < 18: print('Você ainda não pode se alistar! Faltam {...
# DESAFIO 050 # soma de 6 numeros pares s = 0 for i in range(0, 6): num = int(input('Informe um valor: ')) if num % 2 == 0: s += num print('Soma dos numeros inteiros: {}'.format(s))
""" DESAFIO 069 ANALISE DE DADOS """ cont = 's' p18 = h = m20 = 0 while True: idade = int(input('Informe sua idade: ')) sexo = str(input('e informe o sexo [F / M]')).strip()[0].lower() if idade > 18: p18 += 1 if sexo in 'm': h += 1 if sexo in 'f' and idade < 20: m20 += 1 ...
# 递归 # 学习目标 ''' 哪些问题适合用递归解决 怎么用递归方式写程序 *****递归的三大法则 for 循环是一种迭代 递归也是一种迭代 一、什么是递归 递归是一种解决问题的方法,它把一个问题分解为越来越小的子问题,直到问题的规模小到可以被很简直接解决 通常为了达到分解问题的效果,递归过程中要引入一个***代用自身的函数*** [1,2]和[3,3] [6,4] 计算一个列表的和 [1,2,3,4,5,6,7] 迭代求和 ''' # def list_sun(my_list): # t...
d = int(input('Por Quantos dias o senhor pretende alugar o carro ? ')) k = float(input('Quantos km você pretende percorrer ao todo ?')) t = (k * 0.15) + (60 * d) print (f'Nesse caso, alugando o carro durante {d} dias e percorrendo {k} KM, \no senhor pagará R${t} ao todo')
""" tests Player Class """ from Player.Player import Player from io import StringIO from unittest import mock def test_create_Player_1(): Player('1', 'Player1') def test_create_Player_2(): Player('2', 'Player2') def test_get_Player_1_name(): player1 = Player('1', 'Player1') name = player1.name ...
import math r = input("radius?") area= math.pi*int(r)*int(r) print ("Area:", area)
flock_sheep = [5, 7, 300, 90, 24, 50, 75] print ("Hello, my name is Nam, and here are my ship sizes ", flock_sheep) biggest = max(flock_sheep) print ("Now my biggest sheep has size ", biggest, "let's sheer it") sheep_no = flock_sheep.index(biggest) flock_sheep[sheep_no] = 8 print ("After sheering, here is my flock "...
import math n = int(input("input a number ")) if n == 0: print ("Factorial is: 1") else: print ("Factorial is: ", math.factorial(n))
#1 price_list = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock_list = {"banana": 6, "apple": 0, "orange": 32, "pear": 15 } item_list = list(price_list) details = {} for fruit in item_list: price = price_list[fruit] stock = stock_list[fruit] details[fruit] = {'price: ': price, 'stock: ': stock} ...
#Integer addition, subtraction, multiplication and division num1 = int(input("please enter a number:")) num2 = int(input("please anter a number:")) res1 = num1 + num2 res2 = num1 - num2 res3 = num1 * num2 res4 = float(num1) / float(num2) print("%d + %d = %d" %(num1,num2,res1)) print("%d - %d = %d" %(num1,nu...
import operator import sys ''' This assignment contains only one problem, and requires you to write a standalone Python program that can be directly executed, not just a function. Here are some basic facts about tennis scoring: A tennis match is made up of sets. A set is made up of games. To win a set, a...
#Author: Listen #!/usr/bin/env python3 #-*- coding:utf-8 -*- import matplotlib.pyplot as plt import numpy as np import random def scatter1(): x= np.array([x for x in range(1,21)]) y= x**2 colors=['green','yellow','blue','red','orange','purple','cyan'] random_colors=random.sample(colors,7) fig=plt....
# -*- coding: utf-8 -*- """ Created on Sat Jan 09 13:36:18 2016 @author: Zhongxiang Dai """ import numpy as np import matplotlib.pyplot as plt import copy import networkx as nx import random import math # MCMC (Simulated Annealing) solution for Traveling Salesman problem # start from city 1 to city N #N = 50 # the...
class Dog: nationality="Kenyan" def __init__ (self, color,breed,height): self.color= color self.breed= breed self.height= height def pet(self): return f'The dog is a {self.color}, {self.breed} which is {self.height} tall'
class Zoo : def __init__(self, liste): self._liste=liste def __str__(self): return ''.join([l._animal_type+" " for l in self._liste]) def add_animal(self, a): return self._liste.append(a) def dosomething(self): for l in self._liste: print(l.dosomething(),...
# -*- coding: utf-8 -*- """ Created on Tue Aug 18 17:09:46 2020 @author: Ana """ #Napišite program u kojem se učitava prirodan broj, ko #ji se zatim ispisuje u inverznom (obrnutom) poretku znamenaka. #Ne pretvarati početni broj u string. #Koristite funkciju „Obrni” koja prima jedan broj i #vraća broj u inverznom po...
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 10:51:09 2020 @author: Ana """ #Napišite program koji učitava riječ i #ispisuje novu riječ dobivenu tako da se iz unesene r #iječi izbriše svaki treći znak. string = "majmun" #treba izbacit svako treci znak majmun # 123456 triba izbac...
# -*- coding: utf-8 -*- """ Created on Sat Aug 15 16:57:38 2020 @author: Ana """ # Učitati niz X od n članova ispisati one #članove niza X koji su veći od prvog (zadnjeg) člana niza. niz = [] n = int(input("Unesite koliki zelite da vam bude niz")) for j in range(0,n): broj = input("Unesite brojeve: ") n...
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 00:09:58 2020 @author: Ana """ #Napišite program koji učitava riječ i ispisuje broj samoglasnika string = input("Unesite rijec:") suma = 0 samoglasnici = "aeiou" for j in range(len(string)): if (string[j] =="a" or string[j]=="e" or string[j]=="i" or string[j]==...
# -*- coding: utf-8 -*- """ Created on Sat Aug 15 16:11:12 2020 @author: Ana """ #Učitati članove niza. Ispisati: članove niza # koji su veći od slijedećeg člana. niz = [] N = int(input("Unesite broj")) for j in range(0, N): broj = int(input("Unesite broj ")) niz.append(broj) for i in range(0,N -1):...
# -*- coding: utf-8 -*- """ Created on Tue Aug 18 13:04:43 2020 @author: Ana """ #Napišite program u kojem korisnik unosi broj, #a program ispisuje je li suma znamenki paran ili neparan broj. ##Koristiti funkciju „SumaZnamenki” koja prima # broj i vraća njegovu sumu znamenki. def SumaZnamenki(broj): sum...