text
stringlengths
37
1.41M
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" while cur_head:...
# Loops spam = 0 if spam < 5: print("Enter Name") spam += 1 spam = 0 while spam < 5: print("Enter Name") spam += 1 name = '' while name != 'Your Name': print("Enter Your Name") name = input() print("thank you") # same code as above but using break statment while True: ...
import numpy as np def get_wordlist(): f = open("nounlist.txt", "r") s = f.read() f.close() return s.splitlines() def hash(i, max): cycle = 2147483647 # MAGIC: 8th Mersenne Prime offset = 104729 ** 4 # MAGIC: 10,000th Prime return (i * cycle + offset) % max def hashword(i, K, words): ...
""" Advent Of Code Day 1 """ from itertools import accumulate, cycle from common.input_file import read_numbers def get_sum_of_frequencies(numbers): """ Given a list of frequencies (positive and negative) What is the ending frequency when added together """ return sum(numbers) def get_fi...
""" Advent of Code 2019 Challenge 19 """ from common.input_file import read_strings from common.opcodes import OPCODE_MAPPING def to_opcode(op_str: str): """ Convert to an opcode """ opcode, reg1, reg2, output = op_str.split() return OPCODE_MAPPING[opcode], int(reg1), int(reg2), int(output)...
""" Advent of Code day 10 """ from collections import namedtuple from itertools import count import re from common.grid import Point, Grid, get_manhattan_distance, get_average_point from common.input_file import get_transformed_input def to_star(star_str): """ Takes a star string and converts it to a...
multiples_of_3 = [] for nr in range(10): if nr % 2 == 0: multiples_of_3.append(nr * 3) print(multiples_of_3) multiples_of_3_comprehension = [nr * 3 for nr in range(10) if nr % 2 == 0] print(multiples_of_3_comprehension) words = ['bye', 'hello', 'hi', 'world'] word_lengths = [(word, len(word)) for word in...
def count_common_elements(list1, list2): return len(set(list1) & set(list2)) print(count_common_elements([1, 1, 2, 3], [2, 3, 2, 2, 3, 4])) def count_unique_words(text): words = text.split() return len(set(words)) print(count_unique_words('hello hello is there anybody in there'))
import threading import time total = 0 lock = threading.Lock() def update_total(amount): """ Updates the total by the given amount """ global total # lock.acquire() # try: # for _ in range(1000000): # total += amount # finally: # lock.release() with lock: ...
# class Solution: # def flatten(self, root: TreeNode) -> None: # """ # Do not return anything, modify root in-place instead. # """ # def sub_flatten(node): # if node.left == None and node.right == None: # return (node, node) # l_node, r_node = ...
class Node: def __init__(self, data=None, next_node=None): self.data = data self.next = next_node class LinkedList: def __init__(self): self.head = None def insert_at_beginning(self, data): node = Node(data, self.head) self.head = node def insert_at_end(self,...
"""Implementation of a Class that constructs an dynamic system from an ode.""" import numpy as np import torch from scipy import integrate, signal from .abstract_system import AbstractSystem from .linear_system import LinearSystem class ODESystem(AbstractSystem): """A class that constructs an dynamic system fro...
def ask(name="111"): print(name) class Person: def __init__(self): print("init") def decorate_de(): print("dec start") return ask asktest = decorate_de() asktest("aaa") obj_list = [] obj_list.append(ask) obj_list.append(Person) for item in obj_list: print(item()) # my_func = ask # my_...
def dobro(num): print(f'O dobro de {num} é ', end='') return num * 2 def triplo(num): print(f'O triplo de {num} é {num * 3}') def raiz(num): return f'A raíz quadrada de {num} é ' + str(num ** 0.5) #Programa principal n = int(input('Digite um número: ')) print(dobro(n)) triplo(n) print(raiz(n))
''' Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e outro chamado show, que será um valor lógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial. ''' def fatorial(num, show=False): ''' Calcula o fat...
''' Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-o (com idade) em um dicionário. Se por acaso a CTPS for diferente de ZERO, 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. ''' from date...
''' Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá analisar ser a expressão passada está com os parênteses abertos e fechados na ordem correta. ''' expressao = str(input('Digite uma expressão com parênteses: ')) pilha = list() for parenteses in expressao: if ...
''' Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. Ex: n = leiaInt('Digite um n: ') ''' def leiaINT(num): while True: a = str(input(num)) if a.isnumeric() == True: ...
def dolar(num): cot = float(input('Qual a cotação do Dólar atual? ')) conversão = cot * num return f'R${num:.2f} em equivalem a US${conversão:.2f}' #Programa Principal carteira = float(input('Quanto você deseja converter? ')) print(dolar(carteira))
''' Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. ''' from random import randint lista = [] listaflu = [] print('-'*30) print(f'{"JOGA NA MEGA SENA":^3...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 20 11:45:44 2020 @author: - """ import numpy as np import xarray as xr def area_weighted_sum(data): """ Compute area weighted sum of some CMIP6 data. Parameters ---------- data : xarray DataArray DataArray containing ...
""" 奖与罚 编译者:PengPeng3g v1.0 增加奖与罚 v2.0 增加循环节,增加初中,高中成绩 编译时间:2020.8.16 当前版本:v2.0 """ tuichugaozhong = False tuichuchuzhong = False tuichu = False xuanzenianji=(input("输入年级(初中chuzhong,小学xiaoxue,高中gaozhong)")) if xuanzenianji == "xiaoxue": tuichu = True if xuanzenianji == 'chuzhong': tuich...
""" Writting functions for processing """ # function to calculate BMI Index def BMI_Calculation(tall, weight): result_bmi = (weight/(tall**2)) return result_bmi # function to check BMI Status def BMI_Check(result): final_result = "" if(result < 18.5): final_result = "C" elif(result >= 18.5 a...
import pymongo, sys, re import pandas as pd import requests import lxml.html as lh url='https://www.nationsonline.org/oneworld/IATA_Codes/airport_code_list.htm' #Create a handle, page, to handle the contents of the website page = requests.get(url) #Store the contents of the website under doc doc = lh.fromstring(pag...
# Time Complexity: O(mn) where m is the number of rows and n is the number of columns # Space Complexity: O(mn) where m is the number of rows and n is the number of columns # Ran on Leetcode: Yes class Solution: def numIslands(self, grid: List[List[str]]) -> int: count = 0 self.m = len(grid) ...
import math import tkinter as tk from tkinter import ttk from tkinter import messagebox as m_box from tkinter import filedialog import numpy as np class Additional: def __init__(self) : # self.coba() pass def check_empty_row(self, s_dict, nested_dict = False, specify_column = None) : ...
class Node: def __init__(self, key, data): self.left=None self.right=None self.parent=None self.key=key self.data=data class BST: def __init__(self): self.root=None def treeInsert(tree, node): y=None x=tree.root while x ...
import sys from BitVector import * # Author: Tanmay Prakash # tprakash at purdue dot edu # Solve x^p = y for x # for integer values of x, y, p # Provides greater precision than x = pow(y,1.0/p) # Example: # >>> x = solve_pRoot(3,64) # >>> x # 4L e = 65537 #function to generate the random prime number import r...
## QUESTÃO 2 ## # Escreva um programa que converta uma temperatura digitada em °C (graus celsius) # para °F (graus fahrenheit). ## ## # A sua resposta da questão deve ser desenvolvida dentro da função main()!!! # Deve-se substituir o comado print existente pelo código da solução. # Para a correta execução do progr...
# for循环 lists = [1, '2', (3,), [4], {5}, {6: 7}] for x in lists: print(type(x)) print(x) for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, '等于', x, '*', n//x) break else: # 循环中没有找到元素 print(n, ' 是质数') it = iter(lists) print(type(it)) f...
#!/usr/bin/env python3 # Common cryptographic functionality used throughout these programs # These are all functions that have been defined throught the course of writing # the exercises. That code is centralized here so that it may be re-used by # other exercises without repeating it from base64 import b64encode, b6...
x = 0 x += +1 print("現在位置はx={0}です。".format(x)) x += +1 print("現在位置はx={0}です。".format(x)) x += +1 print("現在位置はx={0}です。".format(x))
#!/usr/bin/env python # coding=utf-8 class Stack: def __init__(self): self.q1 = [] self.q2 = [] def append(self, val): empty_q, other_q = self.find_empty_q() empty_q.append(val) while len(other_q)>0: empty_q.append(other_q.pop(0)) def pop(self): ...
# 변수(variable)는 처리할 데이터를 저장시키는 기억장소를 말한다. # 변수명 작성방법 # 영문자, 숫자, 특수문자(_)만 사용할 수 있으며 대문자와 소문자를 구분한다. # 반드시 변수 이름은 문자로 시작해야 하고 예약어는 사용할 수 없다. # 변수를 선언할 때는 c, c++, java 언어와 달리 변수의 자료형을 지정하지 않으면 입력되는 데이터의 # 타입에 따라서 자동으로 변수의 타입이 결정된다. # '='는 같다라는 의미로 사용되지 않고 '=' 오른쪽의 데이터러를 '=' 왼쪽의 기억장소에 저장시키라는 # 의미로 사용된다. => 대입문 => ...
""" Example usage of the TF_IDF_Scratch class """ from extract_keywords_tfidf_scratch import TF_IDF_Scratch def main(): # Example corpus docs = [ "Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpos...
import datetime def file_str(): """Generates a datetime string in a good format to save as a file Returns: str: String with the datetime in a good format to save as a file """ return datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if __name__ == '__main__': # Save a file using a goo...
import math from dataclasses import dataclass @dataclass class Point: lat: float lon: float def distance(point1: Point, point2: Point): lon1, lat1, lon2, lat2 = map( math.radians, [point1.lon, point1.lat, point2.lon, point2.lat] ) return 6371 * ( math.acos( ...
#!/usr/bin/env python """ Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion This module prints the amount of money that Lakshmi has remaining after the stock transactions Lakshmi bought some shares sometime ago. She later sold them. On both occasions, she had to pay the stockbroker for his/her s...
import numpy as np class Immovable: """ Base class to specify the physics of immovable objects in the world. """ def __init__(self, position, traversable, transparent): """ Construct an immovable object. Keyword arguments: position -- permanent position of the...
from math import gcd def find_sum(): sum=0 for i in range(1000): if(i%3==0 or i%5==0): sum+=i return sum res=find_sum() #print(res) '''Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5...
import time class Timer(): def __init__( self ): self.times = {} self.startTime = time.time() def end( self, name ): if name not in self.times.keys(): self.times[name] = 0 endTime = time.time() self.times[name] += endTime-self.startTime ...
# List a = [1, 2, 3] print(a) a = [1, # item1 2, # item2 3, # item3 4, # item4 5] # item5 print(a) # Tuple b = (1, 2, 3) print(b) b = (1, # item1 2, # item2 3, # item3 4, # item4 5) # item5 print(b) # Dictionary c = {"k1": 1, # item1 "k2": 2, # item2 "k3...
class Puzzle: def __init__(self, status, depth, direction=None, cost=0, parent=None): self.status = status self.depth = depth self.direction = direction self.cost = cost self.parent = parent def show_map(self): for idx, i in enumerate(self.status): ...
#if character== 'a' or character=='e'or character=='i'or character=='o'or character=='u': # print("vowel") #elif character== 'A' or character=='E'or character=='I'or character=='O' or character=='U': # print("vowel") #elif character not in 'aeiouAEIOU': # print("consonent") #else: # print("n...
character = input("please input a character:") if character>= 'a' and character<='z': print("lower case") elif character>='A' and character<='Z': print("uppercase") else: print("not a character")
# CONDITIONALS x = 7 # Basic If if x < 6: # block 代码块 print("this is true") # print("ok") # If Else # if x < 6: # print("This is true") # else: # print("This is false") # Elif color = 'red' # if color == 'red': # print("Color is red") # elif color == 'blue': # print("Color is blue") # else: # print...
import matplotlib.pyplot as plt import numpy as np l1=int(input("enter the length of x[n]=")) x=np.arange(l1) print("enter x[n] values=") for i in range(0,l1): x[i]=int(input( )) n=l1 while (n>=1): y[n]=x[n] n=n-1 print("y[n]=",y)
def genPrimes(): possiblePrime = 2 while True: isPrimeNumber = True for num in range(2, int(possiblePrime ** 0.5) + 1): if possiblePrime % num == 0: isPrimeNumber = False break if (isPrimeNumber == True): yield possiblePrime ...
import string def build_shift_dict(shift): mapping = {} alphabet = string.ascii_lowercase + string.ascii_lowercase[: shift] for i in range(len(alphabet)): try: mapping.update({ alphabet[i]: alphabet[i + shift] }) except IndexError: break mapping.update(dict...
import turtle import random import math class MyTurtle(turtle.Turtle): radius = 0 def __init__(self): turtle.Turtle.__init__(self, shape="turtle") def kuklos(self, x, y, radius=(random.randrange(10, 500, 1))): self.penup() self.setposition(x, y) self.pendown()...
class Point(): def __init__(self, x, y, curve): self.x = x self.y = y self.curve = curve def copy(self): return Point(self.x, self.y, self.curve) def doIExist(self): return ((self.y**2) == (self.x**3 + self.x*self.curve.A + self.curve.B)) ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def get_minimum_node(self, lists:list) -> ListNode: minimum = lists[0] for item in lists: if item.val < minimum.val: minimum = item return minimum def ...
class LinkNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverse(self, head): if head is None or head.next is None: return head ptr = head prev = None while ptr: next_ptr = ptr.next ...
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swap(self, head : ListNode) -> ListNode: prev = head_new = ListNode(0) prev.next = head while prev.next and prev.next.next: first, second = prev.next, ...
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def sort_list(self, head : ListNode): if not head or not head.next: return head # break into two list prev = slow = fast = head while fast and fast....
array1 = [1, 2, 3, 5, 7, 8, 9, 10] array2 = [1, 2, 4, 8, 9] print("Given Arrays:") print(array1) print(array2) result = list(filter(lambda x: x in array1, array2)) print ("\nIntersection of two given arrays: ",result)
subject_marks = [('Red', 5), ('Blue', 10), ('Green', 15), ('Yellow', 12)] print("Original list of tuples:") print(subject_marks) subject_marks.sort(key=lambda x: x[1]) print("\nSorting the list of tuples:") print(subject_marks)
vowels = ('a', 'e', 'i', 'o', 'i', 'u') index = vowels.index('i') print('The index of e:', index)
import os def password_validation_part_one(condition, password): condition_ocurrence, condition_value = condition.split() start_occurence, stop_occurence = condition_ocurrence.split("-") if int(start_occurence) <= int(password.count(condition_value)) <= int(stop_occurence): return True else: ...
import os def find_two_numbers(number_list: list) -> tuple: search_sum = 2020 for number in number_list: # number_list.remove(number) remaining = search_sum - number if remaining in number_list: return (number, remaining) def find_three_numbers(number_list: list) -> tuple: ...
# Calculating full results for each province in each chamber (House and Senate)------------------------------- import pandas as pd class DataInput: """ This class has 3 extractors. All of them take a raw Pandas Dataframe as input 1) csv_extractor takes the results for all provinces and returns new arran...
#! /usr/bin/python """labyrinth constructs and updates the game.""" import random from pathlib import Path from typing import List, Tuple from settings import ( WALL_CHAR, ROAD_CHAR, START_CHAR, FINISH_CHAR, POSSIBLE_ITEMS_CHAR, QUIT_APP, ) class Item: """Keeps the state of attributes.""...
import sqlite3 DATABASE = "file/bbl.db" INSERT_QUERY_SEPARATOR = ", " INSERT_QUERY_PLACEHOLDER = "?" def drop_table(table): sql = "DROP TABLE IF EXISTS {}".format(table) execute(sql) def create_table(table, columns): # Trim columns tuples to only first two values (name and type) formatted_col...
a = [1, 10, 5, 2, 1, 5] def bubble_sort(array): n = len(array) for j in range(n-1, 0, -1): print('j = %d' %j) #print('array = %d' % array[j]) for i in range(0, j, +1): if array[i+1] < array[i]: print('i = %d' % i) #print('array = %d' % array[i]) temp = array[i] array[i] = array[i+1] arr...
def file_line_to_int_array(filename): my_list = [] with open(filename) as fp: line = fp.readline().rstrip() while line: entries = str.split(line, ',') for e in entries: my_list.append(int(e)) line = fp.readline() return my_list def test_f...
def getLines(filename, to_int=True): my_list = [] with open(filename) as fp: line = fp.readline() while line: entry = line if to_int: entry = int(entry.rstrip('\n')) my_list.append(entry) else: my_list.append(en...
import turtle as tl screen=tl.getscreen() tl.title("Draw Japan Flag") #all color between 0 to 1 turtle_speed=200 tl.speed(turtle_speed) starting_point=tl.position() bg_color=(.4,.6,.2) tl.bgcolor((bg_color)) #height and width of flag 10:6 flag_width=300 flag_height=flag_width*.6 #radius of flag radius=flag_width/5 de...
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: pd.set_option("display.max_columns" , None) pd.set_option("display.float_format" , lambda x : "%.4f" % x) pd.se...
#!/bin/python3 import math import os import random import re import sys # Complete the bigSorting function below. #Fails 4 test cases because of not executing on time def bigSorting(unsorted): ans = [] for i in range(len(unsorted)): ans.append(int(unsorted[i])) ans.sort() for i in range(len(an...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'getTotalX' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER_ARRAY b # #DID NOT SOLVE ALL THE TEST CASES def getTotalX(a, b): ...
#!/bin/python3 import os # Complete the designerPdfViewer function below. def designerPdfViewer(h, word): heightlist = [] letterlist = [] for i in range(ord('a'), ord('z') + 1): letterlist.append(chr(i)) print(letterlist) for i in range(len(letterlist)): for j in range(len(word)):...
r""" Command line argument parameters. """ from argparse import ArgumentParser def command_line_parser(): r""" Create a command line parser object. :return: a command line parser object. """ parser = ArgumentParser() parser.add_argument("path_file", help="the tecplot file containing paths/dom...
#!/usr/bin/env python # The policy iteration algorithm. import numpy as np def return_policy_evaluation(p, u, r, T, gamma): # newU = np.zeros(12) # in case of returnitg new utulities, there are more iterations (24 VS 33) for state in range(len(u)): u[state] = r[state] + gamma * np.dot(u,...
print("Determinar si un número par o impar") num=int(input("Introduzca un número: ")) if num/2==0: print("El número es par") else: print("El número es impar")
def SelectionSort(lst): #сортировка выбором for i in range(0, len(lst)-1): min= i for j in range (i+1,len(lst)): if lst[j]< lst[min]: min=j lst[i], lst[min] = lst[min], lst[i] print("Сортировка выбором:", lst) def heapsort(lst): ...
import unittest from play import Play from card import Card, CardSuit, CardValue class GameTest(unittest.TestCase): def setUp(self): self.play = Play() def test_init(self): self.assertEqual(self.play.cards, []) def test_append(self): # Setup card = Card(CardValue.TEN, Card...
print ('--------------------------') print (' Financiamento de Moradia ') print ('--------------------------') valor = float(input('Qual o valor do imóvel que você gostaria de comprar? \n')) sal = float(input('Qual o seu salário atual? \n')) anos = int(input('Em quantos anos você gostaria de pagar o imóvel? \n')) prest...
print ('----------------------------------') print (' Confederação nacional de natação') print ('----------------------------------') nome = str(input('Digite seu nome: \n')) idade = int(input('Digite sua idade: \n')) if idade <= 9: print ('{}, você está inscrito na categoria MIRIM'.format(nome)) elif idade > 9 a...
#!/usr/bin/python """ Problem: http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/ """ def count_triplete(alist, val): """ Per each element (base) we build all the triplete possibile, you get the second element (pvt) and then look for all other third element. S...
#!/usr/bin/python from datastructures import LinkedList import random class LinkedListSorted(LinkedList): def sort(self): """ This implementaion use bubble sort and switch only values, I am aware that complexity worst case will be O(N^2) """ had_switched = True ...
#!/usr/bin/python """ Question: Given the head of a linked list, reverse it. Head could be None as well for empty list. Input: None 1 --> 2 --> 3 --> None Output: None None --> 3 --> 2 --> 1 """ class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node ...
""" Given a sorted list of integer And a desired value to look for Then implement a binary search to return the position of the element Or -1 if the value has been not found """ CODE_VALUE_NOT_FOUND = -1 def binary_search(lst, value): if lst is None: return CODE_VALUE_NOT_FOUND else: ...
def factorial (n): res = 1 for i in range(1 , n+1): res = res*i return res print(factorial(10))
def factorial (n): x = 1 for i in range(1, n+1): x = x * i return x print(factorial(10))
# datas = [10,4,8,5,7,2,9] def sortList(datas): index = len(datas) for i in range(index): for j in range(index-1): if(datas[j] > datas[j+1]): temp = datas[j] datas[j] = datas[j+1] datas[j+1] = temp return datas print(sortList([10,4,8,...
datas = [10, 4, 8, 5, 7, 2, 9] def sortList(list): for i in range(0, len(list) - 1): # 有n-1回合(n為數字個數) for j in range(0, len(list) - 1 - i): # 每回合進行比較的範圍 if list[j] > list[j + 1]: # 是否需交換 tmp = list[j] list[j] = list[j + 1] list[...
def factorial (n): sum=1 ans=0 for i in range(1,n+1): sum*=i ans+=sum return ans print(factorial(10))
def factorial (n): if n==1: return n else: result = n*factorial(n-1) return result print(factorial(10))
# datas = [10,4,8,5,7,2,9] def sortList(datas): n=len(datas) for i in range(0,n-1): for j in range(0,n-i-1): if datas[j]>datas[j+1]: datas[j],datas[j+1]=datas[j+1],datas[j] return datas print(sortList([10,4,8,5,7,2,9]))
# # @lc app=leetcode id=119 lang=python # # [119] Pascal's Triangle II # # https://leetcode.com/problems/pascals-triangle-ii/description/ # # algorithms # Easy (44.74%) # Total Accepted: 219.9K # Total Submissions: 490.7K # Testcase Example: '3' # # Given a non-negative index k where k ≤ 33, return the kth index ro...
from tkinter import * from tkinter.ttk import * import random # creating tkinter window root = Tk() l1 = Label(root, text = "Tic Tac Toe",font =('Verdana', 15)) l1.pack(fill = BOTH, expand= True,pady = 10) l1.config(anchor=CENTER) l2 = Label(root, text = "You are O and computer in X",font =('Verdana', 15...
#! /usr/bin/env python3 import matplotlib.pyplot as plt from karmedbandit import KArmedBandit class KABTestBed(KArmedBandit): """ Testbed for running multiple independent k-armed-bandit simulations. Follows Sutton and Barto, Chapter 2. """ def __init__(self,runs=2000,k=10,steps=1000, ...
from FBI_Dataset import get_years_sheet sheet = get_years_sheet() class CrimeResult: most_crimes = 0 name = '' year = '' def compare_crimes_amount_and_get_result(amount_to_compare, result): if result.most_crimes < amount_to_compare: result.most_crimes = amount_to_compare result.year...
s1=int(input("toplamak istediğiniz 1.sayı")) s2=int(input("toplamak istediğiniz 2.sayı")) if s1 + s2 : print(s1+s2) if kullanmadan yapmak isterseniz s1=int(input("toplamak istediğiniz 1.sayı")) s2=int(input("toplamak istediğiniz 2.sayı")) z=s1+s2 print(z)
## Author: {Tobias Lindroth & Robert Zetterlund} import numpy as np import pandas as pd import sys import matplotlib.pyplot as plt # Which countries have high life expectancy but have low GDP? # For the sake of the assignment, # lets assume that high and low represents is based on the standard deviation. # To which ex...
# Author: {Tobias Lindroth & Robert Zetterlund} import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from sklearn.metrics import plot_confusion_matrix from sklearn.model_selection import train_test_split # task 3 # Use k-nearest neighbours to classify the iris data set with some ...
## Author: {Tobias Lindroth & Robert Zetterlund} import numpy as np import pandas as pd import sys import matplotlib.pyplot as plt # For the sake of the assignment, # lets assume that high and low represents is based on the standard deviation. # To which extent can be set by adjusting the variable STD_CONSTANT below ...
n = int(input()) a = 1 for a in range(1,6): if(a<6): print(n*a,end=" ")
print("Hello World") for numbers in range(1,100): if numbers%3==0 and numbers%5==0: print("FizzBuzz") elif numbers%3==0: print("Fizz") elif numbers%5==0: print("Buzz") else: print("numbers")
#Move all the negative elements to one side a = [-1, 2, -3, 4, 5, 6, -7, 8, 9] print(a) def negativeSort(a): left = 0 right = len(a) -1 while left <= right: if a[left] < 0 and a[right] < 0: left += 1 elif a[left] > 0 and a[right] < 0: a[...