text
stringlengths
37
1.41M
number = None while number is None: try: userinput = input("Enter an integer number: ") number = int(userinput) except: print() print("Error: ") print("Please try again") print() else: print("You entered the valid number: ", number)
print(type(1)) # <type 'int'> print(type(1.)) # <type 'float'> print(type(1+3j)) # <type 'complex'> print(type("hello")) # <type 'str'> print(type([1,2,3])) # <type 'list'> # mutable print(type((1,2,3)))...
# write a list with the ingredients salad, orange, mango # choose one element of the list # and write it to a file called "fruit.txt" fruit_list = ["salad", "orange", "mango"] chosen_fruit = fruit_list[1] with open("fruit.txt", "w") as f: f.write(chosen_fruit)
print(str(1)) print(type(1)) eingabe_1 = "1" eingabe_2 = "2" print(3 + 4) print(eingabe_1 + eingabe_2) # concat print(int(eingabe_1) + int(eingabe_2)) print(float(eingabe_1) + float(eingabe_2)) resultat_1 = int(eingabe_1) + int(eingabe_2) resultat_2 = float(eingabe_1) + float(eingabe_2) print(resultat_1, resultat_2...
capitals = {"France": "Paris", "Iceland": "Reykjavik", "Denmark": "Copenhagen", "Litauen": "Vilnius", "Canada": "Ottawa", "Austria": "Wien"} print("Study the following list:") print() print(capitals.items()) # [('Canada', 'Ottawa'), ('\xc3\x96sterreich', 'W...
#print True #print False # conditionals small_number = 100.0 big_number = 100 print(small_number > big_number) # False print(small_number < big_number) # True print(small_number == big_number) # False print(small_number != big_number) # True print(small_number is big_number)...
# Write a loop, which asks for an input, # until you entered a valid operator # hint: # "+" in "+-/*" # "+" in ["*", "+", "-", "/"] print("+-" in "+-/*") # True print("+-" in ["*", "+", "-", "/"]) # False operation = None while operation not in ["*", "+", "-", "/"]: operation = input("Please ente...
entry = input("Enter a number: ") my_number = float(entry) print("You entered {}".format(my_number)) print(type(my_number)) bigger_than_30 = my_number > 30 if bigger_than_30: print("You entered a high number") else: print("You entered a low number")
# create a new file called "my_library.py" # write the functions from the previous exercise in that library # import the file "my_library.py" # use one of the functions and print it's result # Hier eine andere Variante: import Class5_Python3.math_functions print(Class5_Python3.math_functions.digit_cutter(123.456789...
# write a shopping list # list should have the elements: "bread", "butter", "soup" # loop over the list and print each element with a sentence: # "I want to eat ..." (... should be replaced with the element) shopping_list = ["bread", "butter", "soup"] for food in shopping_list: print(f"I want to eat {food}")
capitals = {"France": "Paris", "Iceland": "Reykjavik", "Denmark": "Copenhagen", "Lithuania": "Vilnius", "Canada": "Ottawa", "Austria": "Vienna"} print(capitals["Japan"]) # this will make an error, KeyError
# Use GeoPy package from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="bimaplus-geolocation") # Ask a user for the input of the address address = input("Enter City, Country (e.g. Ljubljana, Slovenia): ") print("Location address:", address) # Get the location of the address and print it out to s...
# Segmentation can be done through a variety of different ways but the typical output is a binary image. # A binary image is something that has values of zero or one. # Essentially a one indicates the piece of the image that we want to use and a zero is everything else. # Binary images are a key component of many image...
a=int(input()) list=[] for i in str(a): list.append(int(i)) list.sort(reverse=True) for i in list: print(i,end='')
"""Manipulate numeric data similar to numpy `ulab` is a numpy-like module for micropython, meant to simplify and speed up common mathematical operations on arrays. The primary goal was to implement a small subset of numpy that might be useful in the context of a microcontroller. This means low-level data processing of...
"""Numerical and Statistical functions Most of these functions take an "axis" argument, which indicates whether to operate over the flattened array (None), rows (0), or columns (1).""" def argmax(array, *, axis=None): """Return the index of the maximum element of the 1D array""" ... def argmin(array, *, axis...
import matplotlib.pyplot as plt from sklearn import datasets,svm digits = datasets.load_digits() # loading the data clf = svm.SVC(gamma=0.0001,C=100) # tuning the model print(len(digits.data)) X,y = digits.data[:-1], digits.target[:-1] # getting ready with or input and target clf.fit(X,y) # fitting model print(...
import Forca import Adivinhação print("="*50) print(f"{'Escolha o seu Jogo':^50}") print("="*50) while True: jogo = int(input(""" Escolha um dos jogos disponíveis : |1| Forca |2| Adivinhação Defina o jogo : """)) if (jogo == 1): print("\nIniciando jogo da Forca ...\n\n") Forc...
""" 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5 (помните, что индексация начинается с нуля), т. к. именно в этих позициях первого массива стоят четные числа. """ import random even_...
""" 3. Написать программу, которая обходит не взвешенный ориентированный граф без петель, в котором все вершины связаны, по алгоритму поиска в глубину (Depth-First Search). Примечания: a. граф должен храниться в виде списка смежности; b. генерация графа выполняется в отдельной функции, которая принимает на вход число ...
""" 1. Проанализировать скорость и сложность одного любого алгоритма из разработанных в рамках домашнего задания первых трех уроков. 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. """ import timeit import cProfile import random def do_it(list_numbers): max_va...
import sys def count_trees(grid, dx, dy): x = 0 y = 0 trees = 0 max_x = len(grid[0]) while y < len(grid): if grid[y][x % max_x] == "#": trees += 1 x += dx y += dy return trees def part1(grid): return count_trees(grid, 3, 1) def part2(grid): pro...
import sys from collections import namedtuple ParsedLine = namedtuple("ParsedLine", ["l", "h", "letter", "pw"]) def part1(parsed_lines): return sum(p.l <= p.pw.count(p.letter) <= p.h for p in parsed_lines) def part2(parsed_lines): return sum( (p.pw[p.l - 1] == p.letter) ^ (p.pw[p.h - 1] == p.letter...
# -*- coding: utf-8 -*- print "1 choklad 10 kr" print "2 festis 8 kr" print "Tryck nummer för onskad vara" nr = int(raw_input(">>> ")) if nr == 1: print "mata in 10 kr" if nr == 2: print "mata in 8 kr" kr = int(raw_input(">>> ")) if nr == 1 and kr >= 10: print "choklad" print "Du får tillbaka %s k...
import random n = int(input("колво элементов в массиве:")) arr=[] for i in range(n): arr.append(random.randint(0,1000)) #step sorting for i in range(len(arr)): for j in range(0, len(arr) - i - 1): if arr[j] > arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) print(arr) find = int(inp...
arr=[42,123,3894,212,422] arr1=[] arr2=[] for i in range(0,3): arr1.append(arr[i]) for i in range(3,len(arr)): arr2.append(arr[i]) print(arr) print(arr1) print(arr2) arr3=arr1+arr2 print(arr3)
arr = [] sumi=0 n = int(input("Write count of array:")) #code print(arr) for i in range(n): number = int(input()) arr.append(number) print(arr) print(arr) for i in range(n): sumi = sumi + arr[i] print(sumi)
# def plus(a,b): # print(a+b) # plus(10,20) def print_arr(arr): for i in arr: print(i) a=[1,2,3,4,5] b =["asdsad","adsad",1231,3123] print_arr(b)
# Final Intro to CS project created by NYU Abu Dhabi '18 students Peter Hadvab (@jozozchrenovej)and Mark Surnin (@marksurnin). # To be continued... import random class Board: def __init__(self, textfile): ''' Board is represented as a textfile that is in the same directory as this file. Th...
import csv import csv with open("new_names.csv",'r') as csvf: read_csv=csv.reader(csvf) next(read_csv) for x in read_csv: print(x[2]) ''' OUTPUT:>>> john-doe@bogusemail.com maryjacobs@bogusemail.com davesmith@bogusemail.com janestuart@bogusemail.com tomwright@bogusemail.com' ''' wit...
list_of_numbers = [-2,-1,1,2,3,4,5,6,7,8,9] print(list_of_numbers) smallest = 1 for number in list_of_numbers: if number < smallest: smallest = number print("========================\nThe smallest number is ") print(smallest)
board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] # board display def print_board(board): for i in range(3): print() for j in range(3): print(board[i][j], end='') if j < 2: print('|', end='') # user input value def user_input(): ...
# Tic Tac Toe import random # Draws empty board def drawBoard(board): print(" "+board[7]+"| "+board[8]+" | "+board[9]+" ") print("---|---|---") print(" "+board[4]+" | "+board[5]+" | "+board[6]+" ") print("---|---|---") print(" "+board[1]+" | "+board[2]+" | "+board[3]+" ") # Makes player ...
def armstrong(number): temp = number sum1 = 0 print temp while temp > 0: digit = temp % 10 sum1 = sum1 + pow(digit, 3) temp = temp / 10 print sum1 if number == sum1: print "{} is armstrong".format(number) else: print "{} is not armstrong".format(number...
import time class BookingClass(object): business = "BUSINESS" economy = "ECONOMY" class SeatingArea(object): def __init__(self, booking_class, start_row, row_count, seats_per_row): self.booking_class = booking_class self.start_row = start_row self.row_count = row_count se...
from structure import ListNode class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: pp = None res = None p1 = l1 p2 = l2 while p1 is not None or p2 is not None: if p1 is None and p2 is not None: p = p2 ...
def quick_sort(nums, a, b): if b>=a: return pivot = nums[a] l, r = a, b while l < r: while l < r and nums[r] > pivot: r -= 1 if l < r: nums[l] = nums[r] l += 1 while l < r and nums[l] < pivot: l += 1 if l < r: ...
from structure import ListNode class Solution: def isPalindrome(self, head: ListNode) -> bool: pre = None slow = head fast = head while fast is not None and fast.next is not None: fast = fast.next.next tmp = slow.next slow.next = pre ...
import heapq from typing import List from structure import ListNode class MyNode: def __init__(self, node: ListNode): self.node = node def __lt__(self, other): return self.node.val < other.node.val class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: my_lis...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : qichun tang # @Date : 2021-01-26 # @Contact : qichun.tang@bupt.edu.cn from typing import List, Tuple class Solution: def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: if not matrix: return False ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : qichun tang # @Date : 2021-01-26 # @Contact : qichun.tang@bupt.edu.cn class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here if not pre: return None in_ix = tin.index(pr...
from structure import ListNode class Solution: def recurse(self, head: ListNode): # 写错↓ if head is None or head.next is None: return head # ←写错 last = self.recurse(head.next) head.next.next = head head.next = None return last su...
from typing import List import heapq def heap_sort(nums): heapq.heapify(nums) res = [] while nums: res.append(heapq.heappop(nums)) return res class Solution: def sortArray(self, nums: List[int]) -> List[int]: return heap_sort(nums) # import random # nums = list(range(10)) # ra...
from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) left, right, ret = [[0] * n for _ in range(3)] left[0] = 1 for i in range(1, n): left[i] = left[i - 1] * nums[i - 1] right[n - 1] = 1 for i i...
from typing import List class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: s_nums=sorted(nums) num2cnt={} for i,num in enumerate(s_nums): if num not in num2cnt: num2cnt[num]=i return [num2cnt[num] for num in nums]
from typing import List class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ z = nz = 0 n = len(nums) while z < n and nz < n: while z < n and nums[z] != 0: z += 1 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : qichun tang # @Contact : tqichun@gmail.com from structure import ListNode class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head: return head oddHead, evenHead = head, head.next odd, even = od...
# Import Dependencies = import random # Define all my global functions def scramble(word): word = list(word) random.shuffle(word) return ''.join(word) # The question def TheCyberKingQuestion1(): # At this point we will be requesting for the player to enter the source of the games data in a text ...
from random import randint from art import logo def guess_number(user_input, random_num): if user_input == random_num: return True elif user_input > random_num: return False elif user_input < random_num: return False print(logo) print('Welcome to the Number Guessing Game!') print...
# expected input/output in_ = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d' out_ = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t' # string of b64 characters, index of each character in string is the # equivalent numerical value of the string in d...
""" Module contains the Object class. """ from engine.texturemanager import TextureManager, TextureInfo class Object: """ An Object in the scene representing by a texture. An object can be attached to a scene node. """ def __init__(self, scenenode=None): """ Constructor for an object cl...
import pygame from pygame.locals import * class InputManager: """ InputManager is the class responsible for registering, and keeping current inputs up to date. """ def setup(): """ setup should be called when the game starts up, it creates empty dictionaries for the the controls. ...
import sys a=float(input('Insira o valor de a: ')) b=float(input('Insira o valor de b: ')) c=float(input('Insira o valor de c: ')) if a==0: print('Nao eh equacao de segundo grau') sys.exit() delta=(b**2)-4*a*c raizDelta=delta**0.5 if delta<0: print('A equacao nao possui raizes reais') sys.exit() e...
num=int(input('Insira um numero de 1 a 7: ')) if num==1: print('1-Domingo') elif num==2: print('2-Segunda') elif num==3: print('3-Terca') elif num==4: print('4-Quarta') elif num==5: print('5-Quinta') elif num==6: print('6-Sexta') elif num==7: print('7-Sabado') else: print('Valor Invalido...
import math valorSaque=int(input('Digite o valor do saque: ')) notas100=int(valorSaque/100) resto=valorSaque-notas100*100 if resto>=50: notas50=1 else: notas50=0 resto=resto-(notas50*50) if resto>=40: notas20=2 elif resto<40 and resto>=20: notas20=1 else: notas20=0 resto=resto-(notas20*20...
import math num=int(input('Digite um numero: ')) verificador=num%2 if verificador==1: print('Eh impar') else: print('Eh par')
print("# Create new threads") for i in range(500): print("thread{} = myThread({})".format(i+1, i+1, i, i)) print("# Start new Threads") for i in range(500): print("thread{}.start()".format(i+1)) print("# Add threads to thread list") for i in range(500): print("threads.append(thread{})".format(i+1))
#! /usr/bin/env python __author__ = 'Arana Fireheart' from math import pi # This is an example of a function with an optional parameter # The optional parameter was added as an upgrade to handle # griviances about the lack of a "report and crash" mode # of operation. def avSphere(radius, raiseError = True, errorMess...
import backtrader as bt # Import Backtrader # Create a strategy class MyStrategy(bt.Strategy): # Initialize policy parameters params = ( (...,...), # the last one “,” It's better not to delete ! ) # Log printing : Official documents for reference def log(self, txt, dt=None): ...
# 次方 def myAbs(x): if not isinstance(x,(int,float)): raise TypeError("lalala") if x >0: return x else: return -x def power(x,n = 2): s = 1 while n > 0: n=n-1 s=s*x return s
import re # I (sort of) know regular expressions! # Calculate number of each element def calculate_quantity(eq,multiplier=1): splitted = re.findall('[A-Z][^A-Z]*', eq) element_dict = {} for i in splitted: try: element_dict[i] += multiplier except: elemen...
from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.tag import pos_tag import nltk # Function to Tokenize the input text def Tokenize(text): tokens = word_tokenize(text) print '******** Tokenize *********' print tokens, '\n' return...
import unittest from sudoku import SudokuCell, Sudoku class TestSudokuCellMethods(unittest.TestCase): def test_init(self): test_cell = SudokuCell(3, 4) self.assertFalse(test_cell.value) self.assertEqual(test_cell.valid_numbers, range(1, 10)) def test_box_coordinates(self): test_cell = SudokuCell...
import numpy as np import nnfs from nnfs.datasets import spiral_data nnfs.init() np.random.seed(0) X, y = spiral_data(100, 3) inputs = [0, 2, -1, 3.3, -2.7, 1.1, 2.2, -100] output = [] class Layer_Dense: def __init__(self, n_inputs, n_neurons): self.weights = 0.10 * np.random.randn(n_inputs, n_neurons...
import numpy as np from enum import Enum class Rotation(Enum): ROLL = 0 PITCH = 1 YAW = 2 class EulerRotation: def __init__(self, rotations): """ `rotations` is a list of 2-element tuples where the first element is the rotation kind and the second element is ang...
#!/usr/bin/env python # coding: utf-8 # ## Co-axial drone dynamics # # <img src="Drone1.png" width="300"> # # In this exercise, you will populate the ```CoaxialCopter``` class with three methods. These functions will calculate vertical acceleration $\ddot{z}$, angular acceleration $\ddot{\psi}$ along the $z$ axis an...
#listbox ==> A listing of selectable text items within it's own container from tkinter import * def submit(): food = [] for index in my_box.curselection(): food.insert(index,my_box.get(index)) print("You have ordered: ") for index in food: print(index) def add(): ...
# *args ==> is a parameter that will pack all arguments into a tuple # useful so that a function can accept a varying amount of arguments def add(*addition): sum = 0 addition = list(addition) addition[1] = 10 for i in addition: sum += i return sum print(add(1, 7, 8, 8,...
from tkinter import * from tkinter import messagebox #This imports message box library def click(): #messagebox.showinfo(title="messagebox", message="Successfully installed Virus") #messagebox.showwarning(title="Warning", message="Virus in your PC!!!") #messagebox.showerror(title="error", message="...
"""A variable is a container for a value. It behaves as the value that it contains""" #VARIABLES #strings => they store a series of characters first_name = "Marcus" last_name = "Ogutu" full_name = first_name + " "+ last_name print("Hey "+ full_name) #Integers => they are data types of numeric value that can ...
"""slicing => is the creating of a sub string by extracting elements from another string index[] or slice() start:stop:step""" #INDEXING name = "Smart Developer" first_name = name[:5] last_name = name[5:15] funcky_name = name[::1] reversed_name = name[::-1] #print(reversed...
#canvas => widget that is used to draw graphs, plots, images in a window from tkinter import * window = Tk() canvas = Canvas(window, height=500, width=500) """blue_line = canvas.create_line(0,0,500,500, fill="blue", width=5) red_line = canvas.create_line(0,500,500,0, fill="red", width=5) rectangle = canvas....
from tkinter import * count = 0 def display(): if(x.get()==1): global count count += 1 print(count) else: print("You don't Agree :(") window = Tk() x= IntVar() check_button = Checkbutton(window, text="Check it", ...
#! python 3 from icalendar import Calendar import os import shutil class Module(): def __init__(self, modCode, modName): self.code = modCode self.name = modName self.lessons = [] def createYearDir(dirArr): yearNum = len(dirArr) + 1 os.makedirs(f'Year {yearNum}', exist_ok=True) ...
from time import gmtime, strftime def time_helper(): """ Get the current time :return: formatted time string """ curr_time = strftime("%H:%M", gmtime()) return curr_time def date_helper(): """ Get the current date :return: formatted date string """ curr_date = strftime(...
import time import asyncio import cozmo from cozmo.util import degrees, distance_mm, speed_mmps, Pose def say_text(robot: cozmo.robot.Robot): print("Saying text") x = input("What do you want cozmo to say?") robot.say_text(x).wait_for_completed() def drive_straight(robot: cozmo.robot.Robot): print("Dr...
def max(x, y): if x <= y: return y else: return x def max1(x, y): return y if x <= y else x def max2(x, y, z): return z if max1(x, y) <= z else max1(x, y)
from typing import Tuple, List import math import numpy as np def distance_min(state): """input: state output: la distance minimal entre un de nos groupes et les groupes ennemies""" distances = [] groups = [None, None] for position_nous in state.our_species.tile_coordinates(): distance_ce...
import random # Give an S element, find the first 2 elements in a list where the sum is the same as S, return True or false and + # + the index's # Ex: S = 8 # list = [1, 2, 4, 4] # 4 + 4 = 8 so, result = True, index 2 and index 3 # Ex2: S= 8 # list = [1,2,3,9] # result = False, index -1 and index -1 #return bool, i...
#7.5 show row space and column space to be equivalent from triangular import * from GF2 import * from matutil import * from solver import solve from The_Basis_problems import * from independence import * from vecutil import * """A [120] [021] row space == [1,0][0,1] column space == [1,0][0,1] row space == column s...
import sqlite3 # Read in Data from table, row def read_data(table, row): db = sqlite3.connect('database.sqlite') cursor = db.cursor() cursor.execute("SELECT " + row + " FROM " + table) return cursor.fetchall() # Reads in Data from table,row, with an id def read_id(table, row, id): db = sqlite3....
def square(x): return x*x print square(10) #You can pass functions around as parameters def dosomething(f, x): return f(x) print dosomething(square, 3) print dosomething(lambda x : x*x*x, 3) #lambda = none function, so we make new function
from typing import Tuple, List import tp6 def my_function_tuple() -> Tuple[int ,int]: return 0, 10 x, y = my_function_tuple() print(x, y) def min_max_avg(l: List[float]) -> Tuple[float, float, float]: min = l[0] max = l[0] sum = 0 for val in l: sum += val if val < min: ...
#! usr/bin/python3 """ Construct a function that finds the missing value between two lists. """ from functools import reduce def reverse_list(x): i = 0 j = len(x)-1 # completes in O(n) time while (i < j): x[i],x[j] = x[j],x[i] i += 1 j -= 1 return ''.join(x) def...
#! usr/bin/env python3 def waterArea(heights): max_height = float('-inf') max_i = -1 valleys = [] last_valley_i = -1 running_area = 0 for i,current_height in enumerate(heights): if current_height >= max_height and current_height != 0: # >=? # if we haven't initialized yet,...
#! usr/bin/env python3 def subarraySort(array): i = 0 j = len(array)-1 print("array[i]\tarray[j]\tcenter_min\tcenter_max") while i <= j: # O(n) time operation center_max = max(array[i+1:j]) center_min = min(array[i+1:j]) if array[i] >= center_min and arra...
#! usr/bin/python3 """ Find the minimum spanning tree (MST) that connects all the vertices in the graph while minimizing the total edge weights. Solution -------- We'll use Prim's algorithm. this is a classic greedy algorithm. (1) Create an empty structure M (adj matrix or binary tree) which will be the MST ...
#! usr/bin/python3 import sys from time import time def fibonacci_naive(n): if n == 1: return 0 elif n == 2: return 1 else: return fibonacci_naive(n-1) + fibonacci_naive(n-2) def fibonacci(n,memo={1:0,2:1}): if n in memo: return memo[n] memo[n] = fibonacci(n-1,memo)...
#! usr/bin/python3 """ Good morning! Here's your coding interview problem for today. This problem was asked by Google. The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. Hint: The basic equation of a circle is x2 + y2 = r2. """ import random import math def monte_ca...
#! usr/bin/python3 """ Print all subsets of a set input set = [1, 2, 3] power set = [[], [1], [2], [3], [1, 2], [2, 3], [1, 3] [1, 2, 3]] """ def subsets_of_set(lArray): results = []; n = 2**len(lArray) # 2**n total subsets for i in range(n): going = [] rep = "{0:b}".format(i) w...
#! usr/bin/python4 """ Good morning! Here's your coding interview problem for today. This problem was asked by Twitter. Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. For example, given the query stri...
dias=int(input('Quantos dias usou o veículo? ')) km=float(input('Quantos quilometros foram rodados? ')) diar=dias*60 kmt=km*0.15 print('O valor das diárias foi R$ {:.2f} e o valor da quilometragem usada foi R$ {:.2f}.\n' 'O total a pagar é R${:.2f}.\nObrigado!\n' 'Volte sempre!'.format(diar,kmt,diar+kmt))
import matplotlib.pyplot as plt import pdb from math import sqrt """This was probably a waste of time - Dylan""" def pressure(V,n,R,T): return n*R*T/V def Force(P,A): return P * A def acceleration(F,m): return F / m def velocity(u,a,dt): return u + a * dt def position(x,u,dt): return x + u *...
while True: print("looping") break count = 1 while count <= 4: print("looping") count += 1 print(f"We're counting odd numbers: {count}") colors = ['blue', 'green', 'red', 'purple'] for color in colors: print(color) print(color) for color in colors: if color == 'blue': continue ...
""" This File demonstrates solving the crossword problem using constraints satisafiction """ import sys from crossword import * from crossword_creator import * import itertools import timeit class CSP(): def __init__(self, crossword_creator): """ Create new CSP crossword generate. """ ...
# -*- coding: utf-8 -*- import pandas as pd import time from datetime import date def clean_people(df): # rename columns: df = df.rename(columns={'email address': 'email'}) # remove rows which have an empty "first_name" (NA): #df = df[df.first_name.notna()] <- equivalent to next line: df = df...
"""Loop Detection Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop. DEFINITION Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list. EXAMPLE Input: A -> B -> C -> D -> E -> ...
"""Three in one Describe how you could use a single array to implement three stacks. Hints: #2 A stack is simply a data structure in which the most recently added elements are removed first. Can you simulate a single stack using an array? Remember that there are many possible solutions, and there are tradeoffs of ea...
"""Minimal Tree Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height. Hints: #19 A minimal binary tree has about the same number of nodes on the left of each node as on the right. Let's focus on just the root for now. How would y...
"""Deck of Cards Design the data structures for a generic deck of cards. Explain how you would subclass the data structures to implement blackjack. Hints: #153 Note that a "card deck" is very broad. You might want to think about a reasonable scope to the problem. #275 How, if at all, will you handle aces? """ ''' C...