text
stringlengths
37
1.41M
class InvSet: """ Inverse Set: a set which contains all values _except_ those specified. Interoperable with builtin `set` and `frozenset` classes wherever possible. Is not iterable: how would you iterate all values?? """ def __new__(self, iterable=()): if isinstance(iterable, InvSet): ...
def longest_palindrome(string): if not string: return 0 string_list = list('#{}#'.format('#'.join(string))) p = [0 for _ in string_list] m = n = c = r = 0 for i, elem in enumerate(string_list[1:], 1): print p if i > r: p[i] = 0 m = i - 1 n...
import functools class ExplainableResult: """ Object to fetch the result from an iterator, and optionally the explanation for that result. See `yields_why` for usage. """ def __init__(self, iterator): try: self.result = next(iterator) except StopIteration as exc: ...
# -*- coding: utf-8 -*- class Field(object): def __init__(self,pos,propert='empty'): self.dic = {'empty':0,'dirt':1,'obstacle':2,'wall':3} self.pos = pos self.property = self.dic[propert] self.visited = False def setProperty(self,propert): self.property = self.d...
#!env /usr/bin/python def add(a,b): print(f"ADDING {a} + {b}") return a+b def substract(a,b): print(f"SUBSTRACTING {a} - {b}") return a-b def multiply(a,b): print(f"MULTIPLYING {a}*{b}") return a*b def divide(a,b): print(f"DIVIDING {a}/{b}") return a/b print("Let's do some math with ju...
# 变量和名字 # 给变量 cars 赋值 cars = 100 # 给变量 space_in_a_car 赋值 space_in_a_car = 4.0 # 给变量 drivers 赋值 drivers = 30 # 给变量 passengers 赋值 passengers = 90 # 计算 cars - drivers 的值 cars_not_driven = cars - drivers # 给变量 cars_driven 赋 drivers 的值 cars_driven = drivers # 计算 cars_driven * space_in_a_car 的值 carpool_capacity = cars...
# 阅读文件 # open():用于打开一个文件,创建一个 file 对象 # read():用于从文件读取指定的字节数,如果未给定或为负则读取所有。 # 导入 sys 的 argv 模块 from sys import argv # 获取文件名 script, filename = argv # 打开一个文件 txt = open(filename) # 打印 print(f"Here's your file {filename}:") # 读取文件字节数 print(txt.read()) # 打印 # print("Type the filename again:") # # 用户输入 # file_again = ...
directions = ("south", "north", "west", "east", "center") verbs = ("go", "kill", "eat", "run", "tell", "shoot", "sing", "love") stops = ("the", "in", "of", "to", "via") nouns = ("bear", "princess", "MissHei", "tiger", "dragon") stuff = input("> ") words = stuff.split() sentence = [] for word in words: if word in...
# Program to grab a file and alphabetize its contents, creating a new .txt file # with everything alphabetized. name = input('Enter name of file to be alphabetized:') # Input function in python prints out a statement for the user to read, then allows them to input characters, which is returned as a string. ...
#Social Computing CS522 #Programming Assignment #7 #(Submission Deadline: 5th November 2020) #Note: The functions given in the assignment are based on link prediction. #If there is any query related to assignment you should ask at least 48 hours before the deadline, no reply would be given in case you ask during the ...
# 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, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not # exceed four million, find the sum of the even-valued terms....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 31 20:50:50 2021 @author: lesliecastelan Professor: Hangjie Ji Discussion: 3B """ #%% class Node: """Node class for individual units within LinkedList class Has next member function, therefore for usage within singly linked list...
#1 with open('gregor.txt') as f: for line in f: print(line, end='') #2 def dict_to_file(d, filename): with open(filename, 'w') as f: for k, v in d.items(): print(k, file=f) print(v, file=f) #3 def dict_from_file(filename): d = {} with open(filename) as f: ...
#Q1 def sorted_words(s): l = s.split() l.sort() return l #Q2 def sorted_words(s): return sorted(s.split()) #Q3 def setify(l): l2 = [] for x in l: if x not in l2: l2.append(x) return l2 #Original from chapter 4 def histogram(l): unique = setify(l) for x in unique: p...
def print_stats(l): print(str(min(l)) + ' up to ' + str(max(l))) def print_stats(l): minimum = min(l) maximum = max(l) print(f'{minimum} up to {maximum}') def print_stats(l): print(f'{min(l)} up to {max(l)}') def print_powers(n): for x in range(1, n): print(f'{x} {x ** 2} {x ** 3} {x...
import math #1 def round(x): c = math.ceil(x) f = math.floor(x) if c - x <= x - f: return c else: return f #2 def between(a, b): x0, y0 = a x1, y1 = b return ((x0 + x1) / 2, (y0 + y1) / 2) #3 def parts(x): if x < 0: a, b = parts(-x) return (-a, b) e...
import math def divisors(n): if n < 2: return set() if n == 2: return set([1]) limit = math.ceil(math.sqrt(n)) divisors = set() for d in range(2, limit + 1): if (n % d == 0): divisors.add(d) m = n // d ...
#! python3 def main(): a = 999 maximum = [0, 0, 0] while a != 99: b = a while b != 99: n = a * b if is_palindrome(n) and n > maximum[2]: maximum = [a, b, n] b -= 1 a -= 1 return maximum[2] def is_palindrome(num): ...
import random, turtle, tkinter def guess_game(): def color(guess_x,guess_y,randvalue_x,randvalue_y): turtle.setpos(guess_x,guess_y) turtle.fillcolor(guess) turtle.begin_fill() turtle.circle(100) turtle.end_fill() turtle.setpos(randvalue_x,randvalue_y) ...
from tabuleiro import Tabuleiro import random import datetime import os # Quebra Cabeça 8 peças class Puzzle: def __init__(self, posicoes, objetivo): self.posicoes = posicoes self.objetivo = objetivo self.tabuleiro = Tabuleiro(posicoes, self.objetivo) self.visitados = [] self...
#Given two points, p1 and p2, check if p1 is clockwise from p2 with respect from the origin. #this uses the cross product of 2d vectors and the fact that the sign of the result of that product #will tell us whether p1 is clockwise from p2 or not. #this algorithm comes from the computational geometry section of CLRS. #...
"""Program that outputs one of at least four random, good fortunes.""" __author__ = "730395734" # The randint function is imported from the random library so that # you are able to generate integers at random. # # Documentation: https://docs.python.org/3/library/random.html#random.randint # # For example, consider t...
# Author: Liam Hooks lrh5428@psu.edu def represent( letter ): if letter == "A": return 4.0 elif letter == "A-": return 3.67 elif letter == "B+": return 3.33 elif letter == "B": return 3.0 elif letter == "B-": return 2.67 elif letter == "C+": return 2.33 elif letter == "C": ret...
# -*- coding:utf-8 -*- """ 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 """ """ 题目分析,假设f[i]表示在第i个台阶上可能的方法数。逆向思维。如果我从第n个台阶进行下台阶,下一步有2中可能, 一种走到第n-1个台阶,一种是走到第n-2个台阶。所以f[n] = f[n-1] + f[n-2]. 那么初始条件了,f[0] = f[1] = 1。 所以就变成了:f[n] = f[n-1] + f[n-2], 初始值f[0]=1, f[1]=1,目标求f[n]。 """ class Solution: def jump...
string, substring = (input().strip(), input().strip()) print(sum([ 1 for i in range(len(string)-len(substring)+1) if string[i:i+len(substring)] == substring]))
import json from difflib import get_close_matches data = json.load(open("data.json")) def translate(_word): _word=_word.lower() if _word in data: return data[_word] elif _word.title() in data: return data[_word.title()] elif len(get_close_matches(_word,data.keys())) > 0: yn = i...
def Average(string): list_of_string = list(string.split(" ")) Total = 0 for num in list_of_string: integer = int(num) Total += integer print(Total/len(list_of_string)) Average("12 11 2 6 7 10")
def insertionSort(arr, index): tmp_val = arr[index] j = index - 1 while j >= 0 and arr[j] > tmp_val: arr[j+1] = arr[j] j -= 1 arr[j+1] = tmp_val len_arr = int(input()) arr = [int(x) for x in input().split()] for i in range(1,len_arr,1): insertionSort(arr, i) print(' '.j...
BOARD_SIZE = 7 def check_for_horizontal_win(board): for row in range(BOARD_SIZE): start_column = 0 end_column = 4 while end_column != BOARD_SIZE + 1: board_slice = board[row][start_column : end_column] piece_set = set(board_slice) if len(piece_set) == 1 a...
#Newton-Raphson method to find a real root of an equation*********** from __future__ import division, print_function import numpy as np import math x0=input ('enter the initial approx') tol=input('enter the tolarence value') n=range(100) print("itr, x") f= lambda x: 3*x-math.cos(x)-1 df=lambda x: 3+math.sin(x) for i in...
import random import string import sys from threading import Timer def text_captcha(): """ It generates a captcha and asks user to verify within 9 seconds. """ captcha = string.ascii_lowercase + string.ascii_uppercase + \ "".join([str(i) for i in range(0, 10)]) captcha_random = '' ...
i = 0 while i == 0: print("") n1 = input ("Type in 1st number. Type 'end' to end -> ") if n1 == "end": print("ended") print() break print("+") print("-") print("x") print("%") op = input ("Select Operation. Type 'end' to end-> ") if op == "end": ...
go = 0 while go == 0: import math def palindrome(s): mid = math.floor(len(s)/2) x = len(s) for i in range (mid): j = -(i+1) if s[i] != s[j]: return False return True userInput = input ("Type in word. Type 'end' to end. ") ...
y = input ("enter a number") y = int (y) i= 0 for c in range (y): i = i+c+1 print (i)
import tkinter as tk window = tk.Tk() car = tk.PhotoImage(file="car1.png",width=280,height=140) img = tk.Label(master=window,image=car) img.pack(side=tk.TOP) f = tk.Frame(bg="navy") f.pack() lbl=tk.Label(master = f,text= "Can you drive?",width=35,height=10,font = ("Arial", 10),fg="Orange",bg="Navy") lbl.p...
# coding: utf-8 import pandas as pd # read excel file and return first 2 rows path=r'Test.xlsx' df=pd.read_excel(path) df.head(3) # filter the records df1=df[df['discharge_disposition_id']!="Expired"] # save the preProcess to the new file writer_noExpired=pd.ExcelWriter('noExpired.xlsx',engine='xlsxwriter') df1.to...
while True: alhpa = input() if alhpa != 'q': print(alhpa) else: print(alhpa) break
''' 문제 두 정수 A와 B를 입력받은 다음, A×B를 출력하는 프로그램을 작성하시오. ''' # solution num1, num2 = map(int, input().split()) print(num1*num2)
# 비효율적인 소수 판별 알고리즘 # 2 부터 X - 1 까지의 모든 자연수로 나누었을때 나누어 떨어지는 수가 하나라도 있으면 소수 아님 # 소수 판별 함수 - 시간복잡도 O(x) def is_prime_number(x): # 2부터 (x - 1)까지의 모든 수를 확인하며 for i in range(2, x): # x가 해당 수로 나누어 떨어진다면 if x % i == 0: return False # 소수 아님 return True # 소수임 # 모든 자연수로 나눈다는 것은 비효율적이...
""" 문제 두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오. """ num1, num2 = map(int, input().split()) if num1 > num2: print('>') elif num1 == num2: print('==') else: print('<')
""" You are given a non-empty array of arrays. Each subarray holds three integers and represents a disk. These integers denote each disk's width, depth, and height, respectively. Your goal is to stack up the disks and to maximize the total height of the stack. A disk must have a strictly smaller width, depth, and heigh...
""" Given an array of positive integers representing coin denominations and a single non-negative integer representing a target amount of money, implement a function that returns the smallest number of coins needed to make change for that target amount using the given coin denominations. Nonte that an unlimited amount ...
""" Write a class from a suffix-trie-like data structure. The class should have a "root" property set to be root node of the trie. The class should support creation froma a string and the searching of strings. The creation method will be called when the class is instantiated and shuld populate the root property of the ...
""" You are given a two-dimensiona array(matrix) of potentially unequal height and width containing letters. This matrix repreents a boggle board. You are also given a list of words. Write a fucntion that returns an array of all the words contained in the boggle board. A word is constructed in the boggle board by conn...
""" Given an array of positive integers representing coin denominations and a single non-negative integer representing a target amount of money, impolement a function that returns the number of ways to make change for that target amount using the given coin denominations. Note that an unlimited amount of coins is at yo...
from abc import ABC, abstractmethod from collections import defaultdict from random import choice, random from pprint import pformat import numpy as np class Agent(ABC): """ Base Agent """ def __init__(self, action_space): self.action_space = action_space @abstractmethod def act(self, obser...
#!./venv/bin/python # ------------------------------------------------------------------------------ # Copyright (c) 2019. Anas Abu Farraj # ------------------------------------------------------------------------------ """Movie Name Manager app Enter 'a' to add movie, 'l' to list movie, 'f' to find movie, and 'q' to...
import math input = 34000000 def present_number(house, primes): divisors = get_divisors2(house, primes) # print(house, divisors) return sum([d * 10 for d in divisors]) # Naive implementation def get_divisors(n): i = 1 d = [n] while i <= n / 2: if n % i == 0: d.append(i) ...
class graph(): def __init__(self,n): self.vertex={} self.n=n def add_edge(self,from_v,to_v): if from_v not in self.vertex.keys(): self.vertex[from_v]=[to_v] else: self.vertex[from_v].append(to_v) def detect_cycle(self): #0-wh...
# Creating a Tuple id = (1, 2, 3, 4) name = ("sam", "sandy", "sharma", "sharmaJi") age = (22, 23, 25, 20) salary = (2500, 2500, 2500, 2500) tuples = (id,name,age,salary) print(f'Creating a tuples', tuples) # Indexing is same as list # Accessing element # Top level print(f'accessing elements top level: ', tuples[1]) ...
import torch import torch.nn as nn import torch.nn.functional as F num_classes = 2 # define the CNN architecture class Net(nn.Module): ### TODO: choose an architecture, and complete the class def __init__(self): super(Net, self).__init__() ## Define layers of a CNN self.conv1 = nn.Conv2...
import os def rename_files(): # 1) get file names for a folder dir_path = os.getcwd() + "/prank/" file_list = os.listdir(dir_path); #print(file_list) # 2) for each file, rename filename. try: #print(os.name) for file in file_list: os.rename(dir_path+file, dir_path+fi...
# Multiples of 3 and 5 ## Problem 1 """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6, and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def multiples(threshold): seq = (i for i in range(threshold) \ if i % ...
import argparse def encrypT(key): ascii_value = 0 crypt = '' for letter in key: if ord(letter) >=120: ascii_value = ord(letter)-23 crypt += chr(ascii_value) else: ascii_value = ord(letter)+3 crypt += chr(ascii_value) return crypt def decrypT(key): ascii_value = 0 crypt_rev = '' for lette...
''' Problem: Create a function that takes a string (without spaces) and a word list, cleaves the string into words based on the list, and returns the correctly spaced version of the string (a sentence). If a section of the string is encountered that can't be found on the word list, return "Cleaving stalled: Word not f...
import wikipedia class WikiAPI: """ Class used to communicate with Wikipedia API ... Methods ------- search(string) Returns wikipedia search titles (string) get_search_result(string) Returns the summary, url and title of the wikipedia search based on "search" met...
class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ nums = [int(i) for i in str(num)] result = reduce(lambda x, y: x + y, nums) if result >= 10: result = self.addDigits(result) return result if __name__ ==...
#!/usr/bin/env python # encoding: utf-8 # Definition for binary tree with next pointer. class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: # @param root, a tree link node # @return nothing def con...
from typing import List class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return n = len(matrix) m = len(matrix[0]) # 记录第一行第一列是否存在需要变化的可能 y...
# -*- coding: utf-8 -*- """ Created on Wed Jan 24 10:38:18 2018 @author: DAMI """ import csv import re with open ("dates.txt") as out: reader = csv.reader(out) text = out.readlines() formatted_dates = [] for j in text: regex2 = re.findall(r'\d{2}[/-]\d{2}[/-]\d{2,4}',str(j)) or re.findall(r'(?:\d{2} )(...
annual_salary = int(input("What is your annual salary? ")) portion_saved = float(input("What percent of your annual salary will be saved? ")) total_cost = int(input("How much does your dream home cost? ")) portion_down_payment = total_cost * float(input("What percentage of the total cost of the house do you need for th...
number=int(input("Enter a number: ")); if number % 4 == 0: print("multiple of 4") if number%2==0: print("Even") else: print("Odd") num = int(input("Give me a number ")) check = int(input("Give me a number ")) if num % 2 == 0: print("Even") else: print("Odd") if num % check == 0: print("divide...
import random a = random.randint(1, 9) kiek=0; while True: inpt=input("Guess the number:") if inpt=="exit": break if inpt.isnumeric(): if a==int(inpt): print("Corect, you did",kiek,"guesses") print("Play again") a = random.randint(1, 9) kiek=0...
numbers = [] for i in range(5): numbers.append(int(input("Please enter a number"))) current = 0 for i in range(5): print("Number: {:<3}".format(numbers[current])) current = current + 1 print("The first number is {}".format(numbers[0])) print("the last number is {}".format(numbers[4])) print("the smalles nu...
#Source: https://pimylifeup.com/raspberry-pi-humidity-sensor-dht22/ #Importing Packages import Adafruit_DHT #Intializing Temperature and Humidity Sensor DHT_SENSOR = Adafruit_DHT.DHT22 DHT_PIN = 4 #Repeat while True: #Read humidity and temperature humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, D...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Fazil Smm # # Created: 21-06-2017 # Copyright: (c) Fazil Smm 2017 # Licence: <your licence> #----------------------------------------------------------------------------...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Fazil Smm # # Created: 20-06-2017 # Copyright: (c) Fazil Smm 2017 # Licence: <your licence> #----------------------------------------------------------------------------...
def splictArr(arr,j,k): for i in range(0,k): x = arr[0] for j in range(0,n-1): arr[j]=arr[j+1] arr[n-1]=x arr=[12,10,5,6,53,37] n=len(arr) position=2 splictArr(arr,n,position) for i in range(0,n): ...
import string LISTA_SIMBOLOS = list(string.digits) + list(string.ascii_uppercase) def converter_entre_bases(base_a,base_b,numero_base_a): """função de conversão genérica""" numero_decimal = converter_base_x_decimal(base_a,numero_base_a) if(base_b == 10) return numero_decimal numero_base_b = converter_d...
class Conjunto: def __init__(self): self.elementos = [] def gerar_conjunto_partes(self): lista_elementos = self.elementos.copy() tamanho = len(lista_elementos) subconjunto = [] for i in range(2**tamanho): for k in range(tamanho): if i&1<<k: ...
""" Napoleon choosed a city for Advertising his company's product. There are streets in that city. Each day he travels one street. There are buildings in a street which are located at points . Each building has some height(Say meters). Napoleon stands at point . His height is . Now Napoleon starts communicating with t...
""" Vikas is given a bag which consists of numbers (integers) blocks,Vikas has to organize the numbers again in the same order as he has inserted it into the bag, i.e. the first number inserted into the bag by Vikas should be picked up first followed by other numbers in series. Help Vikas to complete this work in O(n)...
""" Tic Tac Toe Player """ import math import copy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who h...
# -*- coding:utf-8 -*- class Graph: def __init__(self, vertex_count: int) -> None: self.adj = [[] for _ in range(vertex_count)] def add_edge(self, s: int, t: int, w: int) -> None: edge = Edge(s, t, w) self.adj[s].append(edge) def __len__(self) -> int: return len(self.adj) ...
# -*- coding:utf-8 -*- ''' 109. Convert Sorted List to Binary Search Tree Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node neve...
# -*- coding:utf-8 -*- ''' 95. Unique Binary Search Tree Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. Example: Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corres...
# -*- coding:utf-8 -*- # 迪杰斯特拉算法适用于带权重的有向无环图(权重非负) # graph["a"] = {} # graph["a"]["fin"] = 1 # graph["b"] = {} # graph["b"]["a"] = 3 # graph["b"]["fin"] = 5 # graph["fin"] = {} ←------终点没有任何邻居 # infinity = float("inf") # costs = {} # costs["a"] = 6 # costs["b"] = 2 # costs["fin"] = infinity # parents = {} # parent...
# -*- coding:utf-8 -*- ''' 4. Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example: nums1 = [1, 3] nums2 = [2] The median is 2.0 nums1 = [1, 2] nums2 = [3, 4] ...
# -*- coding:utf-8 -*- def insert_sort(lists): ''' 插入排序 Best: O(n) Average: O(n^2) Worst: O(n^2) ''' count = len(lists) for i in range(1, count): key = lists[i] j = i - 1 while j >= 0: if lists[j] > key: lists[j + 1] = lists[j] ...
# -*- coding:utf-8 -*- def binary_search(array, target): first = 0 last = len(array) - 1 while first <= last: i = first + (last - first) / 2 if array[i] == target: return i elif array[i] > target: last = i - 1 elif array[i] < target: f...
print "Largest Number Exercise" # Print the largest number in the list num_list = [10, 24, 4, 14, 35, 31, 18] big_num = num_list[0] for num in num_list: if num > big_num: big_num = num print big_num
print "Sum the Numbers Exercise" # Given a list of numbers, print their sum. num_list = [1, 2, 3, 4, 5, 6] sum = 0 for num in num_list: sum += num print sum
fruits = ["Grapefruit", "Longan", "Orange", "Apple", "Cherry"] for idx, val in enumerate(fruits, start= 1): print("index is %d and value is %s" % (idx, val))
a = {1, 2, 3, 4} b = {1, 3, 5, 7} c = a | b d = a - b print("a is", a) print("b is", b) print("a | b is", c) print("a - b is", d) ab = [] ac = [] ad = [] for n in range(20): ab.append(n) x = range(3, 13) for n in x: ac.append(n) y = range(2, 51, 3) for n in y: ad.append(n) print(a...
W1 = ['Moday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] W2 = ['Saturday', 'Sunday'] W3 = W1 + W2 W4 = W1 + W2 W5 = W1 + W2 W6 = W1 + W2 W5.reverse() W4.sort() print("Weekday are", W1) print("Days are", W2) print("Sorted days are", W3) print("Sorted days are", W4) print("Reverse days are", W5) print("T...
while True: num = int(input("Enter an integer:")) number = num find = num % 2 if num < 0: False elif num >= 99: break elif find == 1: False else: print(number)
num = int(input("Enter a number to find the factorial:")) number = num total = 1 while num > 0: total = total * (num) num -= 1 print("Factorial of", number, "is", total)
""" Algoritmo responsavel por criar realizar busca em profundidade """ from Pilha import Pilha class Busca_Em_Profundidade: def __init__(self, inicio, objetivo): self.inicio = inicio self.inicio.visitado = True self.objetivo = objetivo #fronteira armazena pilha de cidades que ...
x = int(input("Insert the numerator: ")) y = int(input("Insert the denomiator: ")) if x%y == 0: print(x, " is divisible by ", y) else: print("No! ", x, " is not divisible by ", y)
for x in range(1,10): for y in range(1,10): print("%4d" % (x*y), end="") print()
# Enter your code here. Read input from STDIN. Print output to STDOUT actual_date, actual_month, actual_year = map(int, input().split()) expected_date, expected_month, expected_year = map(int, input().split()) if (actual_year, actual_month, actual_date) <= (expected_year, expected_month, expected_date): print...
def main(): for integer in range(1, 101): print("%-7i%-13s%-13s" % (integer, bin(integer), hex(integer))) return if __name__ == "__main__": main()
from math import sqrt def basel(n): # Compute the sum of 1 / k ** 2 for k=1 to n. total = 0 for k in range(1, n + 1): total += 1 / (k ** 2) return total def main(): print("%-13s%-13s%-13s" % ("n", "sum", "sqrt(6*sum)")) for n in range(1, 100001, 1000): print("%-13f%-13f%-13f...
""" """ class QwickSort: def partition(data, low, high): pivot = data[(low + high) // 2] i = low - 1 j = high + 1 while True: i += 1 while data[i] < pivot: i += 1 j -= 1 while data[j] > pivot: j -= 1 ...
num_estados = int(input('Ingrese numero de estados: ')) num_trans = int(input('Ingrese numero de transiciones: ')) Estados = [] Transiciones = [] for i in range(num_estados): if(i == 0): print('Introduce estado inicial: ') Estados.append(input()) else: print('Introduce estado :') ...
def get_file_contents(file_path): """ Reads the contents of a single-line txt file. :param file_path: A string representing the path of the file :return: A string containing the contents of the file """ file = open(file_path, 'r') new_sequence = file.read() file.close() return new_s...
points = [{"x":-1,"y":-1}] def setup(): size(800,600) def draw(): s = 10 for i in range(100): x = int(random(width)) y = int(random(height)) point = { "x": x, "y": y } pex = False # for p in points: # ...
#accessing elements from a tuple using position and finding value i=0; myTuple=("red","yellow","black"); print(myTuple); y=int(input("Which element would you like to access? Enter position")); print(myTuple[y-1]); #accessing elements from a tuple using value and finding position i=0; myTuple=("red","yellow","...
""" spiral.py ------------ Create helical plunges and spirals. """ import numpy as np import networkx as nx from . import graph from . import polygons from . import constants def offset(polygon, step): """ Create a spiral inside a polygon by offsetting the polygon by a step distance and then interpolati...
import cs50 # This program requests input from the user on how much change is owed. # It then calculates the minimum number of coins required to provide the change. def main(): while True: print("How much change do I owe you?") change = cs50.get_float() if change>0: break ...