text
stringlengths
37
1.41M
''' Given a string, return the first recurring character in it, or null if there is no recurring character. For example, given the string "acbbac", return "b". Given the string "abcdef", return null. ''' import unittest def solution(string): str_set = set() for c in string: if c not in str_set: ...
'''This problem was asked by Google. Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. Do this faster than the naive method of repeated multiplication. For example, pow(2, 10) should return 1024. ''' import math def pow(x,y): if y == 0: ...
''' Given a real number n, find the square root of n. For example, given n = 9, return 3. ''' TOLERANCE_VAL = 10 ** -5 def tol(n1, n2): return abs(n1-n2) < TOLERANCE_VAL def square_root(n): if not n: return n if n < 0: print('Can not square root a negative number') return retu...
''' Given an array of elements, return the length of the longest subarray where all its elements are distinct. For example, given the array [5, 1, 3, 5, 2, 3, 4, 1], return 5 as the longest subarray of distinct elements is [5, 2, 3, 4, 1]. ''' import unittest def distinct_subarray(nums): if not nums or len(nums) ...
import unittest import math ''' We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. Given an array, count the number of inversions it has. Do th...
''' This problem was asked by Amazon. Implement a bit array. A bit array is a space efficient array that holds a value of 1 or 0 at each index. init(size): initialize the array with size set(i, val): updates index at i with val where val is either 1 or 0. get(i): gets the value at index i. ''' class BitArray(object...
''' What will this code print out? def make_functions(): flist = [] for i in [1, 2, 3]: def print_i(): print(i) flist.append(print_i) return flist functions = make_functions() for f in functions: f() How can we make it print out what we apparently want? ''' # This functi...
''' You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle: 1 2 3 1 5 1 We define a path in the triangle to start at the top and go down one row at a time to an adjacent value, eventually ending with...
''' Given a string which we can delete at most k, return whether you can make a palindrome. For example, given 'waterrfetawx' and a k of 2, you could delete f and x to get 'waterretaw'. ''' import unittest def lcs(a, b): DP = [[0]*(len(a)+1) for _ in range(len(b)+1)] for i in range(len(DP)): fo...
''' Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number. A solution will always exist. See Goldbach’s conjecture. Example: Input: 4 Output: 2 + 2 = 4 If there are more than one solution possible, return the lexicographically smaller solution. If [a, b] is one ...
import os from random import shuffle def menu(): print("---------------------------") print("| PYRE IT UP! QUIZ GAME |") print("---------------------------\n") print("[1] START Quiz") print("[2] View High Scores") print("[3] Reset High Scores") print("[0] Exit") choice = int(input("\nChoice: ")) ...
word = input("Please type ten lettered word.") print(word[0], word[9]) for i in range(11): print(word[0:i:1]) from random import shuffle word = list(word) shuffle(word) print(''.join(word))
#1 # def display_message(): # print("I'm learning python") # display_message() #2 # def favourite_book(title): # print(f"My favourite books is {title}") # favourite_book("Harry Potter") # #3 help # def make_shirt(text="I love python",size="large"): # print(f"Your shirt will say {text} and be size {size}...
import re test_cases = ['''Date 1 : 12/11/18 Date 2: 01/01/19'''] # Create a dictionary to convert from month names to numbers (e.g. Jan = 01) month_dict = dict(jan='01', feb='02', mar='03', apr='04', may='05', jun='06', jul='07', aug='08', sep='09', oct='10', nov='11', dec='12') def w...
# Make a function that an take any non-negative integer as an argument and return it with its digits in descendin order # def descending_order(num): # numbr = str(num) # first_list = list(numbr) # first_list.sort(reverse = True) # newstr = ''.join([str(i) for i in first_list]) # newstr = int(ne...
""" Write a Python program to find if a given string starts with a given character using Lambda. """ word = 'python' string = lambda char : True if char == word[0] else False print(string('p')) print(string('P'))
""" Write a Python program to change a given string to a new string where the first and last chars have been exchanged. """ string = 'deal_madrir' def func(word): return word[-1] + word[1:-1] + word[0] print(func(string))
""" Write a Python function that takes a number as a parameter and check the number is prime or not. Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself. """ def func(nums): if nums < 100: for i in range(2 , nums): if ...
""" Write a Python program to count the occurrences of each word in a given sentence. """ sentences = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod,tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea co...
""" Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] """ givenTuples = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] def ...
""" Write a Python program to filter a list of integers using Lambda. """ lists = [2,3,4,5,7,9,10,16,25,36,50,53,74,100,108] items = list(filter(lambda x:x % 3 != 0 , lists)) print(items)
""" Write a Python program to sum all the items in a list. """ items = [34,67,89,354,15,7,78] def func(lists): sum = 0 for list in lists: sum = sum + list return sum print(func(items))
""" Write a Python program to slice a tuple. """ lists = ['Python','is', 'a','programming','language','!!!'] sliced = lists[:5] print(sliced)
#!/usr/bin/python2.7 class Movie: def __init__(self, decade=None, genre=None, title=None, rating=-1): self.decade = decade self.genre = genre self.title = title self.rating = rating def update(self, fields): self.decade = fields[0] self.genre = fields[1] ...
import math import numpy # Create a class to hold a city location. Call the class "City". It should have # fields for name, latitude, and longitude. class City: def __init__(self, name, state, county, latitude, longitude, population, density, timezone, zips): self.name = name self.state = state ...
result = 0 for i in range (1, 51): if(i % 5 == 0): continue elif(i % 3 == 0): result += i print("결과 = ", result)
num = int(input("1부터 10사이의 숫자를 하나 입력하세요 :")) if num>0 and num<=10: if num%2==0: print(num, ": 짝수") else: print(num, ": 홀수") else: print("1부터 10사이의 값이 아닙니다")
#실습 2 color_name=input("색상값을 입력하시오") if color_name == 'red': print("#ff0000") else: print("#000000")
while True: word = input("문자열을 입력하시오 :") wordlength = len(word) if wordlength == 0: break elif wordlength >= 5 and wordlength < 9: continue elif wordlength < 5: print("유효한 입력 결과:", "*", word, "*") elif wordlength > 8: print("유효한 입력 결과:", "$", word, "$")
def get_book_title(): return "파이썬 정복" def get_book_publisher(): return "한빛미디어" name = get_book_title() for i in range(0, 2): print(name) print(get_book_publisher())
''' Jiale Shi Statistical Computing for Scientists and Engineers Homework 1 5b Fall 2018 University of Notre Dame ''' import numpy as np import matplotlib.pyplot as plt import scipy.stats import errno import os.path def readCSV(fileDir='.'): ''' Reads in .csv data file @args: fileDir = path to file ''...
a = int(input('Informe o 1 valor:')) b = int(input('Informe o 2 valor :')) c = int(input('Informe o 3 valor')) if a > b and a > c: if b > c: print(f'Ordem crescente {a} {b} {c}') if c > b: print(f'Ordem crescente {a} {c} {b}') elif b > a and b > c: if a > c: print(f'Ordem crescente ...
import re stack = [] top = -1 max_size = 5 def Empty(S): if top == -1: return True else: return False def Full(S): if top == max_size - 1: return True else: return False def Push(S, ITEM): global top S.append(ITEM) top += 1 def Pop(S):...
import pandas as pd import sqlite3 df = pd.read_csv('buddymove_holidayiq.csv') conn = sqlite3.connect("buddymove_holidayiq.sqlite3") cursor = conn.cursor() df.to_sql("buddymove_holidayiq.sqlite3", conn) query = "SELECT * FROM 'buddymove_holidayiq.sqlite3'" cursor.execute(query).fetchall() print('Table size:_', df...
import sys def inputNumber(inputMessage, verify = None, verifyFail = None): while True: answer = input(inputMessage) # input() in python 2 evaluates the input! if not answer.isnumeric(): print('Answer must be numeric') else: if not verify: # if we don't have...
from collections import defaultdict def create_graph(n , arr , graph): i = 0 while i < 2 * e : graph[arr[i]].append(arr[i + 1]) i += 2 def cycle_util(graph, vertex, visited, rec_stack): visited[vertex] = True rec_stack[vertex] = True for neighbor in graph[vertex]...
"""Project 1: Choose your Own Adventure.""" __author__ = "730401304" player: str = "" points: int = 0 def main() -> None: """The programs entrypoint.""" greet() global points points = points + 1 print(f"Well welcome to the crew {player}!!!") x: int = 0 while x != 3: print("Where...
# Name: Mayuri Patel #this function convert the list to dictionary def converse(months): lstTo_dict = {} for i in months: month = i[0] num_days = i[1] #building the dictionary lstTo_dict[month] = num_days return lstTo_dict #exit the function and return the dictionary #this function reverse th...
# Problem # Alice and Bob take turns playing a game, with Alice starting first. # # Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of: # # Choosing any x with 0 < x < N and N % x == 0. # Replacing the number N on the chalkboard with N - x. # Also, if a pla...
# Problem # The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, # such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, # # F(0) = 0, F(1) = 1 # F(N) = F(N - 1) + F(N - 2), for N > 1. # Given N, calculate F(N). # # # # Example 1: # # Inpu...
# Problem # We are to write the letters of a given string S, from left to right into lines. # Each line has maximum width 100 units, and if writing a letter would cause the # width of the line to exceed 100 units, it is written on the next line. We are given an array widths, # an array where widths[0] is the width of ...
# Problem # Given a string S of lowercase letters, a duplicate removal consists of # choosing two adjacent and equal letters, and removing them. # # We repeatedly make duplicate removals on S until we no longer can. # # Return the final string after all such duplicate removals have been made. It is guaranteed the ans...
# Problem # Given a n-ary tree, find its maximum depth. # # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. # # Nary-Tree input serialization is represented in their level order traversal, each group of children is # separated by the null value (See ex...
# Problem # Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), # return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest. # # A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j,...
#---------------------------------------------------------------------------------------------------------------------- #encoding: UTF-8 # Autor: Sebastian Morales Martin, A01376228 # Descripcion: cálculo de coordenadas cartesianas a coordenadas polares # A partir de aquí escribe tu programa # Análisis #Ent...
""" Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Example 1: Input: "III" Output: 3 Example 2: Input: "IV" Output: 4 Example 3: Input: "IX" Output: 9 Example 4: Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 5: Input: "MCMXCIV" Ou...
# -*- coding: utf-8 -*- __author__ = 'ivanvallesperez' import os def make_sure_do_not_replace(path): """ This function has been created for those cases when a file has to be generated and we want to be sure that we don't replace any previous file. It generates a different filename if a file already exists...
import argparse import re def reduce_asterisks(pattern): reduced = '' asterisk_now = False for i in pattern: if not asterisk_now and i == '*': reduced += i asterisk_now = True elif i != '*': reduced += i asterisk_now = False return reduc...
import numpy as np m = np.array([[1,2,3], [4,5,6]]) print(m) """< [[1 2 3] [4 5 6]] >""" v = m.flatten() print(v) """< [1 2 3 4 5 6] >"""
import numpy as np m = np.array([[1,2,3], [4,5,6], [7,8,9]]) print(m) """< [[1 2 3] [4 5 6] [7 8 9]] >""" v = np.diagonal(m) print(v) """< [1 5 9] >"""
import sys import math # FUNCIO QUE LLEGEIX L'ARXIU PASSAT COM A PARAMETRE def readfile(): filename = sys.argv[1] variables = [] for line in open(filename): variables.append([int(i) for i in line.strip().split(' ')]) points = [] i = 0 while i < variables[0][0]: points.append(va...
#!/usr/bin/env python3 import random N = 64 MAX_WORDS = 256 MAX_EXPONENT_WORDS = 8 for _ in range(N): x_words = random.randint(1, MAX_WORDS) y_words = random.randint(1, MAX_EXPONENT_WORDS) m_words = random.randint(1, MAX_WORDS) x = 0 y = 0 m = 0 for _ in range(x_words): x <<= 32 ...
def zuixiaozhi(arr,type=1): min=arr[0] for i in range(1,len(arr)): if type==1: if min>arr[i]: min=arr[i] else: if min<arr[i]: min=arr[i] return min arr=[3,12,1,34] print(zuixiaozhi(arr,2))
# Ask the user for a password, and then make sure that the password follow those criterias: # - At least 1 lower case letter between. # - At least 1 number. # - At least 1 upper case letter. # - At least one exclamation mark. # - Minimum length of transaction password: 6. # - Maximum length of transaction password: 12...
age = input("How old are you ? ") age = int(age) # _________________________________________ #/ Convert it to an int because the result \ #\ of input() is always a string. / # ----------------------------------------- # \ ^__^ # \ (oo)\_______ # (__)\ )\/\ # |...
### Exercise (medium) # #Make a function that receives a list and print: #- The number of elements in the list #- The minimum element in the list #- The maximum element in the list #- The sum of all the numbers in the list # ### def list_describer(l): print("Number of elements in this list:", len(l)) print...
class VendingMachine: def __init__(self): self.earnt_money = 0 self.products = [] # self.products will be a list of dictionnaries that represent a product # name/price/quantity def stock_article(self, product_dict): # Check if the dictionnary is valid keys = ...
# Define name and age variables my_name = "Eyal" my_age = 20 # Incrementing my_age my_age += 1 my_age = my_age + 1 # Print presentation sentence out print("Hello my name is", my_name, "and I am", my_age, "years old") # Using the format() function print("Hello my name is {} and I am {} years old".format(my_name, my_...
# FrogRiverOne def solution(X, A): leaves = set() for i, j in enumerate(A): if j <= X: leaves.add(j) if len(leaves) == X: return i return -1 def solution2(A): leaves = set() if __name__ == "__main__": print(solution(5, [1, 3, 1, 4, 2, 3, 5, 4]))
import copy import sys class Point: x = -1 y = -1 class Node: 'the main node class' depth = 0 alpha = -9999 beta = 9999 value = -9999 x = -1 y = -1 nextX = -1 nextY = -1 board = [['*' for x in range(8)] for y in range(8)] flag=False def printRef(): for i in ran...
""" A module can define a class with the desired functionality, and then at the end, replace itself in sys.modules with an instance of that class (or with the class, if you insist, but that's generally less useful). import callable_module print(callable_module.bar('lindsay')) """ import sys class Foo: ...
""" A deque (pronounced "deck") implementation in Python A deque, also known as a double-ended queue, is an ordered collection of items similar to the queue. It has two ends, a front and a rear, and the items remain positioned in the collection. What makes a deque different is the unrestrictive nature of adding and re...
# coding: utf-8 """ Some easy questions to ask an interviewer from Joel Spolsky: 1) Write a function that determines if a string starts with an upper-case letter A-Z 2) Write a function that determines the area of a circle given the radius 3) Add up all the values in an array """ import re def starts_with_upper...
""" A decorator factory is a function that returns a decorator. Decorator factories are used when you want to pass additional argument to the decorator, and they are commonly implemented by nesting 3 functions. The outer function is the decorator factory, the middle one is the decorator, and the inner one is the func...
""" Simple cache implementation --------------------------- The following is a simple cache implementation, which is suitable for relatively small caches (up to a few hundred items), and where it’s relatively costly to create or reload objects after a cache miss (e.g. a few milliseconds or more per object.) Usage:: ...
# Program to check student attendance. #If attendance>75%, student can sit for attendance. #If attendance<75%, he cannot class Student_attendance: def att(self,attendance): if(attendance>75): print("Student can sit for unit test") else: print("Student cannot sit...
# This question is about AdaBoost algorithm. # You should implement it using library function (DecisionTreeClassifier) as a base classifier # Don't do any additional imports, everything is already there # # There are two functions you need to implement: # (a) fit # (b) predict from sklearn.model_selection i...
import random import json import datetime class Result(): # class def __init__(self, player_name, score): self.date = datetime.datetime.now() self.player_name = player_name self.score = score def play_game(player_name, level): secret = random.randint(1, 30) score =...
def diffWaysToCompute(input): """ :type input: str :rtype: List[int] """ n = [] symbol = [] p = 0 i = 0 for c in input: if c.isdigit(): p = p * 10 + int(c) else: i += 1 n.append(p) n.append(c) symbol.append(i...
from enum import Enum class Region(Enum): WEST = 1 EAST = 2 NORTH = 3 SOUTH = 4 print(Region.NORTH.name) print(Region.NORTH.value) print(Region(3)) print(Region['NORTH']) print(Region(4))
from ListNode import * def rearrange(head): if head != None: pre = None p = head while p != None: if p.val >= 0: pre = p p = p.next else: pre.next = p.next p.next = head head = p p = pre.next return head def main(): head = createList([0, -1]) head = rearrange(head) printList(he...
# https://leetcode.com/problems/construct-string-from-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def tree2str(self, t: TreeNode) -> str: ...
# https://leetcode.com/problems/design-add-and-search-words-data-structure/ class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.words: Dict[int, Set[str]] = {} def addWord(self, word: str) -> None: """ Adds a word into the ...
# https://projecteuler.net/problem=3 import math # def get_primes(max_val: int) -> set[int]: def get_primes(max_val: int) -> list: crive = [True] * (max_val + 1) crive[0] = crive[1] = False for x in range(2, max_val + 1): if crive[x]: temp = x x += temp while x <= max_val: crive[x] = False x +=...
#!/bin/python3 import math import os import random import re import sys # Complete the checkMagazine function below. def checkMagazine(magazine, note): magazine_dit = dict() for x in magazine: magazine_dit[x] = magazine_dit.get(x, 0) + 1 for x in note: if x not in magazine_dit or magazine_dit[x] == 0: retu...
# https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ class Solution: def is_sorted(self, nums: List[int]) -> bool: # print(f"is_sorted({nums})") lenn = len(nums) for i in range(lenn - 1): if nums[i + 1] < nums[i]: return False return True ...
#!/bin/python import math import os import random import re import sys numberName = ["o' clock", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twoelve", "thirteen", "fourteen", "quarter", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"] numberName +=...
def LongestWord(sen): palavras = sen.split(' ') maior = "" for palavra in palavras: atual = "" for letra in palavra: if letra.isalpha(): atual += letra if len(atual) > len(maior): maior = atual return maior # keep this function call here print LongestWord(raw_input())
print("Hello (^_^)") exi = True while exi == True: print("----MENU----\n1.Register\n2.Login\n3.Exit") menu = int(input()) if menu==1: print("--REGISTER--") userR = str(input("USERNAME:")) plassR = str(input("PLASSWORD:")) print("Register successfuly") elif menu==2: ...
velocidade = int(input('Digite a velocidade do veículo: ')) if velocidade > 80: print('Você foi multado!') multa = (velocidade - 80) * 7 print('O valor da multa é de R${}.'.format(multa)) else: print('Tenha um bom dia e dirija com segurança')
idade_maior = 0 nome_maior = '' soma_idade = 0 count_mulheres = 0 media = 0 for counter in range(1, 5): print('--------- {}° PESSOA ---------'.format(counter)) nome = str(input('Nome: ')) idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')).upper() soma_idade += idade media = soma_ida...
print('-='*27) valor_casa = float(input('Digite o valor da casa que deseja comprar: R$ ')) salario = float(input('Digite o salário que você recebe: R$ ')) anos = int(input('Digite em quantos anos deseja parcelar: R$ ')) print('-='*27) prestacao = (valor_casa / anos) / 12 minimo = salario * 0.3 if prestacao <= minimo: ...
a = float(input('Digite o lado a do triangulo: ')) b = float(input('Digite o lado b do triangulo: ')) c = float(input('Digite o lado c do triangulo: ')) if a < b + c and b < a + c and c < a + b: print('As retas podem formar um triangulo') if a == b and a == c: print('Formará um triângulo equiátero.') ...
""" Example usage of replot to output replottable plots with Pyplot. """ import numpy as np from replot import plot # Code the does the actual plotting # You can also put this in a separate .py file and specify the path to it plotting_code = """\ import matplotlib # Force matplotlib to not use any Xwindows backend. m...
import sys, random print("Welcome to the Psych 'Sidekick Name Picker.'\n") print("A name just like Sean would pick for Gus:\n\n") first = ('Baby Oil','Bad News', 'Big Burps', "Bill, 'Beenie-Weenie'") last = ('Appleyart','Bigmeat','Littlemeat','Bloominshine','Boogerbottom','Clutterbuck','Cocktoasten', 'Jefferson'...
#Escribe un programa que lea las dimensiones (base y altura) de dos rectángulos y que calcule e imprima el perímetro y área #de cada uno. def calcularArea1(base1, altura1): area = base1*altura1 return area def calcularArea2(base2, altura2): area = base2*altura2 return area def calcularPeri...
import sys def read_ints(): """Read integers from underlying buffer until we hit EOF.""" numb, sign = 0, 1 res = [] s = sys.stdin.read() for i in range(len(s)): if s[i] >= '0': numb = 10 * numb + ord(s[i]) - 48 else: if s[i] == '-': sign = -...
def gen(A, b, n): if b == n-1: print A else: A[b+1] = 0 gen(A, b+1, n) A[b+1] = 1 gen(A, b+1, n) if __name__ == '__main__': n = 15 Arr = [] for i in range(n): Arr.append(0) gen(Arr, 0, n)
# -*- coding: utf-8 -*- """ program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh Created on Fri Jun 16 16:03:10 2017 @author: mtrem """ ...
# -*- coding: utf-8 -*- """ Python function, evalQuadratic(a, b, c, x), that returns the value of the quadratic a⋅x2+b⋅x+c. Created on Mon Jun 19 15:28:29 2017 @author: mtrem """ def evalQuadratic(a, b, c, x): ''' a, b, c: numerical values for the coefficients of a quadratic equation x: nume...
print("what's your favorite sport?") sport = input ().title() if sport == "Skiing": print ("That's my favorite too!") elif sport == "Golf": print ("I'm decent, but I'm practing.") elif sport == "Wrestling": print ("I love wrestling") else: print (sport + " sounds fun.") print("What's y...
""" 读取JSON数据 """ import json; import csv2; json_str = '{"name":"wendy", "age": 22, "title": "老师"}'; result = json.loads(json_str); print(result); print(type(result)); print(result['name']); print(result['age']); # 把转换得到的字典作为关键字参数传入Teacher的构造器 teacher = csv2.Teacher(**result); print(teacher); print(teacher.name); pr...
from nltk.tokenize import sent_tokenize def lines(a, b): """Return lines in both a and b""" # split each string into lines linesa = a.splitlines() linesb = b.splitlines() # instantiate results list lines = [] # compare lines for a_line in linesa: for b_line in linesb: ...
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" alphabetLength = alphabet.__len__() def run_caesar(): stringToEncrypt = input("Please enter a message to encrypt") shiftMessage = "Please enter a whole number from -%d to %d to be your key" % (alphabetLength-1, alphabetLength-1) intKey = int(input(shiftM...
#!/usr/bin/python from __future__ import print_function import random print("You are in a dark room in a mysterious castle") print("In front of you are three doors. You must choose one.") playerChoice = raw_input("Choose 1, 2, 3 or 4. . . ") if playerChoice == "1": print ("You find a room full of treasure. You'...
import random low = 0 high = 24 random_index = random.randint(low, high) primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] number = primes[random_index] for i in range(low, high): if number == primes[i]: print("Found {} in {} try(s)".format(number, i+1)) break ...
def sayHello(): myName = input("What is your name? ") print("hello", myName) sayHello()
def sayHello(name): print("hello", name) myName = input("What is your name? ") sayHello(myName)
print('________________________________________') print('CIRCONFERENZA DEL CERCHIO DATO IL RAGGIO') raggio = input('Inserire il raggio: ') r = float(raggio) print('Diametro' , r*2) print('Circonferenza' , r*2 * 3.14) print('Area' , r**2 * 3.14) print('ho ragione, lo so') print('Autore: Luca Gamerro' , 'Linguaggio ...
# FUNCTIONS # A function is like a mini-program within a program. def hello(): print('Howdy!') print('Howdy!!!') print('Hello there.') # Can you run the function hello()? def hello_friend(name): print('Howdy, ' + name) # Can you say Howdy to your code buddy? ### Exercise: Can you write a functio...