text
stringlengths
37
1.41M
class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: if not matrix or not matrix[0]: return 0 self.res = 0 memo = {} def longestFromStart(matrix, i, j): # print("position:", (i, j), "=", matrix[i][j]) if (i, j) in memo...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if not head or not head.next: ...
class Monoqueue: """ Implements a queue with the monotonic decreasing invariant. Nameley: for all i,k i < k: queue[i] >= queue[k] This invariant is enforced by truncating the tail of the queue when inserting a new element. For example, If the new element is strictly greater than all existi...
# Practice: Writing While Loops # #a x = 1 while x < 6: print(x) x += 1 print() #b x = 2 while x <12: print(x) x += 3 print() #c x = -10 while x < 1: print(x, end=" ") x += 2 print() print() #d x = 0 while x < 4: print(4 * "*") x += 1 print() for x in range(4): print("****") print() string...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( "--your-name", type=str, help="Test param", required=True ) args = parser.parse_args() name = args.your_name pri...
#My first Project #Returns the username name = input("Give me your name: ") print("Your Name is " + name) #The Program returns a information "Your Name is + name" age = int(input("Please give me your age / how old are you?: ")) print("You are " + str(age) + " years old") #Returns the date after 100 years year...
# With this concept of default parameters in mind, the goal of this assignment is to write a single function, randInt() that takes up to 2 arguments. # If no arguments are provided, the function should return a random integer between 0 and 100. # If only a max number is provided, the function should return a random...
from binascii import b2a_hex, a2b_hex from Crypto.Cipher import DES import sys #key = '12345678' while 1: key = raw_input('Please input the key(8 bytes): ') if key == '12345678': file = open('history', 'r') try: text = file.read() finally: file.close() ...
from typing import Tuple from .base import ConfigBase """参考https://pytorch.org/docs/stable/optim.html""" class OptimizerConfig(ConfigBase): # learning rate for embedding layer embedding_lr: float = 1e-3 # learning rate for other layer lr: float = 1e-3 # embedding层在前static_epoch将不会进行训练 # 在st...
"""各种模型的设置""" from typing import Union, Optional, Dict from .base import ConfigBase class MLModelConfig(ConfigBase): pass class LogisticRegressionConfig(MLModelConfig): """参考:https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html""" # penalty{‘l1’, ‘l2’, ‘elastic...
num = 0 def adding(a): a += 1 return a def using_global(): global num num += 1 print(adding(num)) print(num) using_global() print(num)
# count_0 = 0 # count_1 = 0 # def fibonacci(N): # if(N==0): # #print("0") # global count_0 # count_0 += 1 # return 0 # elif(N==1): # #print("1") # global count_1 # count_1 += 1 # return 1 # else: # return(fibonacci(N-1)+ fibonacci(N-2...
""" Fetches the API response from the interview scheduler application """ import os,sys,time sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from conf import fetch_api_interviewscheduler_conf as conf import requests import urllib import json from utils.results import Results url="http...
import GridFunctions import heapq from queue import Queue, LifoQueue as stack class Node: def __init__(self, value, par, search_type): self.value = value self.parent = par self.g = 0 # path cost self.h = 0 # heuristic cost self.f = self.g + self.h # A* self.priori...
import math def unoReverse(x): return x[::-1] def findMaxIndex(x): return x.index(max(x)) def odds(x): return [odd for odd in x if odd % 2 != 0] def euclidianDistance(coor1, coor2): return math.sqrt(sum([(x-y)**2 for x, y in zip(coor1, coor2)])) def fileLineFinder(file): lines = [] with op...
from tkinter import * from quiz_brain import QuizBrain THEME_COLOR = "#375362" class QuizInterface: def __init__(self, quiz_brain: QuizBrain): self.quiz = quiz_brain self.window = Tk() self.window.title("Quiz") self.window.config(padx=20, pady=20, bg=THEME_COLOR) self.tex...
""" Tests for trends in time series data Nonparametric Trend Tests ------------------------- Nonparametric tests should be used where one or more of the following conditions exist in the data. 1. The data are nonnormal. 2. There are missing values in the data. 3. The data are censored. Censored data are...
def apply_tax(price, tax): return price + price * tax / 100 def apply_discount(price, discount): return price - price * discount / 100 def basket(basket, tax=15): subtotal = 0 for price, discount in basket.items(): subtotal += apply_discount(price, discount) total = apply_tax(subtotal, ta...
# 문자 출력 print('Hello, Python !!') print('반갑습니다. \n파이썬세계로 온것을 환영합니다.') # '\n' 은 줄바꿈 print("문자는 반드시 인용부호(' ' 혹은 \" \")로 감싸야 합니다.") # '\'는 명령 문자앞에 붙이면 그 문자를 그대로 문자로 출력 # 숫자 출력 print(100) print(150 + 200) print(150 - 200) # 기본연산 x = 50 y = 4. print("x = ", x) print("y = ", y) print("x + y = ", x+y) print("x * y = ", x*y...
from math import sqrt import sys def Input(line): is_error = True while is_error: is_error = False try: coeff = int(line) except ValueError: try: coeff = float(line) except ValueError: is_error = True li...
# -*- coding: utf-8 -*- # "\"用来转义,输入特殊符号 print('I\'m OK.') print('I\'m learning \nPython.') print('\\\n\\') # '''...'''表示多行内容 print('''line1 line2 line3''') print(r'''line1 line2 line3''') # 变量 a = 1 t_007 = 't007' Answer = True # 等号=是赋值语句,可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可## 以是不同类型的变量 a = 111 # a是整数 print(a) a = 'a...
# -*- coding: utf-8 -*- # 排序算法 # 排序的核心是s比较两个元素的大小 # 如果是数字,我们可以直接比较,但如果是字符串或者两个dict,直接比较数学上的大小没有意义,因此比较过程必须通过函数抽象出来。 # Python内置的sorted()函数就可以对list进行排序(升序) sortedList = sorted([28, 1, 39, -9, 0]) print(sortedList) # sorted()函数是一个高阶函数,它还可以接收一个key函数来自定义排序,例如按绝对值大小排序: absSorted = sorted([39, 9, -12, 23, 29, -76, 0, 12], k...
# A snake must know how hiss ... or sometimes rattle # Normally we can just use echo to print out message during execution # However: # It is mandatory to *hiss* when there is error # also, *rattle* is needed when a snake meet something ... at the beginning # or at the end of an execution. import click def...
# Temperature/Humidity analysis program to read in data from a spreadsheet # Plot the data in a static HTML output file # Author: Lucretia Field # Date: July 2018 import pandas as pd import matplotlib as plt import numpy as np from datetime import datetime, timedelta as dt from pathlib import Path from bokeh...
class Node(object): def __init__(self, data): self.data = data self.height = 0 self.leftChild = None self.rightChild = None class AVLTree(object): traversedData = [] def __init__(self): self.root = None def calculate_height(self, node): if not node: ...
#Program to calculate the volume of the sphere with radius 5 cm. Solution: π = 3.14 r= 5 V= (4/3)*π* r**3 print('The volume of the sphere with radius 5 is: ',V)
Q. Write a function called cumulative_sum that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. Solution: def cummulative_sum(n): new_list = [] sum_1ist = 0 for each in n: sum_1is...
def marriage_point_calculator(): a = str(input("Have you seen the joker or not? (Y/N)")) if a.lower()=="y": x = int(input("Your Maal: ")) y = int(input("Total Maal: ")) z = int(input("Total number of players:")) if x * z > y: return "You Win:", (x * z) - (y...
Q. Program to sort a dictionary by key. Solution: info = {'Name':'Nishesh Thakuri', 'Address':'Gothatar', 'Course name':'Python',} for key in sorted(info): print("%s: %s" % (key, info[key]))
Q. Python script to sort (ascending and descending) a dictionary by value Solution: import operator d = {8: 9, 3: 4, 4: 3, 2: 1, 1: 0} print('Original dictionary :',d) sort_d = sorted(d.items(), key=operator.itemgetter(0)) print('Dictionary in ascending order by value : ',sort_d) sort_d = sorted(d.items(),...
Q.Program to calculate a dog's age in dog's years. Note: For the first two years, a dog year is equal to 10.5 human years. After that, each dog year equals 4 human years. Solution: human_age = int(input("Input a dog's age in human years: ")) if human_age < 0: print("Age must be positive number.") e...
Q. Program to check whether an element exists within a tuple. Solution: tup = ("a", "e", "i", "o", "u") print("o" in tup) print(4 in tup)
Q.Program to add an item in a tuple. Solution: tup = (4, 6, 2, 8, 3, 1) print(tup) tup = tup + (9,) print(tup) tup = tup[:5] + (15, 20, 25) + tup[:5] print(tup)
Q.Function to find the Max of three numbers. Solution: def max_of_two( x, y ): if x > y: return x return y def max_of_three( x, y, z ): return max_of_two( x, max_of_two( y, z ) ) print(max_of_three(12, 10, 9))
#IMPORTS import matplotlib.pyplot as plt import numpy as np #FIRST EXAMPLE #Days of the week: days = [1, 2, 3, 4, 5, 6,7] # Your Money: money_spent = [1000, 1200, 1500, 1080, 1400, 1650, 1350] # Your Friend's Money: money_spent_2 = [900, 1500, 1200, 1050, 950, 1250, 1000] # Create figure: fig = plt.figure(figsize=(15...
import queue import collections #Queue O(1) insert, O(1) remove, FIFO. data = queue.Queue() data.put(3) data.get() data.qsize() data.empty() #stack, O(1) insert, O(1) remove, LILO. Can just use list. #PriorityQueue, O(1) find min/max, O(logn) insert, delete/extract min/max, lookup/delete O(n) #lowes...
""" Generate collections of scattered points in Cartesian coordinates. """ import numpy as np def scatter_circular(size, R1=3, R2=None, angle=0, reset_random=True): """ Generate a collection of random points distributed in a circle or elipse. Parameters ---------- size : int Number of poin...
word = input() for i in word: print("'{}'".format(i))
nums = [0,1,2] a = 0 b = 1 c = 2 ordersList = [] while len(ordersList) < 1: for a in nums: for b in nums: if b == a: continue for c in nums: if c == a or c == b: continue #print(str(a) + str(b) + str(c)) ...
day = 0 month = 1 year = 1901 dayIndex = 1 days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] sundays = 0 while year < 2001: day += 1 dayIndex += 1 if dayIndex > 6: dayIndex = 0 if month == 1: if day > 31: day = 1 month += 1 ...
import unittest from lib.checkers import input_type_checker, card_checker, convert_case, is_list_unique class TestCheckers(unittest.TestCase): """ Unit tests for checker methods """ def test_valid_input_true(self): """ Checks if the input is a list of len > 2 for board and len == 2 for...
#!/usr/bin/python3 ''' This program defines functions that can be used to collect data on a movie from a given title and date. The information is collected from imdb and also provides functions to retrieve the rotten tomato score and imdb score ''' from urllib.request import Request, urlopen import urllib from...
import copy # The algorithms work by swapping the values of the blocks with the empty areas to move the block # For example, when the "red" function is called with the direction set to 'down', it swaps the top 2 values (4, 4) # with the two zeros below it # Controls the movement of the red block def red(direction, po...
# This program converts Fahrenheit to Calsius fahr_temp = float(input("Fahrenheit temperature: ")) celc_temp = (fahr_temp - 32.0) * ( 5.0 / 9.0) print("Celsius temperature: ", celc_temp)
import sys from print import printErr, help def checkArgs(args): if (len(args) != 3): if(len(args) == 1 and args[0] == "-h"): help() else: printErr("Not enough arguments. Check ./209poll -h for more informations.") else: try: args[0] = int(args[0]) ...
import sys def help(): print("USAGE\n ./202unsold a b\n") print("DESCRIPTION") print("\t a\tconstant computed from the past results") print("\t b\tconstant computed from the past results") def checkPiece(): if(len(sys.argv)!= 3): if (len(sys.argv) == 2 and sys.argv[1] == "-h"):...
from math import * def printResult(combinaison, value, res): print("chances to get a " + value + " " + combinaison + ": %0.2f%%" % (res)) def binomiale(a, b): res = (factorial(a) / (factorial(b) * factorial(a-b))) * pow(1/6, b) * pow(5/6, a-b) return (res) def calcProba(list, c, nb): res = 0 tim...
import sys from combinaisons import launchGame def help(): print("USAGE\n ./201yams d1 d2 d3 d4 d5 c\n") print("DESCRIPTION") print("\t d1\t value of the first die (0 if not thrown)") print("\t d2\t value of the second die (0 if not thrown)") print("\t d3\t value of the third die (0 if...
def n_queen(k): global count for i in range(k - 1): # 判斷是否可放置皇后的條件 judge = queen[i] - queen[k - 1] if judge == 0 or abs(k - 1 - i) == abs(judge): return if k == n: print(queen) # 輸出皇后放置序列 count += 1 # 解的個數 return for i in range(n): # 放置皇后 ...
""" FACTORY: Problem: Uncertainties in types of bjects decisions to be made at runtime regarding what classes to use """ class Dog: """ A simple Dog Class""" def __init__(self, name): self.name = name def speak(self): return 'woof!' class Cat: """ A simple Dog Class""" def __init__(self, name): ...
# input number as string print ("Please input a number:") x = input() print("Your input:", x) # convert into integer xint = int(x) print("as integer:", xint) # add calculation xsquare = xint * xint print("and squared:", xsquare)
# tax rate 18% # input brutto salary print("please input your brutto salary:") brutto = input() brutto = int(brutto) # calc individual netto & tax with high income statements for higher tax classes if brutto <= 2500: netto = brutto * 0.82 tax = brutto * 0.18 elif brutto <= 4000: netto = brutto * 0.7...
# interupt loop with break for i in 12, -4, 20, 7: if i*i > 200: break print("Number:", i, "square:", i*i) print("end")
#### rng import random random.seed() #### define calcualtion task def task(): a = random.randint(1,100) b = random.randint(1,100) asw = a+b print("The task:", a, "+", b) return asw ### define comment function def comment(ipt, asw): if ipt == asw: print(ipt, "is correct, you Mathe...
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 1: Data Collection df = pd.read_csv("creditcard.csv") print("Data read from file") # 2: Feature Engineering from sklearn.preprocessing import StandardScaler df["normAmount"] = StandardScaler().fit_transform(np.array(df["A...
# -*- coding: latin-1 -*- from connectfourboard import ConnectFourBoard import unittest class BoardTests(unittest.TestCase): """Test the ConnectFourBoard class""" def setUp(self): """Instantiate a ConnectFourBoard for testing""" self.board = ConnectFourBoard() def playmoves(self, moves): """For each move in...
import pandas as pd import numpy as np #Importing DataSet dataset = pd.read_csv("DataSetnanda.csv") X=dataset.iloc[:,1:-1].values y=dataset.iloc[:,-1].values #LabelEncoder and OneHotEncoder from sklearn.preprocessing import LabelEncoder,OneHotEncoder from sklearn.externals import joblib labelenco...
from package import Package class HashTable: # This hash table is of the chaining variety # which requires all buckets to be lists def __init__(self, initial_capacity=10): # Initialization involves creating empty buckets # Buckets are initialized as empty lists self.table = [] ...
import math def is_prime(n): if n < 2: return False elif n == 2: return True else: for i in range(2, int(math.sqrt(n)+1)): if n % i == 0: return False break return True def twin_prime(n): l = 10 ** (n-1) u = 10 ** n twins = [] for i in range(l, u-2): if is_prime(i) and is_prime(i+2): t...
""" Datetime utils. """ from datetime import datetime DT_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" def datetime_to_str(datetime): """ Serialize datetime provided as simplified ISO 8601 (without timezone) string :type datetime: datetime :param datetime: datetime object to convert to string :return: ser...
from random import shuffle import copy class Sudoku_generator(): def generate_solution(self, grid): """generates a full solution with backtracking""" number_list = [1,2,3,4,5,6,7,8,9] for i in range(0,81): row=i//9 col=i%9 #find next empty cell ...
from math import sqare print("quadratic function :(a*x^2)+b*x+c") a=float(input("a:")) a=float(input("a:")) b=float(input("b:")) c=float(input("c:")) r=b^2-4*a*c if(r>0): num_roots=2 x1=(((-b)+sqrt(r))/(2*a)) x2=(((-b)-sqrt(r))/(2*a)) print("there are 2 roots:"%fand%f %(x1,x2) elif(r==0): num_roots=1 x=(-b)/2*a...
__author__ = 'Lexie Infantino' import random import string def main(*args): #for counting iterations, not important iteration = 0 str = 'Hello, World' # gen string alpha/numeric/puntuation/whitespace ranStr = ''.join([random.choice(string.ascii_letters + string.digits + string.punctuation+ string.w...
class User: #User:(string, string) def __init__ (self, name, email): self.name = name self.email = email self.friends = [] #void -> string def getName (self): return self.name #void -> string def getEmail(self): return self.email #void -> list of Us...
# !/usr/bin/env python # encoding: utf-8 """ https://leetcode-cn.com/problems/min-stack/ """ class MinStack: def __init__(self): """ initialize your data structure here. """ self.data = [] self.min_stack = [math.inf] def push(self, x: int) -> None: self.data.a...
# !/usr/bin/env python # encoding: utf-8 """ https://leetcode-cn.com/problems/merge-two-sorted-lists/ """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2:...
# !/usr/bin/env python # encoding: utf-8 """ https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/ """ class Solution: def reverseList(self, head: ListNode) -> ListNode: prev, curr = None, head while curr: temp = curr.next curr.next = prev prev = curr curr = temp ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 16 12:40:15 2018 @author: adanayi """ """ Note: This is only a test sample function. the structure must be followed. """ import time def f(FER): print("Hey! I am a function!") print("You have called me with this args: {}".format(FER['x'])...
import sqlite3 import csv sql_insert_stage = """ INSERT INTO stage (name, id) VALUES (?, ?); """ sql_insert_takeover = """ INSERT INTO takeover (name_key, name) VALUES (?, ?); """ sql_insert_artist = """ INSERT or IGNORE INTO artist (name, name_key, takeover_name_key) VALUES (?, ?, ?); """ sql_insert...
# -*- coding: utf-8 -*- from textblob import Word from spacy.lemmatizer import Lemmatizer from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES def lemmatize_word(word): """ Assign the base form of words Input: word (plural, capital letters) return: word (singular, lower letters) """ p...
# funtions # create a function def sayHello(name = 'stephen'): print('hello', name) sayHello('john') # return a value def getSum(num1, num2): total = num1 + num2 return total numSum = getSum(1, 2) print(numSum) def addOneToNum(num): num = num + 1 print('value inside function:', num) return...
# single line comment #print sub strings print("Hello"[1:4]) # print numbers print(6) # Print on same line print(1,2,3,"hello") # new line print('line1\nline2\nline3') # raw text print(r'c:\\somewhere')
import os class Node (object): def __init__ (self, data): self.data = data self.lchild = None self.rchild = None class Tree (object): def __init__ (self): self.root = None # insert data into the tree def insert (self, data): new_node = Node (data) if (se...
import os # list of operators (tree parents) operators = ['+','-','*','/','//','%','**'] class Stack (object): def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): return self.stack.pop() def peek(self): return self.stack[-1] ...
import os class Node(object): def __init__ (self, data = None): self.data = data self.rchild = None self.lchild = None class Tree (object): # the init() function creates the binary search tree with the # encryption string. If the encryption string contains any # character other...
def tower_of_hanoi(number, source, aux_1, aux_2, destiny): if (number == 0): return 0 if (number == 1): print("Deslocando disco", number, "de", source, "para", destiny) return 0 tower_of_hanoi(number - 2, source, aux_2, destiny, aux_1) print("deslocando disco", number-1, "de", source, "para", aux_2) ...
# Problem: https://leetcode.com/problems/validate-binary-search-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 from typing import Optional class Solution: def isValidBST(...
import sys from typing import List # Problem: https://leetcode.com/problems/coin-change/ class Solution: def coinChange(self, coins: List[int], amount: int) -> int: memo = {} def minCoinChange(currAmount): shorted = None if currAmount == 0: return [] ...
import unittest from leetcode.letter_combinations_of_phone_num_17.letter_combinations_of_phone_num import Solution class TestLetterCombinationsOfPhoneNumber(unittest.TestCase): def test_letter_combinations_of_phone_num(self): self.assertListEqual(["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"], ...
# Problem: https://leetcode.com/problems/unique-paths/ # Solution memoization: https://www.youtube.com/watch?v=oBt53YbR9Kk&t=2320s # Solution tabulation: https://youtu.be/oBt53YbR9Kk?t=12137 class Solution: def uniquePaths(self, m: int, n: int) -> int: return self.with_dynamic_programming(m, n) def un...
import sys import subsets class Solution: """ @param S: A set of numbers. @return: A list of lists. All valid subsets. """ def subsetsWithDup(self, S): # write your code here s = subsets.Solution() xs = s.subsets(S) unique = [] for i in range(0, len(xs)): ...
import sys def sum_with_no_arith(a, b): """ sum two 32 bit numbers without using + return a + b """ carry = 0 bit_sum = 0 for i in range(0,32): a_bit = a >> i a_bit = a_bit & 0b1 b_bit = b >> i b_bit = b_bit & 0b1 if a_bit and b_bit: if carry: #one and carry ...
import bs import sys import unittest class Solution: """ @param matrix, a list of lists of integers @param target, an integer @return a boolean, indicate whether matrix contains target """ def searchMatrix(self, matrix, target): # write your code here bso = bs.Solution() ...
""" Definition of TreeNode: """ class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: def recurseDFS(self, node): if node is None: return "#" else: return str(node.val) + "," + self.recurseDFS(node.left)...
class User(): def __init__(self,first_name , last_name): self.first_name = first_name self.last_name = last_name self.login_attempts = 0 def describe_user(self): print("User: "+ self.first_name.titile() + self.last_name.title()) def greet_user(self): full_name = se...
from time import * def sumsquare(n): """Calculate the sum of the squares of 1~n.""" sq = 0 for i in range(n): sq += (i+1) **2 return sq # begin_time = time() # for i in range(1000000): # print(sumsquare(12)) # end_time = time() # run_time = end_time - begin_time # print(run_time) squares =...
print("Enter marks in DATA STRUCTURES, COMPUTER NETWORKS, DIGITAL ELECTRONICS, MICROPROCESSOR, OPERATING SYSTEM respectively (out of 50 each) : ") a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) percentage = ((a+b+c+d+e)/250)*100 if a > 50 or b > 50 or c > 50 or d > 50 or e > 50:...
a=list(input()) if a[0]=='-': print('Negative') else: print('Positive')
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, left, right): if left <= right: midpoint = (right + left) //2 if arr[midpoint] == target: return midpoint elif arr[midpoint] > target: return binary_search(arr, target, left...
def sumar(num1, num2): resultado = num1 + num2 return resultado def restar(num1, num2): resultado = num1-num2 return resultado def multiplicar(num1, num2): resultado = num1 * num2 return resultado def dividir(num1, num2): resultado = num1 / num2 return resultado
miCadena = "EsTa Cadema EsTa AlGo RaRa" miLista = miCadena.split(" ") for palabra in miLista: palabra = palabra.upper() print("analizando la palabra:",palabra) print("\tLa palabra tiene"+ str(len(palabra))+ "caracteres de largo") if len(palabra)%2==0: print("\tLa cantidad de letras es un numer...
#conversiones.py # miercoles 28 de febrero del 2018 #cristopher jose rodolfo barrios solis #ejercicio de funciones #variables de la ecuacion a = 9/5 e = 5/9 c = 32 menu = input("que desea hacer?\n\n" "1. convertir de grados farenheit a centigrados\n" "2. convertir de grados centigrados a fare...
a = (1, 2, 3, 2, "哈哈哈", "嘻嘻嘻", True, False) print(a) # 二维元组 b = (a, "嘟嘟", "噜噜") # 取哈哈哈 print(b[0][2]) # 取3的下标 print(a.index(3)) # 取2的个数 print(a.count(2)) # 切片 print(a[0:4]) # 左闭右开 print(a[4:6]) print(a[6:8])
""" De una lista de N cantidad de estaturas de personas se desea saber lo siguiente 1) El promedio 2) El punto medio 3) Cuantos son menores a 1.70 4) Cuantos son mayores a 1.70 """ def check_number_height(number, min_number, max_number, text_error): list_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]...
print("") usu_sent = input("Ingrese una oración: ") print("") list_a = ["A", "a"] mod_sent = usu_sent.replace("A", "VACA") mod_sent = mod_sent.replace("a", "VACA") print(mod_sent)
import datetime print("") print("Ingrese una fecha pasada.") year = int(input("Año: ")) month = int(input("Mes: ")) day = int(input("Día: ")) usu_date = datetime.datetime(year=year, month=month, day=day) now_date = datetime.datetime.now() past = now_date - usu_date print("") print("Han pasado {} horas desde ese día...
def correct(list): new_list = [] for item in list: reset = 0 new_item = "" for letter in item: if reset != 0: letter = letter.lower() new_item += letter reset += 1 if letter == " ": reset = 0 ...
import getpass number_2 = 0 print("") number_1 = getpass.getpass(input("Ingrese un número para adivinar: ")) print("") print("") while number_1 != number_2: number_2 = input("¡Ingrese un número para ganar su premio!: ") if number_1 != number_2: print("¡Has perdido") print("") print("") print(...
"""CSC110 Fall 2020 Final Project, Main Description =============================== This module is the graphical user interface that allows the user to access all the components of our project. To display a map, the interface prompts the user to enter a valid year, which creates three maps. To display a graph, t...
#file 006.py def F(n): if(n==1 or n==2): return 1 else: return (F(n-1) + F(n-2)) n = int(input("input the month:")) total = F(n); print("total rabbit number is ", total)