text
stringlengths
37
1.41M
def collapseDuplicates(a): output = "" last_char = None for char in a: if char == last_char: continue output += char last_char = char return output print collapseDuplicates("a"), "Should be", "a" print collapseDuplicates("aa"), "Should be", "a" print collapseDupli...
#! /usr/bin/python from JackToken import JackToken class Node(object): """docstring for Node""" def __init__(self, value, depth=0): super(Node, self).__init__() self.elementName = None; self.elementVal = None; if type(value) is JackToken: self.elementName = value.getTokenType() self.elementVal = value...
def lastjump(a,n): i=0 while i<n: i+=a[i] try: if i==a[i]: return True except: return False def main(): a=[] n=int(input()) for i in range(n): a.append(int(input())) print(lastjump(a,n)) main()
def circle(a): area=3.14*a*a print("Area :", area) def rectangle(l,b): area=l*b print("Area :",area) def triangle(b,h): area=0.5*b*h print("Area :",area) def main(): try: a=int(input("Enter radius for circle :\n")) circle(a) print("\n ----Rectangle----\n") l=int(input("Enter length :\n")) b=int...
num1 = raw_input ("> ") num2 = raw_input ("> ") if num1 > num2: print "naimenshee chislo" + num2 else: print "naimenshee chislo" + num2
# @author Daphne Barretto # 12/01/2019 # AoC-2019-01 Part 1 # import miscellaneous operating system interfaces import os # get filename input.txt assuming it is in the same folder as the script filename = os.path.dirname(os.path.abspath(__file__)) + "/input.txt" # open the file in read mode file = open(filename, "r")...
"""The progress bar.""" import sys from collections.abc import Iterable, Sized from typing import TextIO, Tuple, Union from unicodedata import east_asian_width as eaw BAR_SYMBOLS = ("", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█") BAR_PREFIX = " |" BAR_SUFFIX = "| " class JabBar: """Just Another Beautiful progress B...
import sys def decryptRailFence(cipher, key): rail = [[None for c in xrange(len(cipher))] for r in xrange(key)] row = 0 col = 0 for i in xrange(len(cipher)): if row == 0: down = True if row == key-1: down = False rail[row][col] = 'X' col+=1 if down: row+=1 else: row-=1...
from dataclasses import dataclass @dataclass class Position: x:int = 0 y:int = 0 def __iadd__(self,other): self.x+=other.x self.y+=other.y return self def checkSlope(areaMap,slope):#Check the amount of trees in your trajectory descending areaMap with given slope. pos = Positio...
import time as t import numpy as np import pandas as pd CITY_DATA = { 'chicago': 'chicago.csv', 'nyc': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(city, month, day): """ Asks users to specify a city, month, and day to analyze. Returns: (str) city...
""" Clase Abstracta que define los metodos claves de la especificacion """ class BaseEspecificacion: def __init__(self, objeto): self._objeto = objeto return def es_satifecho_por(self, objeto): pass def y(self, especificacion): pass def o(self, especificacion): ...
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder, their colleagues and Austin Strozier. """ ######################################################################## # Done: 1. # On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name...
# list part 1 subjects = ['python', 'java', 'car'] print(subjects) print(subjects[0]) print(subjects[1:]) print(subjects[-1]) # in / not in print("java" in subjects) print("ada" in subjects) print("ada" not in subjects) # add anything print(subjects + [' rubi ' ,89] ) print(subjects * 3)
#!/usr/bin/env python # coding: utf-8 # # 口コミ(食べログ) # we will try to find about "When I visit Japan (or particular town in Japan) what kind of food that is recomended by Japanese that should I try?" # # This code will contain of the data scraping and data cleaning part # # Data Scraping # In[ ]: #import the libr...
# To find biggest of given two numbers from the key board #!/usr/bin/python #x=int(input("Enter The 1st Number:")) #y=int(input("Enter The 2nd Number:")) #z=int(input("Enter The 3rd Number:")) #if x>y and x>z: #print("The Bigger Number is:",x) #else: # print("The Smaler Number is:",y) #print("The Smalest Number...
#!/usr/bin/python ########## Right Triangle Shape ########## x=int(input("Enter The Number Of Rows:")) for y in range(1,x+1): for z in range(1,y+1): print("*",end="") print()
#!/usr/bin/python n=int(input('Enter The N Rows:')) #for i in range(0,n): #for j in range(0,n-i-1): #print(end=" ") #for j in range(0,2*2*i+1): #print("*",end="") #print() ########## Using for loop ########### def pyramid(rows): for i in range(rows): print(''*(rows-i-1)+'*'*(2*i...
class Person: def __init__(self): print("Init the class") if __name__=="__main__": print("111") a=0 person1 = Person() print("2222") a=1 print(2+3)
from PointT import* from Ships import* from Board import* # Tyler Philips #April 1 the work being submitted is your own individual work #ASSUME: there are 2 real players. No cpu ## @brief this class has functinos that bring the other classes together and create a game ## @param boardsP1 is board abject for player 1. ...
# coding: utf-8 import sys, re def flip_dict(dict_to_flip): ''' flip a dict. Parameters ---------- dict_to_flip : dict Examples -------- >>> flip_dict({'a': 2, 'b': 3, 'c': 4}) {2: 'a', 3: 'b', 4: 'c'} Notes that duplicated data will be automaticly dropped >>> flip_dict({...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def min_node(self): if self.left is not None: return self.left.min_node() return self class BinaryTree: def __init__(self, root=None): if not root: ...
"""Write two modules pytasks.py and runner.py. Module pytasks contains definition for functions from previous tasks. Separate module runner contains runner() function. runner module can be imported or started from command line as script. generate_numbers() count_characters() fizzbuzz() – returns list with values is_pa...
dolar=float(input("Insira o valor em reais que possui: ")) reais=float(input("Insira o valor da cotação do dolar: ")) print("O valor em dolares é ",dolar*reais)
x = int(input('Insira o primeiro valor: ')) y = int(input('Insira o segundo valor: ')) print('A soma destes valores é: ',x+y)
data = int(input('Digite a data do seu aniversário: ')) DD = data//10000 MM = data//100 - DD*100 AA = data - DD*10000 - MM*100 print(AA,MM,DD)
Compare two list and return matches, without using for loop a = [1, 2, 3, 4, 5] b = [9, 5, 7, 6, 8] Common element = 5 a = [1, 2, 3, 4, 5] b = [9, 5, 7, 6, 8] sa = set(a) print(sa.intersection(b))
# Foizni topish dasturi # a sonni P foizni topish progi print("A sonni P foizini topish") a = int(input("a sonni kiritin: ")) p = int(input("P foizni kiritin: ")) x = a * p / 100 print("a sonni P foizi shu: ",x)
login = input('Yangi login tanlang:') if len(login) <= 5: # agar login 5 harifdan kichik bulsa 1 print('Login 5 harfdan kup bulishi kerak') else: print('login qabul qilindi')
son = input('ixtiyoriy son kiritin:') if int(son) <=50: print('kiiritilgan son 50 teng yoki kichik ') else: print('kiritilgan son 50 dan katta')
ism = input('Ismingiz nima:\n') if ism.lower() != 'valijon': print(f"uzur {ism.title()} biz Valijon ni kutyapmiz") else: print("salom Valijon")
from policy import Policy from board import Board class AI: def __init__(self, Computer): self.shape = Computer self.computer = Policy(self.shape) def Opponent(self): if self.shape == "X": return "O" return "X" # Check if there is any spaces left on board ...
""" p6_linear_regression.py Author: Jagrut Gala Date: 28-08-2021 Practical: 6 Objective: Predict the price of a house using Linear Regression. """ import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model import pandas as pd import io from pathlib import Path p= Path(__file__)....
#!/usr/bin/env python # coding: utf-8 # In[1]: def hanoi(n, P1, P2, P3): """ Move n discs from pole P1 to pole P3. """ if n == 0: # No more discs to move in this step return global count count += 1 # move n-1 discs from P1 to P2 hanoi(n-1, P1, P3, P2) if P1: ...
from random import randint secret = randint(1, 10) guess = 0 count = 0 print('Guess the secret number between 1 and 10') while guess != secret: guess = int(input()) count += 1 if guess == secret: print('You got it! Nice job.') elif abs(guess - secret) == 1: print('You are really clos...
#print all colors from the list1 not contained in list2 color_list1=set(["white","black","yellow"]) color_list2=set(["green","blue","red"]) print(color_list1.difference(color_list2))
# https://leetcode-cn.com/problems/copy-list-with-random-pointer/ class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random class Solution: def __init__(self): self.visited = {} def copyRando...
import copy class BinaryTree: # define and init a binary tree def __init__(self, data): self.data = data self.left = None self.right = None # preorder traversal def preorder_traversal(self, tree) -> None: if tree: self.preorder_traversal(tree.left) ...
# https://leetcode-cn.com/problems/binary-tree-level-order-traversal/ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrder(self, root: TreeNode) -> list: tree = [[root]] visi...
""" input:target = [9,3,5] output:true explanation:start from [1, 1, 1] [1, 1, 1], sum is 3 ,location is 1 [1, 3, 1], sum is 5, location is 2 [1, 3, 5], sum is 9, location is 0 [9, 3, 5] successful """ def ispossible(target: list) -> bool: m = max(target) m_l = target.index(m) s = sum(target) - m if m...
""" Giving a set of coins, and their value are c1,c2...cn How to choose coins to achieve that the summary of selected coins is the largest where any location of coins are not adjoining? F(n)=max(cn+F(n-2),F(n-1)) """ """ there are n oranges,you have three choices to eat them: 1. eat 1 2. if n%2 == 0, eat n/2 3. if n%...
# -*- coding: utf8 -*- """ Using the Python language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it (ie. if num = 4, return (4 * 3 * 2 * 1)). For the test cases, the range will be between 1 and 18. """ def first_factorial(num): try: num = int(num...
# 참과 거짓 boolean # if # True, False # and, or, not # a = True # b = False # # A가 참이고 그리고 B가 참이라면 (A와 B가 둘다 참이여야 된다) # print(a and b) # # A가 참이거나 혹은 B가 참이라면 (A나 B 둘 중에 하나라도 참이면 된다) # print(a or b) # # # # = & == # # a = true a라는 값에 true를 넣어준다는 의미 # # a == ture a 와 true가 동일하냐 라는 뜻 equal의 의미 # c = True # print(a == True) ...
def calculate(m, i, y): original_mortgage = m for year in range (0, y): print(m) amt = (m/(y - year))/12.0 print('Year '+str(year + 1)+': $%.2f per month' % amt) m -= (amt * 12) m += (original_mortgage * i) original_mortgage *= (1.0 + i) total_mortgage = int(input('Enter the amount of your mortgage: $'))...
def calculate_tax(amt, tax): return amt * (1.0 + tax) amt = float(input('Enter a dollar amount: $')) tax = float(input('Enter the tax amount (decimal): ')) print('Your total is $' + str(calculate_tax(amt, tax)))
""" Generate vocabulary for a tokenized text file. """ import sys import argparse import collections import logging import os def get_vocab(infile, max_vocab_size=None, delimiter=" ", downcase=False, min_frequency=0, to_file=True): # Counter for all tokens in the vocabulary cnt = collections.Co...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of the PyBGL project. # https://github.com/nokia/pybgl import sys from collections import defaultdict from .algebra import BinaryRelation, BinaryOperator, Less, ClosedPlus from .breadth_first_search import DefaultBreadthFirstSearchVisitor from .graph...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of the pybgl project. # https://github.com/nokia/pybgl import heapq class Comparable(object): """ Wrapper used to define a custom pre-order for a given object. This class is inspired from ``functools.cmp_to_key`` and `this discussio...
#!/usr/bin/env python3 """ Basic Python generator examples. The yield statement halts the function and saves it state. The function continues from its halted state on successive calls. """ def all_even(max): n = 0 while n < max: yield n n += 2 def fib_generator(nth): n = 0 ...
#String Compression def string_compression(s): if len(s) <= 1: return s compressed_string = "" count = 1 for i in range(len(s)-1): if s[i] == s[i+1]: count += 1 else: compressed_string = compressed_string + s[i]+ str(count) count = 1 i...
#Given a circular linked list, return node at the beginning of the loop class Node: def __init__(self, value): self.value = value self.next = None def loop_detection(node): fast = node slow = node while fast and fast.next and slow: slow = slow.next fast = fast.next.next...
#Import the os module & #Module for reading CSV files import os import csv #assign variables total_votes = 0 candidates = [] winning_count = 0 election_winner = "" #Dictionary for candidate and votes each candidate_votes = {} #Set path for the CSV file csvpath = os.path.join('.', 'PyPoll', 'Resources', 'election_da...
from datetime import datetime def fun(): print("done") print("begin time:",datetime.now()) fun() print("end time:",datetime.now()) def callfun(func): print("begin time:", datetime.now()) func print("end time:", datetime.now()) def test(): print("test") callfun(test) ########################排...
""" On the whiteboard, please write a version of the unix utility "wc" in the language of your choice. This is a rudimentary programming question, but it tests many things: Working under stress. It requires the candidate to actually get up to the whiteboard and write some code under observation. This tests how well t...
""" Find the height of a binary tree. Recusion f(b, c) Another solution: store branch height in each node :) """ # Expected height: 3 tree = { 'children' : [ { 'children' : [] }, { 'children' : [ { 'children' : [] ...
""" This problem was asked by Google. Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical. For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8. In this example, assume nodes with the same value are the exact ...
""" This problem was asked by Palantir. Write a program that checks whether an integer is a palindrome. For example, 121 is a palindrome, as well as 888. 678 is not a palindrome. Do not convert the integer into a string. """ # This solution is O(N * 1.5) def get_digits(num): digits = [] while num >= 10: digits.a...
""" This problem was asked by Microsoft. Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. For example, given the set of w...
print('Binary translator') sentence = input('input a sentence to be translated in : ') sentence_ascii, sentence_char,rtn = [], [],'' for i in range(len(sentence)): sentence_char.append(sentence[i]) sentence_ascii.append(ord(sentence[i])) def to_binary(n): binary,binary_val = [0,0,0,0,0,0,0,0],[128,6...
# def fact(n): # if n==0: # return (1) # if n==1: # return (1) # else: # return n*fact(n-1) # # # factorial_required=[int(input()) for i in range(int(input()))] # print(*list(map(lambda x:fact(x),factorial_required)),sep='\n') import math T = int(input()) for i in range(0,T,1): N...
A=[1,2,3] string="" for i in range(len(A)): string=string+str(A[i]) string=str(int(string)+1) answer=[int(i) for i in string] print(answer)
""" String 이 주어지면, 중복된 char 가 없는 가장 긴 서브스트링 (substring)의 길이를 찾으시오. 예제) Input: “aabcbcbc” Output: 3 // “abc” Input: “aaaaaaaa” Output: 1 // “a” Input: “abbbcedd” Output: 4 // “bced” """ def search_word(txt): result = 0 start = 0 char_dict = {} for i, c in enumerate(txt): if c in char_dic...
a=[1,2,3,4] b=[2,3,4] # c=(i+j for i in a for j in b) c=[i+j for i in a for j in b] print(c) #print(next(c)) #print(next(c)) #print(next(c))
#---------------------------------Importing Libraries import tkinter from tkinter import Button, StringVar from tkinter import Tk from tkinter import PhotoImage import socket import threading from tkinter import Listbox from tkinter import Entry from tkinter import Scrollbar #------------------A function to calculate ...
import re # To Read Tweets directly from Program: tweet = """Most employees fulfilled with used hardware based on device turns four years old. Some job categories (hardware or software developer, technical sales, etc.) are eligible at three years. Recognizing that employee job roles or device request qualities an...
import time import timeit #40.a i=12 while i>0: localtime = time.asctime(time.localtime(time.time())) print ("Local current time :", localtime) time.sleep(5) i=i-1 #40.b code = """list1=['Surat','Vyara','Vadodara','Ahmedabad','Div'] list2=['Pune','Chennai','Mumbai','Kolkata','Delhi'] list3=['Skikk...
Str = "this is string example....wow!!!"; Str = Str.encode('base64','strict'); print ("Encoded String: " + Str) print ("Decoded String: " + Str.decode('base64','strict'))
def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l)//2; # Check if x is present at mid if int(arr[mid]) == x: return mid # If x is greater, ignore left half elif int(arr[mid]) < x: l = mid + 1 ...
import os import csv election_csv_path = os.path.join("/Users/himadevulapalli/Documents/Tech/GTATL201908DATA3/02 - Homework/03-Python/Instructions/PyPoll/Resources", "election_data.csv") #file_to_output = os.path.join("./election_output.txt") # you might declare election results here and then assignt them within the...
# -*- coding: utf-8 -*- """ problem 87 weblink: description: The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way: 28 = 22 + 23 + 24 33 = 32 + 23 + 24 49 = 52 + 23 + 2...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ problem description: In the hexadecimal number system numbers are represented using 16 different digits: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F The hexadecimal number AF when written in the decimal number s...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ problem description: 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? weblink: https://projecteuler.net/problem=16 """ ...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ problem description: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the pro...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ problem description: The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: ...
# -*- coding: utf-8 -*- """ Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6. The numbe...
#sort these arrays & print out median from itertools import cycle def main(): shouldEnter= int(raw_input()) masterList=[] median=[] for i in range(0,shouldEnter): list=raw_input().split(" ") masterList.append(list) for i in masterList: numList=[] for x in i: ...
#################Pro Co 2009 Problems######################### ######################2.5####################### def main_Snupper(): sent= "we provide great gifts for every occasion" print sent.title() #####################5.2##################### def main_YaWho(): original= "stanford proco" check="p...
import numpy as np #Question 9: Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees. Centigrade values are stored into a NumPy array. F= np.array([0, 12, 45.21 ,34, 99.91]) print ("Value of Centigrade degrees: {}".format(F)) C = (5*(F-32))/9 print ("Value of Centigrade degrees: {}...
age = int(input("How old are you? ")) height= input(f"You are {age} old? Nice. How tall are you? ") weight = input("How much are you weight? ") print(f"So, you are {age} old, {height} tall and {weight} heavy.")
names = ['Richie','George','Gogdito','Sien','Lalo','Pepito','Gus','Xavo'] message = "Hi dear " print(message + names[0]) print(message + names[1]) print(message + names[2]) print(message + names[3]) print(message + names[4]) print(message + names[5]) print(message + names[-1])
from random import randint # 무작위로 정렬된 1 - 45 사이의 숫자 여섯개 뽑기 # 오름차순 리스트...이거 그건데 자료구조 # https://www.codeit.kr/assignments/140 def generate_numbers(): lotto = [] i = 0 while i < 6: select = randint(1, 45) while select in lotto: select = randint(1, 45) lotto.append(select) ...
from string import ascii_lowercase, ascii_uppercase import operator import nltk nltk.download("words", quiet=True) from nltk.corpus import words alphabet_lower = ascii_lowercase alphabet_upper = ascii_uppercase word_list = words.words() def encrypt(text_phrase: str, key: int) -> str: """[encrypts you phrase by ...
# Asynchronous TCP Server using core socket functions and "Select" import socket import select import string #Function to send message to client def send_data(sock, message): #Send message to client. #print("Connection is--",sock,"----Message is----", message) try: sock.send(message) except Co...
from random import randint # dictionary containing customized settings of each levels levels = { "1": { "name": "Easy", "start_message": ""f"What's the secret number to the treasure Chest", "min_num": 1, "max_num": 6, "guesses": 6 }, "2": { "name": "Medium", ...
def tokenize(sentence): for sym in ['.', ',', '?', ';', '\'', ':']: sentence = sentence.replace(sym, ' ' + sym) return sentence.split()
# Convert the ASCII input to hex representation in upper case. # # Example: "FOo123" -> "464F6F313233" def transform(n): newstring = '' n = list(n) for c in n: newstring += hex(ord(c))[2:].upper() return newstring
#Radhika PC #5/25/2016 #Homework2 numbers = [22,90,0,-10,3,22, 48] #display th enumber of elements in the list print(numbers) #display the 4th elements print("The 4th element is", numbers[3]) #Display the sum of the 2nd and 4th element of the list. print("The sum of 2nd and 4th element is", numbers[1] + numbers[3]) #Di...
#!/usr/bin/env python # coding: utf-8 import math def rotate(degre,posX,posY,largeur,hauteur): ''' Besoins de la fonction degre : angle en degré de la rotation souhaitée posX : Position initiale de x de la forme posy : Position initiale de y de la forme largeur : largeur de la forme hauteur : hauteur de la fo...
#!/usr/bin/env python """ The Retuner script serves as a convenient means of adjusting the pitch and/or speed of a given audio file. The script makes use of the pydub and librosa libraries/modules to either adjust the pitch of a file by semitonal intervals or both the pitch and the playback speed. The latter retains t...
import numpy as np count = 0 # счетчик попыток number = np.random.randint(1,101) # загадали число print ("Загадано число от 1 до 100") def score_game(game_core): '''Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число''' count_ls = [] np.random.seed(...
# -*- coding: utf-8 -*- """ Created on Tue Mar 30 14:04:28 2021 @author: Keshav """ def magic_square(n): magicSquare = [] #initializing magic square to all 0 for i in range(n): l = [] for j in range(n): l.append(0) magicSquare.append(l) i=n//2 j=n-...
import string flames = {'f':'friend','l':'love','a':'affirmative','m':'marriage','e':'enemy','s':'sister'} p1=list(input("Please Input Your Name : ").lower().replace(" ", "")) p2=list(input("Please Input Your Name : ").lower().replace(" ", "")) def remove_matching_letters(): for i in p1: for j in p2: ...
import timeit def linear_search(a,x): flag =0 for i in a : if (i==x): print("yes !! found my number at position",str(i)) flag =1 break if (flag==0): print("Number not found") def binary_search(a,x): first_pos = 0 last_pos = len(a)-1 flag...
def pattern(n) for i in range(0,n+1): for k in range(n,i-1): print("",end="") for j in range(0,i): print("*",end="") print("\r") n=5 pattern(n)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jul 26 21:44:30 2017 @author: saul Función para contar las palabras dentro de un texto. Pasar como parametro el vector que almacena el texto Nota: El texto no debe tener letras con acento. """ def contarPalabras(vector): l = 0 # longitud del vect...
import random a1 = input('Primeiro Aluno: ') a2 = input('Segundo Aluno: ') a3 = input('Terceiro Aluno: ') a4 = input('Quarto Aluno: ') list = [a1, a2, a3, a4] sort = random.choice(list) print('O aluno escolhido foi {}'.format(sort)) print('-'*20) from random import shuffle n1 = input('Primeiro Aluno: ') n2 = input('Seg...
# Testando dicionários '''pessoas = {'nome': 'Jabes', 'sexo': 'Masculino', 'idade': 18} print(f'Seu nome é: {pessoas["nome"]}\n' f'Você é do Sexo: {pessoas["sexo"]}\n' f'Sua Idade é de: {pessoas["idade"]} anos ') print(pessoas.values()) print(pessoas.keys()) print(pessoas.items()) del pessoas['sexo'] pessoa...
print('{:=^40}'.format(' LOJAS FANHES ')) preço = float(input('Preço das compras: R$')) print('''FORMAS DE PAGAMENTO [ 1 ] à vista dinheiro/cheque [ 2 ] à vista cartão [ 3 ] 2x no cartão [ 4 ] 3x ou mais no cartão''') opc = float(input('Qual é sua opção? ')) if opc == 1: total = preço - (preço * 10 / 100) elif opc ...
from time import sleep import moeda p = float(input('Digite o preço: R$')) print('-=' * 20) print('CALCULANDO...') print('-=' * 20) sleep(2) print(f'A metade de {p} é {moeda.metade(p)}') sleep(2) print(f'O dobro de {p} é {moeda.dobro(p)}') sleep(2) print(f'Aumentando em 10%, temos R${moeda.aumentar(p, 10)}') sleep(2) p...
'''for c in range(0, 5): print('oi') print('Fim')''' for c in range(0, 10): print(c) print('FIM') #i = int(input('Início: ')) #f = int(input('Fim: ')) #p = int(input('Passo: ')) #for c in range(i, f + 1, p): # print(c) #print('Adeus') '''s = 0 for c in range(0, 4): n = int(input('Digite um número: ')) ...
def solution(N): if N <= 9: result = N else: nine_count = ((N)// 9) second_num = str((N)%9) result = int(second_num + nine_count*'9') print(result) N = 7 solution(N)