text
stringlengths
37
1.41M
def calculate_len(input_str): if type(input_str) == int: print ("Intergers don't have lengths") elif type(input_str) == float: print("Floats don't have lengths") else: return len(input_str) input_str=input("Enter input string: ") print (calculate_len(input_str))
#!/usr/bin/env python3 # @AUTHUR: Kingsley Nnaji <kingsley.nnaji@gmail.com> # @LICENCE: MIT # Creation Date: 03.09.2019 def is_Vowel(char): ''' is_Vowel() -> boolean Checks to see is a given character is a vowel and returns a True or False. >>> is_Vowel("b") False >>> is_Vowel("i") Tru...
#opens csv file input_file = open("songs.csv", "r") FILES = input_file.readlines() #intitiating all attributes required for proper function of class class SongList: def __init__(self, list = []): self.list = list self.file = FILES self.count_list = [] self.learnt_count = [] ...
# What will the output of this be? term1 = 5 term2 = 10 sum = term1+term2 print(sum)
### The answer is: # 26 # The way this works is it makes a function that takes to arguments aka the two terms. It then stores the math equation # ValueOne+ValueTwo in a variable called sum. When we return the sum using 'return sum' that makes it so you can store # the functions output in a variable. The value that w...
import itertools it = [2,4,8,10,12,14,16,18,19,20,22,24] def even(i): return not i % 2 x = itertools.takewhile(even, it) for e in x: print(e)
""" From a series of points on a time sequence that represents stock profit points, select the times to buy and sell to maximize profits. Since it is a time series, you can only sell after you have bought. """ source = [36,10,3,18,3,7,8,9,6] profit = {} # d[sum of b - a] = (a, b) for i in source: for j in source...
name = input("Please enter your name: ") lname = input("Please enter your last name: ") age = int(input("Please enter your age: ")) birth = int(input("Please enter your date of birth(just year): ")) myList = list() myList = [name,lname,age,birth] i=0 for i in myList: print(i) if age<18: print("You can...
#=============================================================================== # Robert Mitchell # # Computer Science - CSUF #=============================================================================== import pygame import time import random # initialize pygame. pygame.init() # environment colors blackColor = (...
def LaticePath(n): L = [1] * n for i in range(n): for j in range(i): L[j] = L[j] + L[j-1] L[i] = 2 * L[i - 1] return L[n -1] print LaticePath(1) print LaticePath(2) print LaticePath(3) print LaticePath(20)
age = 10 #One way statement if age == 10: print("ten") name = "Melanie" if name == "Melanie": print("the same") letter = "C" #Alphabetical if letter < "D": print("Less than D") if letter > "B": print("Greater than B") age = eval(input("Enter your age: ")) #Else statment if age >= 18: print("...
cidade = str(input("A cidade começa com Santo: ")).strip() print("SANTO" in cidade[:5].upper())
# Given two sentences A and B return a list of all uncommon words. # A word is uncommon if it appears EXACTLY ONCE in one of the sentences, # and DOES NOT appear in the other sentence. # Each sentence is a string of space separated words. # Each word consists only of lowercase letters. # Order in the final array is...
import unittest from palindrome import palindrome class TestPalindrome(unittest.TestCase): def test_racecar(self): self.assertEqual(palindrome('racecar'), True) def test_noon(self): self.assertEqual(palindrome('noon'), True) def test_civic(self): self.assertEqual(palindrome('civi...
# -*- coding: utf-8 -*- """ @author: NightRoadIx """ # Manejo de grandes cantidades de datos import pandas as pd import numpy as np import matplotlib.pyplot as mp # Cargar el enlace a descargar enlace = "https://covid.ourworldindata.org/data/owid-covid-data.csv" # Mi recomendación es bajar el archivo y co...
import time def ran(): if x==['.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.']: print(asm2 + ' winner') time.sleep(5) quit() else: print(asm1+' tur...
import random # import platform # print(platform.architecture()) print('---石头剪刀布游戏开始---') print('请按下面的提示出拳:') print('石头【1】剪刀【2】布【3】结束【4】') while True: x = int(input('请输入你的选项:')) if x == '4': break map = {1:'石头', 2:'剪刀', 3:'布'} mapp = {1:2, 2:3, 3:1} y = random.randint(1, 3) print('您的出拳为...
''' Introduction to Neural Engineering (Fall, 2020) Implementation of Population Coding of Smell Sensing with Artificial Neural Network (ANN) ''' ''' PLEASE FILL UP BELOW (PERSONAL INFO) ''' # Full Name (last name first) : '''Park seung joo''' # Student Number : '''2018250029''' # import modules (can't b...
""" Given a string, sort it in decreasing order based on the frequency of characters Time complexity = O(n) space Complexity = O(n) """ __author__ = "Ravi Kiran Chadalawada" __email__ = "rchadala@usc.edu" __credits__ = ["Leetcode.com"] __status__ = "Prototype" from collections import defaultdict def sort_string(...
import numpy as np def var(X,Y,V,num0,scale): #-----------------------Matriz Triangular de Distancias---------------------------# D = np.array([[0]*len(Y)]*(len(X)),float) # D = matriz de distancias for j in range (len(Y)): for i in range (len(X)): D[j,i] = scale*(np.sqrt((Y[j] ...
# This is a program to visually plot sets of X & Y coordinates. # Written by: Jason Bierbrauer, 1-20-2017 import os import turtle # Location of Random_XY on local computer. A program I made to supplement the need for XY text files. rxy = "C:\\Users\\Jason\\Blue\\plot_data\\Random_XY.jar" def prompt(): """Main pr...
tablero = [ [" "," ", " ", "|"," "," ", " ", "|"," "," ", " "], #1 5 9 ["-","-", "-", "+","-","-", "-", "+","-","-", "-"], [" "," ", " ", "|"," "," ", " ", "|"," "," ", " "], #23 27 31 ["-","-", "-", "+","-","-", "-", "+","-","-", "-"], [" ...
def rowReduce(A,b): ''' Row reduce a matrix that is assumed to be in good form, aka no pivoting strategies. :param A: The Matrix to be reduced :param b: The b vector in Ax = b :return: A tuple containing both A and b. ''' numRows = len(A) numColumns = len(A[0]) for k in range(numRow...
from numpy import float64 def doublePoint(): one = float64(1.0) seps = float64(1.0) appone = float64(1.0) for ipow in range(1, 1000): seps = seps / 2 seps = float64(seps) appone = one + seps if (abs(appone) == 1): return ipow print("Didn't make it after 1...
def mostfreq(str): result={} for i in str: if i in result: continue result[i]=str.count(i) list = result.values() return max(list) print(mostfreq("AsssAAA"))
import re def rever(s): list = s.split() newlist = '' for i in range(len(list)-1,-1,-1): print(i) if i==0: newlist = newlist+list[i] else: newlist = newlist+list[i]+' ' return newlist print(rever("how are you?"))
# !\usr\bin\python3 # _*_ coding _*_ """ 计算字符串中,指定字符出现的次数 """ def count_char(s, char): s_dict = {} for si in s: if si in s_dict: s_dict[si] += 1 else: s_dict[si] = 1 return s_dict[char] count_char('abcdefgdcbaa', 'a')
def non_repeating(given_string): dictionary = {} for c in given_string: if c in dictionary: dictionary[c] += 1 else: dictionary[c] = 1 for c in dictionary: if dictionary[c] == 1: return c return None def test(): assert non_repeating("a...
def is_one_away(s1, s2): min_length = min(len(s1), len(s2)) max_length = max(len(s1), len(s2)) if max_length - min_length > 1: return False dif_counter = 0 index1 = 0 index2 = 0 while min_length > min(index1, index2): if s1[index1] == s2[index2]: index1 += 1 ...
a = 2 b = 0.5 print(a+b) name = 'Denis' print(f"Привет , {name} !") #v = int(input('Введите число от 1 до 10 ')) #print(int(v + 10)) #name = input("Введите Ваше имя ") #print(f'Привет, {name}. Как дела? ') print(int(1.0)) a = [3 , 5 , 7 , 9 , 10.5] print(a) a.append("Python") print(a) del a[5] print(a...
#3. Escribe el código que solicite números al usuario hasta que éste ingrese -1. #Cuando se ingrese -1, el programa debe imprimir el promedio de todos los números ingresados # hasta ese momento (sin contar con el -1). num = int(input("ingrese un numero cualquiera : ")) acum = 0 cont = 0 while num != (-1) : acum ...
print("actividad1") #Escribe el código que imprima un comando dada la luz del semáforo #Verde = Siga #Amarillo = Precaución #Rojo = Pare luz = input("ingrese color del semaforo: verde 'v' / amarillo 'a' / rojo 'r' ") if luz.lower() == "v" : print("siga") else : if luz.lower() == "a...
print("actividad3") #Escribe el código para dos numeros a y b, el usuario va a seleccionar una opcion: #1 para sumar, 2 para multiplicar, 3 para restar (a-b) y 4 para dividir (a/b) y #retornar el resultado de la operación indicada. a = float(input("ingrese valor de la variable a. : ")) b = float(input("ingrese val...
#Actividad 1 #Escribamos un programa que nos permita crear con una lista de 6 números aleatorios entre 1 y 20, #y luego creemos tres funciones que reciban la lista como parámetro de la siguiente forma: # # mayor(x) - Una función que imprima el número mayor valor de una lista x # primos(x) - Una función que impr...
## Tower of Hanoi ## move n pieces from source to destination ## using a temporary location ## Program: def tower(n,start,end,middle): if n==1: print("Move %i from tower %s to tower %s" %(n,start,end)) else: tower(n-1,start,middle,end) print("Move %i from tower %s to tower %s" %(n,start,end)) to...
from preprocess import * import pickle import os def lm_train(data_dir, language, fn_LM): """ This function reads data from data_dir, computes unigram and bigram counts, and writes the result to fn_LM INPUTS: data_dir : (string) The top-level directory continaing the data from which to ...
import random deck = [] player1_hand = [] player2_hand = [] def makedeck(deck): SUITS = ["hearts", "diamonds", "clubs", "spades"] VALUES = ["A","1","2","3","4","5","6","7","8","9","10","J","Q","K"] for e in SUITS: for i in VALUES: card = i + " " + e deck.append(card) def s...
# JoshBothell # 1/19 class Human(object): def __init__(self, name, hair_color, eye_color, height, weight, iq, gender, race): self.name = name self.hair_color = hair_color self.eye_color = eye_color self.height = height self.weight = weight self.iq = iq self....
print("python terms") puzzle = """ fjvfloatdy yopxednins mspfycnnal xeaeeukgei slufryprlc abeeiagcoi buclqttbon gojlivxobg admyahgerj stringwvrs """ print(puzzle) print("word list") word_list = "float, while, if, boolean, doubled, operators, string, slicing, index" print (word_list) word1_length = len("float") word2_...
import urllib.request from bs4 import BeautifulSoup url="https://sarnesh444.github.io/COVID-19-Mask-Detector-Web-App/" #opening and reading url #read eliminates the need for a loop html=urllib.request.urlopen(url).read() #print(html.decode())#gives the entire page print(html) #initiating parser #html-conte...
print ("1 milla = 1609.344 metros.") print ("1 galón = 3.785411784 litros.") litros = float(input("cuantos litros consume tu coche a los 100: ")) millas = float(input("cuantas millas recorre tu coche por galon: ")) def l100kmtompg(litros): millas = 100 * 1000 / 1609.344 galones = litros / 3.785411784 retu...
''' 函数和模块的使用 ''' ''' m = int(input('m = ')) n = int(input('n = ')) fm = 1 for num in range(1,m + 1): fm *= num fn = 1 for num in range(1,n + 1): fn *= num fmn = 1 for num in range(1,m - n + 1): fm *= num print(fm // fn // fmn) ''' ''' 定义函数 def ''' ''' def factorial(num): """求阶乘""" result ...
# %% #Tokenization import re import string def tokenization(text): text_token = re.split('\W+',text) #Returns a match where the string does contain only word characters return text_token def tokenization_apply(Series): Series = Series.apply(lambda x: tokenization(x.lower())) return Series
n = int(input("enter a number")) i=2 c=0 while(i<=n/2): if(n%i==0): c=c+1 break i=i+1 if(c==0 and n!=1): print(n,"is prime") else: print(n,"is not prime")
""" An example that finds all L3 travel regions overlapping with Germany/Bavaria and the nodes they contain organized by country """ from travel_regions.admin_regions import get_country_codes, get_admin_region_geoms from travel_regions import TravelRegions import os import json # Initialize travel regions travel_regi...
#!/usr/bin/env python import struct file = raw_input("the file you want identfy:") f = open(file,'rb') s = f.read(30) print('0-30:',s) ss = struct.unpack('<ccIIIIIIHH',s) if ss[0] == 'B' and ss[1] == 'M': print 'This is a bmp file! It has ',ss[6],'*', ss[7],', It is color is ',ss[9],'.' else: print ...
#!/usr/bin/env python def normalize(name): return name.title() L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) def is_palindrome(n): sn = str(n) for i in range(len(sn)/2): if sn[i] != sn[len(sn)-i-1]: return False return Tru...
number = int(input("Enter the numeric grade: ")) if number >= 0 and number <= 100: if number > 89: letter = "A" elif number > 79: letter = "B" elif number > 69: letter = "C" elif number <60: letter = "F" print("The letter grade is ", letter) else: print("Error: gr...
""" Program: Surface area calculator Author: Kevin Tran The purpose of this program is to calculate the surface are of a cube. 1. Get user input for the length of single edge of a cube. 2. Calculate surface area of cube from the given input. surface_area = 6 (length**) 3. Print out put of surface area. """ # Get...
""" Program: Employee pay calculator Author: Kevin Tran The purpose of this program is calculate an employees pay considering overtime 1. Get input of employees hours 2. Calculate hourly pay. If there are more than 40 hours then pay is 1.5 times the hourly rate for those hours 3. Print output of the calculated pa...
""" File: dotprod.py Author: James Lawson """ import numpy as np import random import time import matplotlib.pyplot as plt # Dot Product Function - stack overflow linked that helped me: # https://stackoverflow.com/questions/32669855/dot-product-of-two-lists-in-python def dotProduct(a, b): return sum(i[0] * i[1]...
import re def compute_paths(array, start_node, finish_node, not_found = 1000000): """ Naive implementation of dijkstra algorithm, without heap So the running time here is n * m, where n is number of vertices, and m is number of edges Array has the following format: [ '1 2,3 4,5, 7,...
def merge(tuple1, tuple2): """ Merging subroutine of merge sort We have two sorted arrays, which we have to merge into one sorted array Also, we calculate number of inversions, so we keep track of them during merging too, adding to the existing number Each tuple has structure (sorted_arra...
import collections import heapq import queue import threading import time class SkipQueue(queue.Queue): """ Implementation of blocking queue which can queue urgent items to the beginning of the queue instead of at the end. """ def __init__(self): super().__init__() self.queue = collec...
""" Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? """ from linked_list import LinkedList def deduplicate_with_hash(node): """ Makes use of temporary "hash table" (dictionary) to keep track of all the values ...
""" Q: Given two strings, write a method to decide if one is a permutaion of the other. """ def permutation_naive(a, b): """ A naive implementation iterating over. This has worst case running time of O(n ** 2). """ if len(a) != len(b): return False chars = [c for c in a] for cha...
import random def openList(): try: with open('lista.txt') as f: lines = f.read().splitlines() return lines except FileNotFoundError as e: print("File not found") def randomWord(): lines = openList() i = len(lines) i = i-1 a =random.randint(0,i) return lines[a].lower() ...
import turtle import random # set up the screen window = turtle.Screen() # creates a window window.title("Likun's Snake Game") # give title to the window window.bgcolor("black") # set the background color window.setup(width=600, height=600) # sets the window dimensions window.tracer(0) # turns off the screen updates ...
import os with os.scandir('images') as entries: print("###############_start_###############") for entry in entries: # List all files in a directory using os.listdir basepath = "images/" + entry.name for entry1 in os.listdir( basepath): if os.path.isfile(os.path.join(basepath, entry1)): p...
#programm to take a single no from user and print it in string num= int(input("enter single digit no please=")) days= ["one","two","three","fourth", "fifth","six","seven","eight","nine"] if num > 9: print("you have entered number more then 9 please enter again but less then 9") elif num==1: print("one") elif nu...
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ purpose:-Power of 2 @author:-Sheevendra Singh Singhraul @version:-3.8.6 @since:-18-03-2021 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ import math useInput=int(input("Enter a Integer number to check for its power of 2=")) #5 if use...
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ purpose:-Computes the prime factorization of N @author:-Sheevendra Singh Singhraul @version:-3.8.6 @since:-18-03-2021 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ userInput=int(input("enter a number to check for prime factorial=")) p...
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ purpose:-programm for stop watch @author:-Sheevendra Singh Singhraul @version:-3.8.6 @since:-22-03-2021 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ import time # importing time module while True: #while loop will run untill condit...
""" +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Purpose: Program To find second max variable in a given list * @author: Sheevendra Singh Singraul * @version: 3.8.6 * @since: 19-03-2021 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ list=[23,21,4...
class ArrayHandler: # returns a flattened list + the starting indices of each sublist @staticmethod def flatten(list_of_indices): list = [] indices = [] index = 0 for sublist in list_of_indices: list.extend(sublist) indices.append(index) ...
print("Be happy\nWork hard and eat healthy food") def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def div(a,b): return a/b def modu(a,b): return a%b name=input("Enter your name-->") print("insert operation") print("Addition (+)") print("Substraction (-)") print("multiplic...
from itertools import chain def sort_sequence(sequence): x, y = [], [] for i in sequence: if i == 0: x+=[sorted(y) + [0]] y=[] else: y+=[i] return list(chain.from_iterable(sorted(x, key=lambda n: sum(n))))
# Hangman def Hangman(guess, word): ans = "" for letter in word.lower(): if letter == guess.lower(): ans += letter else: ans += "_" return ans
def descending_order(num): converted_num = str(num) li = list(converted_num) li.sort(reverse=True) maxNumStr = ''.join(li) #toStr = str(li) #print(toStr) maxNum = int(maxNumStr) return maxNum
def tribonacci(signature, n): #your code here if n == 0: return [] if n == 1: return signature[:1] if n == 2: return signature[:2] else: for i in range(2, n-1): signature.append(sum(signature[i-2:i+1])) return signature
def to_camel_case(text): s = text.replace("-", " ").replace("_", " ") s = s.split() if len(text) == 0: return text return s[0] + ''.join(i.capitalize() for i in s[1:])
#Link: https://practice.geeksforgeeks.org/problems/move-all-zeroes-to-end-of-array/0 t = int(input()) for i in range (t): n=int(input()) a=map(int,input().split()) c=0 for i in a: if i!=0: print(i,end=' ') c=c+1 for i in range(n-c): print(0,end=' '...
import merge_sort class point(): def __init__(self, name, x, y): self.name = name self.x = x self.y = y def points_to_XY(P): X = [] Y = [] for i in range(len(P)): X.append(P[i].x) Y.append(P[i].y) return X, Y def divide_points(X, Y): Px = merge_sort.div...
import os import shutil from tkinter import filedialog from tkinter import * from tkinter import messagebox root = Tk() root.withdraw() directory = filedialog.askdirectory(initialdir="C:\\") if directory == "": quit() result = messagebox.askquestion("File Organizer", directory + " will be organized. Continue?", i...
""" CP1404/CP5632 - Practical Program to display all odd values between 1 and 21. """ for i in range(1, 21, 2): print(i, end=' ') print() """ CP1404/CP5632 - Practical a. Program to display all values on 10 between 0 and 100. """ for i in range(0, 101, 10): print(i, end=' ') print() """ CP1404/CP5632 - Pr...
import sys import string import math class NbClassifier(object): """ A Naive Bayes classifier object has three parameters, all of which are populated during initialization: - a set of all possible attribute types - a dictionary of the probabilities P(Y), labels as keys and probabilities as values ...
#!/usr/bin/env python import re # This function removes new line & return carriages from tweets def stripNewLineAndReturnCarriage(tweetText): return tweetText.replace('\n', ' ').replace('\r', '').strip().lstrip() # This function is used to remove all the URL's in a tweet def removeURL(tweetText): return re.s...
class Option: def __init__(self, json_list): self.text = '' # the text of the option self.chosen = False # whether this option was chosen by the user self.parse_json(json_list) def parse_json(self, json_list): raise NotImplementedError class MultipleChoiceOptio...
class MaxHeap: def __init__(self, items=[]): self.name = None super().__init__() self.heap = [0] for i in items: self.heap.append(i) self.__floatUp(len(self.heap) - 1) def insert(self, data): self.heap.append(data) ...
import turtle class WinTurtle: def checkWin(grid): diags = ((0, 4, 8), (2, 4, 6)) for n in range(3): test = grid[n] test2 = grid[n + 3] test3 = grid[n + 6] if test != '_': if test == test2 == test3: if test == 'x' or...
# Given an array of integers, find two numbers such that they add up to a specific target number. # The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (# both index1 and index2) are not zero-base...
# def outer_func(): # message = 'Hi' # def inner_func(): # print(message) # return inner_func def outer_func(msg): message = msg def inner_func(): print(message) return inner_func i_f = outer_func('Hi') i_f_2 = outer_func('Hello') print(i_f) print(i_f.__name__) # i...
# Jared Spector # 08/22/2021 # This program plays the classic Rock, Paper, Scissors game with the user. # The user makes a choice and then indicates the number of times the # computer should make a choice. The results of all games played are # shown along with a summary of results. import random # Constants ...
#!/usr/bin/python from sets import Set # Minglish lesson # =============== # # Welcome to the lab, minion. Henceforth you shall do the bidding of Professor Boolean. Some say he's mad, trying to develop a zombie serum and all... but we think he's brilliant! # # First things first - Minions don't speak English, we speak...
#!/bin/python import sys import random import os print 'Guess Number between 1 - 10' print 'You have 5 attempts !!' guess=random.randint(0,10) j=5 i=0 while i < j : num = input('Enter your Guess : ') if num < guess: print 'YOUR GUESS IS LOWER' i+=1 elif num > guess: print 'YOUR GUESS IS HIGHER' i+=1 eli...
import numpy arr=array([45,97,6],[154,5557,175]) print(arr) from array import * #array build from user input import sys ip=['192.168.50.45','192.168.50.46'] for i in ip: print (i) arr=array('i',[]) size=int(input('hi user how many numbers u want : ')) for i in range(size): print (i+1, end=" "...
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.min = [] def push(self, val): """ :type val: int :rtype: None """ if len(self.min) == 0: self.min.append(val...
#Write a function taking in a string like WOW this is REALLY amazing and returning Wow this is really amazing. String should be capitalized and properly spaced. Using re and string is not allowed. def filter_words(st): # Your code here. text = " ".join(st.split()) return text.capitalize() print(fil...
#1. Напишіть програму, яка пропонує користувачу ввести ціле число і визначає чи це число парне чи непарне, чи введені дані коректні. num = int(input("PLease put the number: ")) def digit(num): try: if num%2 == 0 : return "This is the even number" return "this is the odd number"...
#2. Написати скрипт, який перевірить чи введене число парне чи непарне і вивести відповідне повідомлення. num= int(input("please enter the number : ")) if num%2 == 0: print("This number {} is even". format(num)) else: print("This number {} is odd". format(num))
#1. Спробуйте переписати наступний код через map. Він приймає список реальних імен і замінює їх хеш-прізвищами, використовуючи більш надійний метод-хешування. names = ['Sam', 'Don', 'Daniel'] for i in range(len(names)): names[i] = hash(names[i]) print(names) print(map(lambda i: hash(names[i]), names)) print...
upper = 0 lower = 0 digit = 0 num = 0 space = 0 spaceU = 0 res = "si" res2 = "si" nombre = {} #Function that prompts the user for his or her name def nombre_u(): global nombre name = input("\nIntroduce your name: ") nombre = name print("\nFuck, what a great name") us...
import random import time random = random.sample(range(20), 20) # range of 20 items including the numbers from 0 to 20 print(random) searching_for = 15 def linear_search(arr, target): # Your code here for i in range(0, len(arr)): if arr[i] == target: return i return -1 # not...
import json from queue import PriorityQueue # dictionaries of json files energy_cost_btw_2_nodes_dictionary = {} dist_btw_2_nodes_dictionary = {} # this is for g(n) graph_dictionary = {} # this is to find neighbours of node def convert_json_files_to_dictionaries(): f = open('Cost.json', ) global energy_cost...
from math import * max_sols = 0 best_p = 0 # the shortest side can be no larger than 'a' where # a^2 + a^2 = req_primes^2 and a + a + req_primes = p # solving gives a = .5(2p - sqrt(2)*p) for p in range(1, 1001): max_pos_shortest = floor(.5*(2*p - sqrt(2)*p)) sols = 0 for a in range(1, max_pos_shortest + 1...
''' Function to take a integer and returns its string equivalent ''' def itos(int1): if type(int1) == str: print(f'Enter an integer, {int1} is a string.') else: if isinstance(int1, float): raise ValueError('Input an integer not a float') elif isinstance(int1, int):...
imiona = ['Artur', 'Barbara', 'Czesław'] print(imiona) indeks = int(input('Proszę podać indeks imienia do skasowania: ')) if indeks < len(imiona): print('Kasowane imię to:', imiona[indeks]) del imiona[indeks] else: print('Nie ma elementu o takim indeksie') print(imiona)
imiona = ['Artur', 'Barbara', 'Czesław'] print(imiona) nowe_imie = input('Proszę podać nowe imię: ') imiona.append(nowe_imie) print(imiona) imiona[0] = 'Guido' print(imiona)
from datetime import datetime poczatek = datetime.now() input('Naciśnij ENTER') pierwszy_stop = datetime.now() pierwsza_roznica = pierwszy_stop - poczatek print(f'Naciśnięto ENTER po {pierwsza_roznica} sekundach.') input('Naciśnij ENTER') drugi_stop = datetime.now() druga_roznica = drugi_stop - pierwszy_stop pri...
lista = [1, 2, 'jakiś tekst', True, None, [1, 2, 3]] for element in lista: print('element:', element, ' typu:', type(element))