text
stringlengths
37
1.41M
if __name__ == "__main__": print ("Introduzca un nombre: ") x = True y = 0 while x == True: erro = '' nombre = input () largo = int(len(nombre)) for y in range(largo): letra = nombre[y] if letra.isdigit(): ##print ("El nombre no puede tener caracteres numericos") erro...
#Python Programming Challenge #10/1/14 #Danielle Brhely ############################## import time input('What is your question?') print('Let me think abut that') time.sleep(10) print('I dont what to answer that question right now') input('What is your question?') print('Let me think about that') time.sleep(10) print(...
#Python Programming Challenge #10/2/14 #Danielle Brhely ######################### import random answer = (random.randint(0,100) count = 0 guess = 100 while guess != answer: guess = input('Enter a number') count = count + 1 if guess > answer: print('lower') elif guess < answer: print(...
import calendar y=int(input("Enter Year:")) m=1 print(calendar.month(y,1))
class Flight(): def __init__(self,capacity) -> None: self.capacity=capacity self.passengers=[] def add_passenger(self,name): if not self.open_seats(): return False self.passengers.append(name) return True def open_seats(self): return self.capacity...
name=input("Enter Your Name : ") print("Hello "+name) #fstring print(f"Hello {name}")
# game_rules_class.py # Christian Munoz # 04/10/2015 class GameRules: """This class separates the rules of the game.""" def __init__(self): self.list_of_dice = [] self.points = 100 def score_dice(self, dice_list): """This function checks the players current hand and scores it acco...
''' You are given a sorted array of positive integers and a number 'X'. Print out all pairs of numbers whose sum is equal to X. Print out only unique pairs and the pairs should be in ascending order ''' def sum_numbers(series): numbers = series.split(";")[0].split(",") sum_target = series.split(";")[1] ...
#Write a program to determine the largest sum of contiguous integers in a list. def get_max_sum(numbers): number_list = numbers.split(",") max_sum = 0 running_sum = 0 for num in reversed(number_list): running_sum = running_sum + int(num) if (max_sum < running_sum): max_sum =...
import os """ @TODO 1. Get Path of file to move to archive 2. Append "#Archive" tag to copy of .md file 3. Move appended file to /Archive Folder 4. Delete original file """ def append_new_line(file_name, text_to_append): """Append given text as a new line at the end of file""" # Open the file in append & rea...
import numpy as np import matplotlib.pyplot as plt def F(x): return x**2 def grad_F(x): return 2*x def gradient_descent(F, grad_F, learning_rate, x, i): count = 0 x_val = [x] y_val = [F(x)] while count < i: x = x-learning_rate*grad_F(x) count += 1 # print(F(x)) ...
#!/bin/python3 import sys def findRunningMedian(isEven, elem, curr, left, right): if curr == None: # Case len 1 curr = left = right = elem return float(curr), left, right if isEven: # Even Case if left == curr: # Case len 2 if elem < curr: ...
# Find the princess position def findPrincess(n, grid, elem): posI = 0 posJ = 0 for i in range(0,n): for j in range(0,n): if grid[i][j] == elem: posI = i posJ = j return [posI, posJ] return [-1,-1] # Find next move def nextMove(n,r,c,...
# 10개 중 1개의 오답으로 인해 오래 걸린 문제 # 책이 홀수이면 l = 1, 짝수이면 l = 0을 해줬던게 문제 # 엣지 케이스는 10 3 2 def search(entire, target): l = 1 r = middle = entire cnt = 0 while True: middle = (l + r) // 2 if target > middle: l = middle cnt += 1 elif target < middle: r =...
# Have user enter Fahrenheit or Celsius, then convert user provided temperature to opposite temperature scale. # Step 1 - Display message saying "Type f for fahrenheit or c for celsius" and get input # Step 2 - store input # Step 3 - determine if inuput is fahrenheit or celsius # Step 4 - get input and store input for ...
# Day 1: Will be working with data types and adding/concating items that are # of integer, double, and string formats i = 4 d = 4.0 s = "HackerRank " i_2 = int(input()) d_2 = float(input()) s_2 = str(input()) print(int(i + i_2)) print("{:.1f}".format(float(d_2 + d))) print(s + s_2)
# Day 6 requires you to take in input from the STDIN and then print out # all of the characters in the even index as a word and all the characters # in the odd index as a word, Ex: water = wtr ae # Link: https://www.hackerrank.com/challenges/30-review-loop/problem for i in range(int(input())): s = input().strip() ...
# Year 2000 - 2020 # Each year after 2000 + 5000kr # Each 10k km -(5)000 kr import random import csv def makeCar(): make = 'Mercedes-Benz' year = random.randint(2000,2021) newprice = 700000 kmperliter = 25 km = random.randint(0,200000) horsepower = random.randint(50, 120) gearbox = random....
num = 1 for i in range(1, 101): num *= i print num print sum([int(x) for x in str(num)]) # a = raw_input("Press Enter key")
#!/usr/bin/env python # coding=utf-8 ''' github: adrian273 ''' try: from tkinter import * from tkinter import messagebox except ImportError: print('Modulo TKINTER requerido') def cal_suma(): suma = number1.get() + number2.get() messagebox.showinfo('Resultados', str(suma)) def cal_rest(): ...
import pandas as pd pd.set_option('display.expand_frame_repr', False) tweets_csv = pd.read_csv("exercises/tweets.csv") tweets_df = pd.DataFrame(tweets_csv) print(tweets_df.head(5).tail(3))
import string import random import os import platform import re import time STRING_CHARS = string.ascii_lowercase GUESSES = 5 def pick_random_letter(): return random.choice(STRING_CHARS) def detect_os(): return platform.system() def detect_clear_screen_string(os_name): if os_name == 'Windows': ...
from itertools import combinations def solution(num_buns, num_required): copies_of_each_key = num_buns - num_required + 1 combos = list(combinations(range(num_buns), copies_of_each_key)) result = [[] for i in range(num_buns)] for i, combo in enumerate(combos): for j in combo: resu...
name="laptop is good" count=0 for x in name: if x.isalpha(): count=count+1 print count
from collections import Counter def count_letters(words): counter = Counter() for word in words.split(): counter.update(word) return sum(counter.itervalues()) words = raw_input() print count_letters(words)
#!/usr/bin/python3 import sys def main(): solve() def solve(): for line in sys.stdin: if '+' in line: first, second = line.split(' + ') res = int(first) + int(second) else: first, second = line.split(' * ') res = int(first) * int(second) # output print(line[:-1]) int_max = 2147483647 if in...
import readline VALID_OPS = ['=', '+', '-', '*', '/', 'c', 'p'] class StackCalcException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class StackCalculator(object): def __init__(self): self.stack = [] def __st...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: dummy = ListNode(0) original_head = ListNode(0) dummy.next = head or...
x = 10 # x が 30 より大きい場合に「 xは30より大きいです 」と出力 if x > 30: print('xは30より大きいです') money = 500 apple_price = 200 # money の値が apple_price の値以上の時、「 りんごを買うことができます 」と出力 if money >= apple_price: print('りんごを買うことができます')
#Time Complexity : O(N) where N is the numbers present in the list #Space Complexity : O(N) for using one hashmap #Did this code successfully run on Leetcode : Yes but after seeing today's lecture video #Any problem you faced while coding this : Yup, I could not solve the question until I saw the lecture video #Y...
#!/usr/bin/env python ''' Update: 2010 Added extra unnessary comments (that should be self explantory) so that it is understandle by new commers A simple connect 4 game on terminal for 'proof of concept' Initially wrote to familarize myself with Python - list manipulation exercise But more importantly, it was...
Pereira = [] Bucaramanga = [] Bogota = [] Cali = [] Barranquilla = [] """ def Note1 (array): sum = 0 for element in array: sum += element / 2 return sum """ a = float(input("ingrese la temperatura de pereira ")) Pereira.append(a) b = float(input("ingrese la 2da temperatura de pereira ")) Pereir...
def find_max_consecutive_ones(nums): """ Given a binary list(only contain 0 and 1), find the maximum number of consecutive 1s in this list. :type nums: List[int] :rtype: int Input: [1,1,0,1,1,1] Output: 3 (last three 1s) """ i = 0 one_counter = 0; while i < len(nums): ...
import Chromosome import random class Mate: def __init__(self,population,pairingType): #Create mothers and fathers using either # a. Top Down Pairing # b. Tournament Pairing if pairingType == 'topDown': self.fathers, self.mothers = self.topDown(population) elif...
import math import numpy as np import numpy.linalg as la def point_from_angle(x, y, angle, length): """return the endpoint of a line starting in x,y using the given angle and length""" x = x + length * math.cos(angle) y = y + length * math.sin(angle) return x, y def distance(point_1, point_2): "...
board= [ ["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"] ] user= True def print_board(board): for row in board: for slot in row: print(f"{slot}", end="") print() print_board(board) def quit(user_input): if user_input == "q": print("Thanks for playing") ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, project_dir) class Solution(object): def minSteps(self, n): """ :type n: int :rtype: int 质数因式分解 ""...
#!/usr/bin/env python # -*- coding: utf-8 -*- import copy import os import sys project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, project_dir) class Solution: def wordBreak(self, s, wordDict): dp = [False] * (len(s)+1) # 哨兵位, 检查整个字符串是否属于字典 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- def expandAroundCenter(s, left, right): l = 0 r = 0 len_s = len(s) while left >= 0 and right < len_s and s[left] == s[right]: l = left r = right left -= 1 right += 1 return r - l + 1 class Solution(...
import math def is_perfect_number(): number = int(input('Enter a number ')) perfect_square = int(math.sqrt(number)) ** 2 if perfect_square == number: return True else: return False while True: if is_perfect_number(): print('Its a perfect number') break else: ...
# .-------------------------------------------------------------------------------------. # | Puzzle Author: Eric Wastl; http://was.tl/ | # | Python 3 Solution Author: Henri Branken | # | GitHub Repository: https://github.com/HenriBra...
# .-------------------------------------------------------------------------------------. # | Puzzle Author: Eric Wastl; http://was.tl/ | # | Python 3 Solution Author: Henri Branken | # | GitHub Repository: https://github.com/HenriBra...
def kmer(seq, mer): """ Given a sequence of characters, returns the kmer distribution in that sequence. :param seq: Sequence of characters (string). :param mer: Integer word size of required kmers. :return: String of space-separated numbers representing the kmer distribution in the sequence. "...
#!/usr/bin/env python3 ''' lib/task/pool.py Task pool abstraction. Replacement for `concurrent.futures`. Defines a task pool class that can be used to run tasks asynchronously. Most of this logic was taken from pythonfutures: https://github.com/agronholm/pythonfutures https://git.io/vdCQ2 ''' from concurrent.future...
WORDS = set(i.lower().strip() for i in open("words2.txt")) def is_valid_word(word): return word in WORDS #check if one char is different #create graph using function
WORDS = set(i.lower().strip() for i in open("words2.txt")) def is_valid_word(word): return word in WORDS print (is_valid_word("test"))
# -*- coding: utf-8 -*- import re import string def word_count(msg): msg = re.sub(u'[^\w\u0370-\u1FFF+\d]|_', ' ', msg.decode("utf-8").lower()) words = msg.split() counted = dict((word,0) for word in words) for word in words: counted[word] += 1 return counted
################################################################################## # An input that is controlled by two keys and can have 3 values, -1, 0, 1 # # Example: in a FPS game, keys W and S control forward and backward movement # # pressing W, output is +1 or move forward # pressing S, output ...
# ========== 1. basic REST API using Flask =============== # get/post # provide parameters to the url from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): # how to extract the content from a post # maybe can be used to process the da...
def stringOperation3(s): s = s.lower() dict1 = {} for ch in s: if ch not in dict1: dict1[ch] = 1 else: dict1[ch] += 1 set1 = {(1, 2)} for (key, value) in dict1.items(): set1.add((key, value)) set1.remove((1, 2)) return set1 if __name__ == '__...
def mapping(test_dict1, test_dict2): res = {} for key, val in test_dict1.items(): for key1 in val: res.setdefault(key, []).extend(test_dict2.get(key1, [])) return res if __name__ == '__main__': test_dict1 = {"Gfg": [4, 7], "Best": [8, 6], "is": [9, 3]} test_dict2 = {6: [15, 9]...
def Monotonic(A): return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or all(A[i] >= A[i + 1] for i in range(len(A) - 1))) if __name__ == '__main__': A = [6, 5, 4, 4] B = [5, 15, 20, 10] print(Monotonic(A)) print(Monotonic(B))
def findMinSum(num): sum = 0 i = 2 while (i * i <= num): while (num % i == 0): sum += i num /= i i += 1 sum += num return sum if __name__ == '__main__': a = 12 b = 105 print(findMinSum(a)) print(findMinSum(b))
def main(): numbers = [0, 0, 0, 0] grades1 = [0, 0, 0, 0] grades2 = [0, 0, 0, 0] average = [0, 0, 0, 0] for x in [0, 1, 2, 3]: print("") numbers[x] = input("Student {0} number:".format(x + 1)) grades1[x] = int(input("student {0} grade 1:".format(numbers[x]))) grades2[...
import re def countSmileys(arr): valid_eyes = [':', ';'] valid_nose = ['-', '~'] valid_mouth = [')', 'D'] count = 0 for i, item in enumerate(arr): if len(item) == 2: # no nose if item[0] in valid_eyes and item[1] in valid_mouth: count += 1 ...
# -*- coding: utf-8 -*- """ Created on Mon Nov 13 19:01:19 2017 @author: Bruce """ class Shape: def __init__(self, x=0, y=0, color=None): self.x = x self.y = y self.color = color def translate(self, delta_x, delta_y): self.x += delta_x self.y += delta_y ...
import turtle #Abrir ventana window = turtle.Screen() #Inicia el dibujo square = turtle.Turtle() #dibuja square.forward(200) square.left(90) square.forward(200) square.left(90) square.forward(200) square.left(90) square.forward(200) square.left(90) #Mantiene el dibujo en pantalla turtle.mainloop()
import numexpr as ne EARTH_RADIUS = 6371.0 def geodetic_distance_fast(lons1, lats1, lons2, lats2): """ Calculate the geodetic distance between two points or two collections of points using a formula that is substantially faster than the Haversine formula, but is nearly as accurate for distances up to...
# modify MergeSort to count the number of inversions in an array def SimpleInvCount(array): """complexity O(n**2)""" count = 0 n = len(array) for l in range(0, n - 1): for k in range(l + 1, n): if array[l] > array[k]: count += 1 return count # sort and count inve...
from datetime import date from typing import List, Tuple def approximateGrowth(data: List[Tuple[date, int]]) -> List[Tuple[date, float]]: # filter low values data = list(filter(lambda x: x[1] >= 10, data)) result = [] approx = None for i, j in zip(data[:-1], data[1:]): diff = j[1] / float...
""" Написать 2 генератора: 1) Генератор simple_number первый идет по всем простым числам (число делится только на 1 и на само себя) 2) Генератор odd_simple, который используется значения первого и возвращает из них нечетные """ def simple_number(n: int = 2) -> int: while True: counter = 1 for i in...
""" Написать функцию triangular_sequence, которая принимает n и выводит следующую последовательность 1 22 333 4444 55555 ... Например: n = 3: 1 22 333 n = 6: 1 22 333 4444 55555 666666 """ def triangular_sequence(n: int, multiply=1) -> int: if multiply <= n: print(str(multiply) * multiply) tri...
"""Fetch structured JSON-LD data from a given URL.""" import requests import extruct from w3lib.html import get_base_url import json def get_urls(filename): url_ls = [] with open(filename, "r") as file: for line in file: stripped_line = line.strip() url_ls.append(st...
#!/usr/bin/env python # -*- coding: utf-8 -*- from stack import Stack def is_paranthesis_balanced(s): pass open_b = ['(','[','{','<'] matches = [('{','}'), ('[',']'), ('(',')'), ('<','>')] stack = Stack(len(s)) for i in s: if i in open_b: stack.push(i) else: ...
print("Down Payment calculator ") price = input("WHats the price of property? ") credit_good = True if credit_good: down_payment = int(price)/10 result = f' you have to pay {down_payment}' print(result) else: down_payment = int(price)/5 result = f' you have to pay {down_payment}' print(result) ...
import sys import collections import random global totalNodes global nodesToAdd #Returns filled edges def initializeGraph() : edges = collections.defaultdict(list) for i in range(0,nodesToAdd): for j in range(0,nodesToAdd): if not i == j: edges[i].append(j) totalEdges...
from Crypto.Cipher import AES import binascii ciphertext = input() if len(ciphertext) == 32: cipher = AES.new('b1daf001f51d0b89c2619d52af0fe218', AES.MODE_ECB) print(cipher.decrypt(binascii.unhexlify(ciphertext)).decode('ASCII'))
def add(a,b): result = a + b print( "{} + {} = {}".format(a,b,result) )#print문은 수정하지 마세요. add(10,5)
rainbow=["빨","주","노","초","파","남","보"] for i in range(len(rainbow)) : color = rainbow[i] print('{}번째 색은 {}'.format(i+1,color))
rainbow=["빨","주","노","초","파","남","보"] for i,color in enumerate(rainbow) : print('{}번째 색은 {}'.format(i+1,color))
list1 = [1, 2, 3] list2 = [1, 2, 3] if list1 is list1: print("당연히 list1과 list1은 같은 인스턴스입니다.") if list1 == list2: print("list1과 list2의 값은 같습니다.") if list1 is list2: print("그리고 list1과 list2는 같은 인스턴스입니다.") else: print("하지만 list1과 list2는 다른 인스턴스입니다.")
#Ejercicio 9.5.4. Escribir una función que reciba un texto y para cada caracter presente en el texto devuelva la cadena más larga en la que se encuentra ese caracter. def cadena_mas_larga(cadena:str): """ devuelve por cada caracter la cadena mas larga en la que se encuentra dicho caracter """ diccionario = {} ...
#Ejercicio 3.2. Usando las funciones del ejercicio anterior, escribir un programa que pida al usuario dos intervalos expresados en horas, minutos y segundos, sume sus duraciones, y muestre por pantalla la duración total en horas, minutos y segundos. def convierte_a_segundos(horas, minutos, segundos): """ convierte...
#Ejercicio 3.3. Escribir una función que, dados cuatro números, devuelva el mayor producto de dos de ellos. Por ejemplo, si recibe los números 1, 5, -2, -4 debe devolver 8, que es el producto más grande que se puede obtener entre ellos (8 = −2 × −4). def mayor_producto_entre_dos(n1, n2, n3, n4): """ me devuelve el...
#Ejercicio 7.7. Escribir una función que reciba una lista de tuplas (Apellido, Nombre, Inicial_segundo_nombre) y devuelva una lista de cadenas donde cada una contenga primero el nombre, luego la inicial con un punto, y luego el apellido. def nombre_completo(nombres:list): """Devuelve una lista de cadenas con el no...
#Ejercicio 10.7. Persistencia de un diccionario #a) Escribir una función cargar_datos que reciba un nombre de archivo, cuyo contenido tiene el formato clave, valor y devuelva un diccionario con el primer campo como clave y el segundo como valor. def cargar_datos(archivo): """ devuelve un diccionario con los usuari...
#Ejercicio 9.5.3. Continuación de la agenda. #Escribir un programa que vaya solicitando al usuario que ingrese nombres. #a) Si el nombre se encuentra en la agenda (implementada con un diccionario), debe mostrar el teléfono y, opcionalmente, permitir modificarlo si no es correcto. #b) Si el nombre no se encuentra, debe ...
#Ejercicio 2.7. Escribir un programa que imprima por pantalla todas las fichas de dominó, de una por línea y sin repetir. def domino(): ficha = "" for i in range(7): for k in range(i, 7): ficha = f"|{i} : {k}|" print(ficha) domino()
#Ejercicio 2.8. Modificar el programa anterior para que pueda generar fichas de un juego que puede tener números de 0 a 𝑛. def domino(): cantidad = int(input("ccual es la pieza con mayor puntos?: ")) ficha = "" for i in range(cantidad+1): for k in range(i, cantidad+1): ficha = f"|{i} :...
''' pyrainflow Rainflow counting of time-history data in Python. Based on the method described here: https://community.sw.siemens.com/s/article/rainflow-counting ''' import pandas as pd import numpy as np import matplotlib.pyplot as plt def round_nearest(value, lst): ''' Round ``value`` to the nearest ...
import json import requests from difflib import get_close_matches date=input("Please enter the date (in the format 'yyyy-mm-dd' or 'latest'): ") base=input("Convert from (currency) in the format as example: (USD/EUR): ") curr=input("Convert to (currency) in the format as example: (USD/EUR): ") base=base.upper() curr...
# -*- coding: utf-8 -*- """ Created on Tue Jun 18 11:47:35 2019 @author: Yudy Andrea Fierro """ #EJERCICIO 10 cadena = input('Ingrese la cadena de texto. ') lista_mins = ['a','á','b','c','d','e','é','f','g','h','i','í','j','k','m','n', 'l','ñ','o','ó','p','q','r','s','t','u','ú','ü','v',...
# Akses P = 0 # Akses P U = 1 ==> Katanya diakses sampai range perulangan # Akses P U R = 2 # print(kata.extend()) # print(kata_baru.append(kata)) # for rows in range(len(kata)): # # hasil = kata_baru.append(kata[0:rows+1]) # print(kata[0:rows+1], end = "") # kata = "Digital" def ravel(kata): ...
######################## """ def hello(): """this functions prints hello world""" print("hello world") # calling the function hello() # what you can do with docstring? print(hello.__doc__) """ ######################## """ def my_func(param1 = "defult"): print("This is {}".format(param1)) my_func() """...
from math import sqrt, acos class Vector: def __init__(self, x, y): self.x = x self.y = y def length(self): return sqrt(self.x ** 2 + self.y ** 2) def __mul__(self, factor): return self.__class__( self.x * factor, self.y * factor ) def angle(self, other): ''' Calculate the angle between V1 and ...
import random import time class Piece: #Ship object to represent the game pieces def __init__(self, name, size): self.size = size ...
class Node: def __init__(self,data): self.data = data self.next = None self class LinkedList: def __init__(self): self.head = None def push(self,new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def pr...
# unpacks the module from sys import argv # defines what varibles to unpack. script, filename = argv # sets a variable name to the file to open txt = open(filename) # shows the name of the file print "Here's your file %r" % filename # prints the contents of the file print txt.read() close(filename) # prompt input print...
#Quinton dean #This program prints the average of random integers using "random" import random number = int(0) k = eval(input("Give me the number of integers you wish to create ")) for i in range(1,k): randomNum = random.randint(1, 999) number = randomNum + number average = float(number/k) print(form...
#Quinton Dean #This program converts ASCII for greek letters and prints them lowerAlpha = chr(945) lowerBeta = chr(946) lowerLamda = chr(955) lowerGamma = chr(947) lowerDelta = chr(948) lowerTheta = chr(952) lowerPi = chr(960) lowerSigma = chr(963) lowerOmega = chr(969) theta = chr(920) lamda = chr(923) ...
#AUTOR : Arnaud HINCELIN #Date : 07/2020 En python ==>> Indentation compte !!!!!!!!!!!! (vs tous autres langages) #==================================================== #FONCTIONS ET VARIABLES #==================================================== #Fonction simple avec lambda f = lambda x: x**2 a=f(2) #print(a) d =...
''' This is for Task 8 - Files The following are questions that I had when reading through the session04 lecture notes on reading and writing files. 1) Make a document. Read in the document. Then print every other line of the document. 2) Open and write to a new document ''' # Question 1: Can I read in a document an...
def fibonacci(n): """Return the nth number in the Fibonacci series. Args: n - positive int. The position in the series to return. """ value1, value2 = 0, 1 for i in range(n): value1, value2 = value2, value1 + value2 return value1 def lucas(n): """Return the nth number in ...
'''Dictionary Set Lab''' '''Richard Green''' '''Session 05''' my_dict = {"name": 'Chris', "city": 'Seattle', "cake": 'Chocolate'} # Display the dictionary. print my_dict # Delete the entry for cake my_dict.pop('cake') # Display the dictionary. print my_dict # Add an entry for fruit with M...
def ordinal_value(): """ 1. What's the ordinal values of my name: Karen? """ for i in "Karen": print(ord(i)) def greetings(): """ 2. How to create a greeting using the __format__() method? """ name = "Peter" print("{}, you have a cool name".format(name)) def string_spli...
# Exceptions (2 questions) # Question 1 def age_exception(): """ What if I print ask to print a key that isn't in the dictionary? Result: ValueError: invalid literal for int() with base 10: 'ten' (line 15) - when a non integer is entered, "Entry Error." is printed """ while True: ...
def fibonacci(n=5): '''This function performs a fibonacci series based off of a single user''' '''defined value.The function should returns ``nth`` value in the fibonacci''' '''series Numeric arguments: n an integer Returns: an integer ''' # Returns the fibonacci series based off a user def...
'''def my_name_error(): print x my_name_error() def my_function(): print "a" #a = 1 + 1 #print 'a' my_function()''' def my_text(): str = "hi there" # print "str.capitalize(): ", str.upper() print str.upper() my_text()
def mail_room(): reply = none def make_donor_list(): donor_list = [] donor_name = [name, total_donated, number_of_donations, average_donation_amount] for donor_name in donor_list: add donor_name to donor_list def ask_input(): reply = choose_thanks_or_create_re...
#!/usr/bin/env python """JosephO'Malley""" """Session 3 task6""" fruit_list = ["Apples", "Pears", "Oranges", "Peaches"] print fruit_list new_fruit = raw_input("What fruit would you like to add?") fruit_list.append(new_fruit) print fruit_list number = int(raw_input("Please provide a number between 0 and 4")) print ("Yo...