text
stringlengths
5
121k
from datetime import date, timedelta import calendar year=int(input("Year:")) month=int(input("\nMonth:")) day=int(input("\nDay:")) try: date = date(year, month, day) except: print("\nPlease Enter a Valid Date\n") date += timedelta(days=1) print(date)
from typing import List import random class QuickSort: def __int__(self, array: List[list]): self.array = array def swap(self, a, b): temp = a a = b b = temp def sort(self, array): if len(array) < 2: return array base = array[0] low...
import unittest import tommy as challenges class TestChallenges(unittest.TestCase): def test_fizz(self): actual = list(challenges.fizz(10)) expected = [1, 2, 3, 4, 5, 6, 'Fizz', 8, 9, 10] self.assertEqual(actual, expected) def test_numbers(self): actual = list(ch...
from time import sleep import random if __name__ == "__main__": print ("*" * 32) print("Welcome to the Dice Roller!".center(32)) print ("*" * 32) print() sleep(1) def roll_dice(diceamnt, diceint): dicetotal = 0 for i in range(diceamnt): diceroll = rand...
gradeArray=[] gradeArray.append(5.5) gradeArray.append(3.2) gradeArray.append(-2.7) print(gradeArray) gradeArray[1]=9.9 print(gradeArray[0]) print(gradeArray)
x=float(input("Please enter First Number: ")) y=float(input("Please enter Second Number: ")) z=x+y print("x + y = ", z)
import math low=int(input()) high=int(input()) prime=[] for num in range(low,high+1): factor=0 for i in range(2,int(math.sqrt(num))+1): if num%i==0 : factor+=1 break if factor==0: prime.append(num) print("List of prime numbers is",prime)
s=input() l=s.split() new=[] for i in range(len(l)): new.append(l[i][::-1]) print(new) for i in range(len(new)): print(new[i],end=" ")
s1=input("Enter First String:") s2=input("Enter Second String:") output=s1+s2 print(output)
def count(s): l=sorted(list(set(s))) for i in range(len(l)): new=s.count(l[i]) print("{}-{}".format(l[i],new),end=" ") s=input() count(s)
import os import sys class Node: def __init__(self,key,depth): self.left = None self.right = None self.val = key self.depth = depth def addChildren(self,c): children = [] if c[0] != -1: self.left = Node(c[0],self.depth+1) children...
""" @author: ali_shehzad """ """ Finger exercise 11: Write a function isIn that accepts two strings as arguments and returns True if either string occurs anywhere in the other, and False otherwise. Hint: you might want to use the built-in str operation in. """ def isIn(str1, str2): if len(str1) > l...
class girl: 'Class for girl' name = '' attractiveness = 0 maintenance_budget = 0 intelligence = 0 relationship_status = '' boyfriend = '' happiness=0 type_= '' def __init__(self,name,attractiveness,maintenance_budget,intelligence,type_): 'Constructor fot initialising girl' self.name = name self.attracti...
import datetime try: year = int(input("Enter year ")) month = int(input("Enter Month ")) day = int(input("Enter day ")) dob = datetime.date(year,month,day) print(dob) days_in_year = 365.2425 dt = datetime.datetime.now().date() age = (dt - dob) / datetime.timedelta(days=365) print("approx age= ", age) ...
from tkinter import * from tkinter import messagebox win = Tk() win.title("Kamal Classes") win.geometry("300x500+200+100") win.configure(background='powder blue') def f1(): fb,mat ="","" if s1.get() == 1: fb = "Fantastic" if s1.get() == 2: fb = "Excellent" else: fb = "Superb" if n.get()==1: mat += "No...
for i in range(2): print("hello world") print\ ("""This is a long code, it spreads over multiple lines, because of the triple quotaions and brackets""") print('This is a String but if you are using numbers the data type is int and called integer') b = 100 print(b) print(2+2) print(2/2) print("The num...
""" This is a mapper program. It reads an input file which is in the format Username<space>DNAseq. The program considers the DNA seq as Key and Username as the Value. It sorts the records on the DNA seq and then stores each record in the output file in the format DNAseq<tab>Username """ inputFile = op...
class SymbolTable: def __init__(self): self.table = {} def add(self, name, cat, type, level, params=None): self.table[str(name)] = {} self.table[str(name)]["cat"] = cat self.table[str(name)]["type"] = type self.table[str(name)]["level"] = level self.table[str(...
import time import collections import numpy as np puzzle_input_string = "356261-846303" puzzle_input = (356261, 846303) time1 = time.time() count_passwords = 0 for number in range(*puzzle_input): number_string = str(number) digits = [digit for digit in number_string] ascending_order = sorted(digits) == ...
import queue as q from collections import namedtuple max_iterations=1000000 def search(start): """ Performs A* search starting with the initialized puzzle board. Returns a namedtuple 'Success' which contains namedtuple 'position' (includes: node, cost, depth, prev), 'max_depth' and 'nodes_expanded' ...
import sys for line in sys.stdin: line = line.strip() words = line.split() for word in words: day = words[1] tmax = words[5] tmin = words[6] print('%s\t%s\t%s' % (day, tmin, tmax))
''' In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements. The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function. The o...
from Card import Card import random class Deck(object): def __init__(self): cards_in_deck = 52 self.deck_of_cards = [] index = 0 while index < cards_in_deck: card_number = index % 13 suit_number = int(index / 13) new_card = Card() new_card.number = card_number new_card.suit = suit_number new...
import matplotlib.pyplot as plt from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout from keras.utils import np_utils from keras.layers.normalization import BatchNormalization (X_treinamento, y_treinamento), (X_teste, y_...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: n = head prev = None while n: n.next, prev, n = prev, n, n.next return prev if __name__ == '__mai...
people = {} print ('Welcome to base of person!') log = input('You want to add new person or watch base? (a/w):') if log == 'a': while True: lastname = input('Input lastname of new person:') firstname = input('Input firstname of new person:') gender = input('Input gender of new person:') ...
def get_class_name(obj) -> str: """ Get an arbitrary objects name. :param obj: any object :return: name of the class of the given object """ return obj.__class__.__name__ def issequence(obj) -> bool: """ Check if an object is a sequence / an iterable. .. note:: Using agai...
from sys import argv script, first, second, third = argv print ("The script is called:", script) print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third) a = input("Input a #:") b = input("Input another one:") result = a + b print(f"And {a} + {b} e...
import streamlit as st import pandas as pd import numpy as np import project_functions def main(): with open('opening.md', 'r') as f: opening = f.read() readme_text = st.markdown(opening) st.sidebar.title("What would you like to do?") app_mode = st.sidebar.selectbox("Choose what you'd like to do:", ['...
chars = ['a', 'b', 'c', 'd'] print(chars[1:3]) print(chars[-1:]) print(chars[:2]) new_chars = chars[:] print(new_chars)
import unittest from name_function import get_formatted_name class NameTestCase(unittest.TestCase): def test_first_last_name(self): formatted_name = get_formatted_name('Jacky', 'Wu') self.assertEqual(formatted_name, 'Jacky Wu') def test_first_last_middle_name(self): formatted_name = ...
chars = ["a", "b", "c"] chars.reverse() print(chars) chars.reverse() print(chars)
""" MuscleJoint class """ import numpy as np class MuscleJoint(object): """This class provides the interface between Muscles and Joints.""" def __init__(self, muscle, joint, parameters): """ Class initialization.""" self.muscle = muscle self.joint = joint self.theta_max = np....
"""This script introduces you to the useage of Imports in Python. One of the most powerful tool of any programming langauge is to be able to resuse code. Python allows this by setting up modules. One can import existing libraries using the import function.""" from __future__ import print_function import biolog bi...
""" 예제 위주로 작성 객체 속성과 클래스 속성 property의 고전적인 구문 """ class LineItem1: """ property를 사용한 예제 """ def __init__(self, description, weight, price): self.description = description self.weight = weight self.price = price def subtotal(self): return self.weight * self.pri...
class Foo: def __getitem__(self,pos): return range(0, 30, 10)[pos] f = Foo() for i in f: print(i) print(20 in f) print(15 in f) import collections Card = collections.namedtuple('Card',['rank','suit']) class FrenchDeck: ranks = [str(n) for n in range(2,11)]+list('JQKA') suits = 'spades diamonds ...
class LineItem1: def __init__(self, description, weight, price): self.description = description self.weight = weight self.price = price def subtotal(self): return self.weight * self.price class LineItem2: def __init__(self, description, weight, p...
class Foo: @property def bar(self): '''The bar attribute''' return self.__dict__['bar'] @bar.setter def bar(self, value): self.__dict__['bar'] = value def quantity(storage_name): def qty_getter(instance): return instance.__dict__[storage_name] def qty_setter...
""" 2018_10-30_Fluent_Python @Author Sanghong.Kim 오늘은 예제만 돌려 보았다. """ import time import os import sys import argparse import functools import copy def clock(func): @functools.wraps(func) def clocked(*args, **kwargs): t0 = time.time() result = func(*args, **kwargs) elapsed ...
''' __setitem__과 collections.UserDict에 대한 내용. + 클래스 상속 ''' import collections class DoppelDict(dict): def __setitem__(self, key, value): super().__setitem__(key, [value] * 2) class AnswerDict(dict): def __getitem__(self, key): return 42 class DoppelDict2(collections.UserDict): def __setitem__(self, key, ...
class DoppelDict(dict): def __setitem__(self, key, value): super().__setitem__(key,[value]*2) dd = DoppelDict(one=1) print(dd) dd['two'] = 2 print(dd) dd.update(three =3) print(dd) class AnswerDict(dict): def __getitem__(self, item): return 42 ad = AnswerDict(a='foo') print(ad['a']) d = {} d...
import math print([callable(obj) for obj in (abs, str, int, float, 13, 'str', math)]) import random class Lotto: def __init__(self, items): self._items = list(items) random.shuffle(self._items) def pick(self): self.numbers = [] for i in range(6): self.numbers.append(self._items.pop()) return self....
""" Created by Jingu Kang on 11/12/2018. Copyright © 2018 Jingu Kang. All rights reserved. DESCRIPTION: When to use Generate function? How to use more effieciently with itertools? """ class ArithmeticProgression: def __init__(self, begin, step, end=None): self....
class Bus: def __init__(self, passengers=None): if passengers is None: self.passengers = [] else: self.passengers = list(passengers) def pick(self, name): self.passengers.append(name) def drop(self, name): self.passengers.remove(name) ...
""" Created by Jingu Kang on 17/12/2018. Copyright © 2018 Jingu Kang. All rights reserved. DESCRIPTION: simple variation of example source using with and stdout.write """ import sys class LookingMinus: def __enter__(self): self.original_write = sys.stdout.write ...
''' 예제에 @property를 사용하여서 visualize 매소드를 추가함. ''' import datetime import math import numpy as np from matplotlib import pyplot as plt class Demo: @classmethod def klassmeth(*args): return args @staticmethod def statmeth(*args): return args print(Demo.klassmeth()) print(Demo.klassmeth('spam')) print(De...
""" trivial in python """ t = int(input()) for a0 in range(t): n = int(input()) n = str(2**n) print(sum([int(x) for x in n]))
def countUniqueWords(words): wordList = [] for word in words: wl = [w['word'] for w in wordList] if word not in wl: wordList.append({'word': word, 'count': 1}) else: wordMap = [w for w in wordList if w['word'] == word][0] wordMap['count'] += 1 return wordList
from tkinter import * gui = Tk() gui.title("Simple Calculator") gui.resizable(0, 0) gui.geometry("300x200") expression = "" def press(num): global expression expression+=str(num) equation.set(expression) def equalpress(): global expression total = str(eval(expression)) e...
""" 作者:陈志安 功能:计算出时间,是几年几天 """ from datetime import datetime def is_leap_year(year): """ 判断是否是闰年 """ is_leap = False if (year % 400 == 0) or (year % 4 == 0) and (year != 0): is_leap = True return is_leap def main(): """ 主函数 """ ...
""" 作者:陈志安 日期:19/3/21 功能:AQI计算 版本:v.1 """ import csv import json def process_json_file(filepath): """ 解码json文件 """ f = open(filepath, mode='r', encoding='utf-8') city_list = json.load(f) return city_list def main(): """ 主函数 """ filepath = input('请输入json文件名') city_list = process_json_fi...
""" 综合应用——石头剪刀布 """ import random while True: player = int(input("请输入您要出的拳 石头(1)/剪刀(2)/布(3):")) computer = random.randint(1, 3) print("玩家出的拳是 %d -- 电脑出的拳是 %d" % (player, computer)) if ((player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and ...
def all_subarrays(arr): n = len(arr) for i in range(0,n): for j in range(i,n): for k in range(i,j+1): print (arr[k], end = " ") print ("\n", end = "") n = int(input()) arr = [int(input()) for x in range(n)] all_subarrays(arr)
import requests import pandas as pd import numpy as np import json import os def address_reader(path='data/address_data_example.csv'): """ This function reads the address data and returns a dataframe of the addresses :param path: path to the data :return: """ address_csv = pd.read_csv(path, dt...
"""Own math module. Contained functions are: - ft_abs(n): return the absolute value of n. - ft_power(n, p): return n raised to power p - ft_sqrt(n): return the square root of n. Should be improved ! Contained objects are: - Complex(r, i): Represents a coplex number. """ def ft_abs(n): return -n if n < 0 else n ...
import csv import numpy as np import random from scipy import stats import gsea_functions as gf '''Program to calculate the normalized enrichment scores and pvalues according to the publication: http://software.broadinstitute.org/gsea/doc/subramanian_tamayo_gsea_pnas.pdf The program accepts 2 files, which user can s...
tuple1 = (1,2,3,4,5) stringTuple = ("one","two","tree") mixedTuple = ("one", tuple1, 3) itemTuple = ("apple", 2, 3.5) print(itemTuple) print("lenght",len(itemTuple)) print("min",min(tuple1)) print("max",max(tuple1)) print("index 2 ",itemTuple.index("apple")) grocList = ["eggs","milk","flour","butter"] print(grocList...
def addmenu(name_item, price_pound = 0, price_pence = 0): try: price_pound = int(price_pound) except ValueError: print("a number is required here") return try: price_pence = int(price_pence) except ValueError: print("a number is required here") return ...
lst=[1,4,5,2] def quickSort(lst,start,stop): if(start<stop): q=partition(lst,start,stop) quickSort(lst,start,q-1) quickSort(lst,q+1,stop) def partition(lst,start,stop): x=lst[stop] i=start-1 for j in range(start,stop-1): if lst[j]<=x: i+=1 ...
""" Hackerrank The Time in words Medium 25 Max Score Input Format The first line contains , the hours portion The second line contains , the minutes portion Constraints Output Format Print the time in words as described. Sample Input 0 5 47 Sample Output 0 thirteen minutes to s...
from typing import * from fizzbuzz import FizzBuzz import unittest class TestFizzBuzz(unittest.TestCase): def test_出力はstrである(self): self.assertEqual(str, type(FizzBuzz.single_line_answer(1))) def test_数値の1を渡したら文字列の1を返す(self): self.assertEqual("1", FizzBuzz.single_line_answer(1)) def te...
import turtle from bezier import * from common.types import * def draw(t: turtle.Turtle, scale: int, bezier_points: List[Line], steps: int = 20, closed: bool = False): t.penup() t.goto(bezier_points[0].p1.x * scale, bezier_points[0].p1.y * scale) t.pendown() points = bezier_interpolation(bezier...
""" prac 04 - Lists """ numbers = [3, 1, 4, 1, 5, 9, 2] numbers[0] numbers[-1] numbers[3] numbers[:-1] numbers[3:4] 5 in numbers 7 in numbers "3" in numbers numbers + [6, 5, 3] numbers[0] = "ten" numbers[-1] = 1 numbers[2:] 9 in numbers
import csv def read_csv(filename, types, *, errors='warn'): ''' Read the CSV with type conversion into a list of dictionary ''' if errors not in {'warn', 'silent', 'raise'}: raise ValueError("errors must be in one of 'warn', 'silent', 'raise'") records = [] with open(filename,'...
""" Problem2 (https://leetcode.com/problems/house-robber/) You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically co...
import random def num_vowels(s): vowels=0 for letter in s: if letter in [a,e,i,o,u]: vowels+=1 print(vowels)
import sys try: n = sys.argv[1] except IndexError: n = input("Enter something, yo! ") while type(n) != int: try: n = int(n) except ValueError: n = input("Enter something, yo! ") print("Fizz buzz counting up to " + str(n)) counter = 0 for counter in range(1,n+1): if counter % 3 =...
import pandas as pd import matplotlib.pyplot as plt def main(): Line="*"*60 excel='StudentData.xlsx' data=pd.read_excel(excel) print(Line) print("Size of the data is: ",data.shape) print("All data of excel sheet") print(Line) print(data) print(Line) print("F...
met=input("What is the meter resolution? Enter>>") meters=float(met) sec=meters*(1/30.87) deg=sec/3600 print("Approximate decimal degrees is", deg)
import statistics amostra = [] while True: n = int(input('Digite Valores de 0 a 10 varias vezes: ')) amostra += [n] if n == 0: break moda = statistics.mode(amostra) print('Moda', moda)
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 2: Which telephone number spent the ...
from collections import OrderedDict class LRU_cache(object): def __init__(self, capacity = 10): self.cache = OrderedDict() self.capacity = capacity def get(self, key): if key in self.cache.keys(): self.update_existing_order(key) return self.cach...
''' ============================================================================== File Name : pandas_demo.py Purpose : Introduce some basic pandas functionalities Creation Date : 14-02-2018 Last Modified : Wed 14 Feb 2018 01:00:08 PM EST Created By : Samuel M. Haugland ==============================================...
def main(): elements = {"hydrogen": 1, "helium": 2, "carbon": 6} print("print the value mapped to 'helium'",elements["helium"]) elements["lithium"] = 3 print("elements = ",elements) print("is there carbon = ", "carbon" in elements) print("get dilithum = ",elements.get("dilithium")) pri...
import random def game(): i=0 n=int(input('n=')) rand=random.randrange(1,n) while True: a=int(input('guess the num: ')) if a==rand: print('number was:',rand ,'\nYou guess correctly in ',i,'times') break; elif a>rand: print('guess again it ...
def main(): phone_balance = 10 bank_balance = 50 if phone_balance < 10: phone_balance += 10 bank_balance -= 10 print(phone_balance) print(bank_balance) number = 145 if number % 2 == 0: print("Number " + str(number) + " is even.") else: print("Number "...
students = [] for _ in range(int(input())): name = input() score = float(input()) students.append([name,score]) tmp1 = students[0][1] for i in range(1, len(students)): if tmp1 > students[i][1]: tmp1 = students[i][1] tmp4 = [["", 101.0]] print("asd",tmp4[0][1]) for i in r...
def zipdic(sentence,a,b,c,d,e): print(sentence['what'][a%2],sentence['who'][b%3], sentence['how'][c%2],sentence['do'][d%2], sentence['where'][e%3]) def main(): sentence=dict(zip(['what','who','how','do','where'],[ ['What what','Stray'], ...
import random Matrix = lambda r,c,k: [[ random.randrange(1,k) for x in range(c)] for y in range(r)] def main(): c=int(input('choose columns= ')) r=int(input('choose rows= ')) k=int(input('range of k= ')) print(Matrix(r, c, k)) main()
student = {'name':'Vani','rollno':101} if 'name' in student and 'marks' in student and 'rollno' in student: print('Hello I am {name}, My Rollno: {rollno}, My Marks:{marks}'.format(**student)) else: print('Missing Some keys') try: print('Hello I am {name}, My Rollno:...
''' Author: Padma Gundapaneni @padma-g Date: 7/28/21 Description: This script cleans up a csv file on county level precipitation data downloaded from the CDC. URL: https://data.cdc.gov/browse?category=Environmental+Health+%26+Toxicology @input_file filepath to the original csv that needs to be cleaned @o...
class Manga(object): def __init__(self, name, chapter, website): self.name = name self.chapter = int(chapter) self.website = website def __str__(self): return str(self.name + ", " + str(self.chapter) + ", " + self.website + "\n") @staticmethod def read_from_file(line): ...
num = int(input("Enter a number: ")) def game(): if num % 3 == 0 and num % 5 == 0: print("Fizz Buzz") elif num % 3 == 0: print(f"Fizz") elif num % 5 == 0: print(f"Buzz") else: print("Invalid number, sorry!") game()
from matplotlib import pyplot as plt import numpy as np def printHistogram(bmp): """ Print the histogram of colors of the bmp file using Matplotlib Parameters ---------- bmp: BMP """ flattenedImage = bmp.imageData[:, :, :].flatten() blueFlattened = bmp.imageData[:, :, 0...
from utils import helpers as hp import numpy as np def scale(image, nR, nC): nR0 = len(image) nC0 = len(image[0]) return [ [ image[int(nR0 * r / nR)][int(nC0 * c / nC)] for c in range(nC) ] for r in range(nR) ] def imageScale(bmp, nR, nC): """ Scaling/Shrikin...
class Solution: def isSymmetric(self, root: TreeNode) -> bool: if root == None: return True return self.recur(root.left, root.right) def recur(self, leftP1: TreeNode, rightP2: TreeNode) -> bool : if ...
import cv2 import numpy as np img = cv2.imread("org.jpg") gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) dst3 = cv2.GaussianBlur(gray, ksize=(3,3), sigmaX=1.3) cv2.imshow("GaussianBlue", dst3) cv2.imwrite("output3.jpg", dst3) cv2.waitKey(0) cv2.destroyAllWindows()
print ("Dit is het FIZZBUZZ spel!") end = input("""\nWe gaan even na of een getal deelbaar is door 3 OF 5 .\nOf door 3 EN 5.\n Geef een geheel getal in tussen 1 en 100: """) try: end = int(end) for num in range(1, end+1): if num % 3 == 0 and num % 5 == 0: print ("FIZZBUZZ-3-5") ...
Stringy = ''' Suyash: Why are you wearing your pajamas? Atul: [chuckles] These aren't pajamas! It's a warm-up suit. Suyash: What are you warming up for Bro..!!? Atul: Stuff. Suyash: What sort of stuff? Atul: Super-cool stuff you wouldn't understand. Suyash: Like sleeping? Atul: THEY ARE NOT PAJAMAS! ''' print(Stringy) ...
n = int(input("Enter the length of the sequence: ")) number_1 = 1 number_2 = 2 number_3 = 3 next_number = 0 n=n-2 print(number_1) print(number_2) print(number_3) for i in range(1,n): next_number = number_1+number_2+number_3 print (next_number) number_1 = number_2 number_2 = number_3 number...
x = 1 print("The program will start counting up from 0 and finish at 9.") print("You will recieve a nice message after the program has ended.") response=(input("Are you ready to proceed? ")) for x in range(0,10): print ("total= ",x) print("Program has ended folks! Take care and Stay Frosty - Vinnie")
from sys import argv script, filename = argv txt= open(filename) print(f"Here's your file {filename}:") print ( txt.read()) print("Type the filename again:") file_again = input ( " > ") txt_again = open ( file_again) print (txt_again.read())
number_usuary = [] number_of_usuary = "" while len(number_usuary) < 6: while not number_of_usuary.isdigit(): number_of_usuary = input("Dime un numero : ") number_usuary.append(int(number_of_usuary)) number_of_usuary = "" print("Numero añadido!!") lower = number_usuary[0] for number in number_...
number_usuary = [] number_of_usuary = "" while len(number_usuary) < 10: while not number_of_usuary.isdigit(): number_of_usuary = input("Dime un numero : ") number_usuary.append(int(number_of_usuary)) number_of_usuary = "" print("Numero añadido!!") higher = number_usuary[0] for number in numbe...
day = input("Ingrese el dia de la semana : ").title() if day == "Lunes": print("Con la profesora Bety") elif day == "Viernes": print("Hoy la Motok") elif day == "Sabado": print("A salir de peda") elif day == "Domingo": print("Sale asaduki") elif day == "Martes" or day == "Miercoles" or day == "Jueves":...
radio = float(input("Ingrese la radio : ")) height = float(input("ingrese la altura : ")) volumen = float(radio * radio * 3.14 * height) if (volumen >300): print("Su volumen es mayor a 300 ") else: print("El volumen es menor a 300")
import random def age(): mayor, menor = 0, 0 for i in range(0, 50): edad = random.randrange(1, 75) print("", edad ,end="") if edad > 21: mayor += 1 elif edad < 21: menor += 1 print("\nMayores a 21 : ", end="") for i in range(mayor): print("...
import PySimpleGUI as sg def calcularConversion(magnitud, u1, u2, entrada): if magnitud == "LONGITUD": return entrada * 0.914 if u1 == "Metros" and u2 == "Yardas" else entrada / 0.914 elif magnitud == "MASA": return entrada * 453.6 if u1 == "Libras" and u2 == "Gramos" else entrada / 46...
import pandas as pd import random from configuration import MAN_NUM,WOMAN_NUM def create_sample(): man_num = MAN_NUM women_num = WOMAN_NUM print('==============================生成样本数据==============================') man = pd.DataFrame( [['w'+str(i) for i in random.sample(range(1,women_num+1),wom...
''' Method1: Brute Force Method2: Boyer-Moore Algorithm Author: Xinting Date : 2019-11-04 ''' class Solution: def majorityElement(self, nums: List[int]) -> List[int]: res = [] for num1 in nums: if num1 not in res and sum(1 for num2 in nums if num2 == num1) > len(...