text
stringlengths
37
1.41M
def show_big(somenumbers): finallist = [] for i in range(1, len(somenumbers)): if somenumbers[i] > somenumbers[i - 1]: finallist.append(somenumbers[i]) return finallist original_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55] print(show_big(original_list)) ### Alternative solu...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as parameter. # def diagonalDifference(ar): # Write your code here pri = 0 sec = 0 ...
import pygame from button2 import * # initialize screen pygame.init() clock = pygame.time.Clock() # create display screen = pygame.display.set_mode((878, 878)) # title and icon pygame.display.set_caption("Snake!") icon = pygame.image.load('snake.png') pygame.display.set_icon(icon) # initialize board ...
test_cases = int(input()) for i in range(0, test_cases): number_of_shots = int(input()) movements = [] hits = 0 shots = input() heights = shots.split() moves = input() for movement in moves: movements.append(movement) index = 0 for k in range(0, number_of_shots): ...
""" Let's create a to do list. I know, thrilling. Ask the user for 5 items to put into their to do list. Once the user has provided 5 items, display the list back to the user. """ print "Greetings Busy Bee! Let's get to work making that TO DO list!" my_to_dos = [] list_len = 5 # HINT: You can see how many items are...
def stars(arr): for x in arr: print "*" * x nums = [6,2,5,7,9] stars(nums) print "That was part 1, starting part 2" def stars2(arr): for x in arr: if isinstance(x, int): print "*" * x elif isinstance(x, str): length = len(x) letter = x[0].lower() ...
def pigLatinSimple(word): if word[0] in "aeiou": return word + "hay" else: return word[1:] + word[0] + "ay" def pigLatinBest(word): if word[0] in ['a','e','i','o','u']: if word.isalnum(): return word + "hay" else: return word[:-1] + "hay" + word[-1] ...
def isVowel(letter): letter= letter.lower() A = letter == 'a' E = letter == 'e' I = letter == 'i' O = letter == 'o' U = letter == 'u' return A or E or I or O or U def noVowels(s): i = 0 result = "" while i < len(s): if not isVowel(s[i]): result = result + s[i]...
""" def sumOfPowers(n): power = 1 sumpower= 0 while 2**power <= n: sumpower = sumpower + 2 ** power power = power + 1 return sumpower print sumOfPowers(0) print sumOfPowers(10) print sumOfPowers(2) """ def sumAtoB(a,b): sumab = 0 while a <= b: sumab = sumab +...
def makeEvenList(n): x = [] i = 0 while i < n: x.append(i*2) i += 1 return x def makeHailList(n): x = [] while n > 1: if n%2 == 0: x.append(n) n = n / 2 else: x.append(n) n = 3 * n + 1 x.append(1) return x
"""Creating cup pong""" # from random import randint CUP: str = '\U0001F964' # SHOT: str = '\U00002716' # first_row: str = CUP*4 # print(first_row) # # print(len(first_row)) # second_row: str = CUP*3 # print("", second_row) # # print(len(first_row) + len(second_row)) # third_row: str = CUP*2 # print(" ", third_row...
"""Challenge question 1.""" choice: int = int(input("Enter a number: ")) if choice < 50: if choice < 25: print ("A") else: print ("B") else: if choice > 75: print ("C") else: print ("D")
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-07-31 18:17:44 # @Author : Star (1140330611@qq.com) # @Link : https://github.com/chenstarsQ/My-Python-Study-Note # @Version : $Id$ def dayUP(df): dayup = 1 for i in range(1, 366): if i % 7 in [6, 0]: dayup = dayup * (1-0.0...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-11-26 21:10:21 # @Author : Star (1140330611@qq.com) # @Link : https://github.com/chenstarsQ/My-Python-Study-Note # @Version : $Id$ def getNum(): nums = [] iNumStr = input("请输入数字(回车退出):") while iNumStr != "": nums.append(eval(iNumS...
import re # 使用 while 循环打印 1 3 5 7 9 i = 1 while i < 10: if i % 2 == 1: print(i) i += 1 # 编写一个函数,查找数字 6 是否在列表 l 里,如果在,输出“found”,如果不在,输出“not found” l = [1, 5, 7, 8, 9] def found(lst): if 6 in lst: print('found') else: print('not found') found(l) # 将字符串 s 拆分成两个字符串 s1、s2,其中 s...
class tree(): def __init__(self, p, root = 0, fathers = None, weigths = None): self.__map = {} self.__p = p self.__root = root if(fathers is not None and weigths is not None): l = len(fathers) self.__q = l for i in range(1, l): ...
''' Created on 30 avr. 2018 @author: PASTOR Robert ''' import numpy import math import random from ForcesTorques import acceleration, angular_acceleration from Controller import pid_controller ''' Simulation times, in seconds. ''' start_time = 0; end_time = 10; dt = 0.005; times = [start_time,dt,end_time]; ''' % N...
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from make_data import * def validate_prediction(df_data, weight_vector): a, b, c = weight_vector df_data['pred'] = df_data.apply(lambda row : 1 if (a*row.x + b*row.y + c) >0 else 0, axis=1) df_data['p'] = df_data.apply(lambda row :...
def emoji_convertor(): emoji_dictionary = { "happy": "😀", "sad": "😐", "excited": "🤓", } messages_list = message.split() output = "" for words in messages_list: output = output + emoji_dictionary.get(words, words) + " " print(output) message = inp...
import queue from queue import PriorityQueue import sys import copy # Sets the default recursion limit to satisfy the search sys.setrecursionlimit(10**6) # An object storing all the relevant information about the state, # game board: stored as a single string # g_n: the number of steps taken from the start to th...
# Example: # Read numbers until a sentinel (an empty string), and return their sum. # JMR 2018 # This is a typical example of a "loop-and-a-half": # a common situation where the exit condition # should be tested in the middle of the loop body. def inputTotal(): tot = 0.0 while True: s = input("valor?...
# Example: Listing directories and using file paths and metadata. import os import sys # Ask the user for a directory name, and validate it. def getDir(prompt): while True: name = input(prompt) if os.path.isdir(name): break print("{} não é diretório".format(name), file=sys.stderr) retu...
# Example: Print truth tables of boolean expressions # Consider three independent boolean variables A, B and C # and two dependent variables X and Y given by: # X = (A and not B) or C # Y = A and (not B or C) # Print the truth tables for these variables and check if X <=> Y. # # JMR 2019 boolValues = [False, True...
# Example: a simple translator # A dict with translations of Portuguese words to English: d = {"as": "the", "os": "the", "e": "and", "praia": "beach"} # Try: as armas e os barões assinalados que da ocidental praia lusitana s = input("Texto? ") t = "" for w in s.split(): if w in d: # check if word w is a key ...
# Example: # Write a function that counts down from N and then prints "Go!". # Write both a recursive version and an iterative version. # JMR 2018 # Recursive version def countdownR(n): if n > 0: print(n) countdownR(n-1) else: print("Go!") # Iterative version def countdown(n): whil...
# Example: loops inside loops # JMR 2018 letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def doSomething(): for c in letters: for d in letters: print(c+d) # What does this print? How many lines? doSomething()
import os import pandas as pd #print(courses) def get_course_list(): courses = os.listdir('./data') return courses def get_departments_list(course): courses = get_course_list() if course not in courses: return "Invalid course input" departments = os.listdir('./data/' + course) return ...
# coding: utf-8 # 実行方法: python3 network.py < list.csv import matplotlib.pyplot as plt import networkx as nx import numpy as np import sys edge_list = [] for line in sys.stdin: data_list = line.replace("\n", "").replace('"', '').split(",") edge_list.append( (data_list[0], data_list[1]) ) G = nx.Graph() # 辺の追加 for...
# -*- coding: utf-8 -*- #%% About # Name: bikeshare.py (based on the template bikeshare_2.py by UDACITY) # Author: Dr. Octavian Knoll (BMW Group/EP-413) # Python: Anaconda/Spyder (Python 3.8) # GitHub: https://github.com/OK-BMW/pdsnd_github.git # Version: v1.2 # History: v1.0: Initial version # v1.1: In...
from node import Node class Queue: def __init__(self, max_size=None): self.size = 0 self.max_size = max_size self.head = None self.tail = None def enqueue(self, value): if self.has_space(): item_to_add = Node(value) if self.is_empty(): ...
class Vertex: def __init__(self, id): self.id = id self.neighbors = {} def __str__(self): vertex_str = "I am " + self.id if self.neighbors: neighbors_result = ", ".join(self.neighbors.keys()) vertex_and_neighbors_str = vertex_str + "\nand my neighbors ar...
p=input() if((p>='a' and p<='z') or (p>='A' and p<='Z')): if(p=='a' or p=='A' or p=='e'or p=='E'or p=='i'or p=='I'or p=='o'or p=='O'or p=='u'or p=='U'): print("Vowel") else: print("Consonant") else: print("invalid")
beers = 5 covers = 0 bottles = 0 total = 0 while beers > 0: print 'drinking %d beers'% beers total += beers covers += beers bottles += beers beers = 0 beers = (covers + 2*bottles)/4 covers = (covers + 2*bottles)%4 bottles = 0 print 'exchange %d beers'% beers print 'You have drunk %d beers...'% total
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np G=1 M=1 m=1 class Planeta(object): ''' Simula, con opcion de 3 distintos metodos de integracion (Euler, Runge-Kutta4 y Verlet), el movimiento de un planeta que orbita al rededor del Sol, usando como base su pontecial. ''' def __init...
import nltk import math import matplotlib.pyplot as plt list = {"y'all", "y'alls", "y'all'd", "y'all'd've", "y'all're", "y'all've", "you'd", "you'd've", "you'll", "you'll've", "you're", "you've", "your" } alice = nltk.corpus.gutenberg.raw('carroll-alice.txt') #print(alice) ...
myList = list(map(int, input().split())) myList.sort() print(' '.join(map(str, myList))) myList = list(map(int, input().split())) sortedList = sorted(myList) print(' '.join(map(str, sortedList))) print(sorted((1, 3, 2))) print(sorted(range(10, -1, -2))) print(sorted("cba"))
myList = [1, 2, 3] for i in iter(myList): print(i) for i in myList: print(i) def myRange(n): i = 0 while i < n: yield i i += 1 for i in myRange(10): print(i) def genDecDigs(cntDigits, maxDigit): if cntDigits > 0: for nowDigit in range(maxDigit + 1): for tai...
class Man: height = 0 name = '' def manKey(man): return (-man.height, man.name) n = int(input()) peopleList = [] for i in range(n): tempManData = input().split() man = Man() man.height = int(tempManData[0]) man.name = tempManData[1] peopleList.append(man) peopleList.sort(key=manKey) fo...
name = input() print('I love', name) a = int(input()) b = int(input()) print(a + b) a = int(input()) b = int(input()) c = int(input()) d = int(input()) cost1 = a * 100 + b cost2 = c * 100 + d totalCost = cost1 + cost2 print(totalCost // 100, totalCost % 100) n = int(input()) print(n % 256) n = int(input()) k = int(...
""" int - округляет в сторону нуля (отбрасывет дробную часть) round - округляет до ближайшего целого, если ближайших целых несколько (дробная часть равно 0.5), \то к чётному floor - округляет в меньшую сторону ceil - округляет в большую сторону """ import math print(math.floor(-2.5)) print(math.ceil(-2.5)) from math...
# List lista = ['thing', 'thing1', 2, False] add = input("Whatcha wanna do baby?: ") lista.append(add) #print(listb[3]) # Dictionary listc = { 'first': 'zero', 'second': lista[1], 'third': 2, } print( listc )
""" Conversion Tool UTM - WGS84 This program is a command line tool to convert coordinates from one world coordinate system to the other one in both directions. It asks the user in which direction to convert and in which angle format (Decimal or Degrees, Minutes, Seconds) the user will enter the locations. The user ins...
import json """ This program will track the stats of characters such as wounds, strain and credits. It will also keep track of a characters skill points and give the option to use the default values provided thereby when making skill checks. These values will be stored in a dictionary called char and the dictionary ...
# Amanda Arreola - #001067645 import Package import datetime # This function contains all the console interface that a user interacts with. # It provides a option menu for the user. # A user can use this interface to find information on a package, or multiple packages. : O(n)^2 def interface(hashmap): print("WELC...
#function for calculate two numbers def calculator(): num1 = float(input("Enter first number: ")) #user input the first number op = input("Enter Operator: ") #user input the operator that are +,-,* or / num2 = float(input("Enter second number: ")) #user input the second number #if else statment for what...
class Calculator: def __repr__(self): return "value: {0}, \nattributes: {1}".format(self.value, self.__dict__) def __init__(self, init_value=0): self.value = init_value self.iter_flag = False def __add__(self, other): value = other.value if isinstance(other, Calculator) el...
import random # main routine goes here token = ["unicorn","horse","horse","horse","zebra","zebra","zebra","donkey","donkey","donkey"] STARTING_BALANCE = 100 balance = STARTING_BALANCE # Testing loop to generate 20 tokens for item in range(0,500): chosen = random.choice(token) # Adjust balance if chosen == "uni...
p1 = input().split() p2 = input().split() def append(inp): arr = [] for i in range(1, len(inp), 2): arr.append(inp[i] + "," + inp[i + 1]) return arr # 去除重复项 def removal(arr): arr = to_int(arr) new_arr = [] for i in range(0, len(arr), 2): base = arr[i] if base == 0: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Python的函数定义非常简单,但灵活度却非常大。 # 除了正常定义的必选参数外,还可以使用默认参数、 # 可变参数和关键字参数,使得函数定义出来的接口, # 不但能处理复杂的参数,还可以简化调用者的代码。 # 默认参数 # 默认参数应该放在必选参数后,这样才可以省略 def power(x, n=2): s = 1 while n > 0: s = s * x n = n - 1 return s print(power(3)) # 默认参数很有用,但也有坑啊 def...
import Parameters as param import ResourceQuality import BasicOperations as Ops import copy import math import csv res_dict = ResourceQuality.resourceDict seed = param.seed class Country: """ A class that defines the country object for every country in our countries dictionary. Each country object contains ...
from BaseAI_3 import BaseAI import time import math import random class PlayerAI(BaseAI): """This function manages the behaviour of the PlayerAI, uses alpha-beta prunining and minimax algorithm to determine the optimal play, against an opponent who is playing optimally. It should work well with ...
import random # импортируем модуль random #import os # импортируем модуль os для очистки консоли. os.system("cls") ##################################################################################### def multiplication(): multiplication_1 = random.randint(1, 10) multiplication_2 = random.randint(1, 10) result_1 ...
# Token types # #EOF token is used to indicate that #there is no more input left for lexical analysis INTEGER,PLUS,MINUS,MULTI,DIVISION,EOF='INTEGER','PLUS','MINUS','MULTI','DIVISION','EOF' class Token(object): def __init__(self,type,value): #token type:INTEGER,PLUS,or EOF self.type=type self.value=value def ...
# 분류 ANN을 위한 인공지능 모델 구현 from keras import layers, models #분산 방식 모델링을 포함하는 함수형 구현 def ANN_models_func(Nin, Nh, Nout): x = layers.Input(shape=(Nin,)) h = layers.Activation('relu')(layers.Dense(Nh)(x)) y = layers.Activation('softmax')(layers.Dense(Nout)(h)) model = models.Model(x,y) model.compile(loss...
def lcm(x, y): return (x * y) / gcd(x,y) def gcd(x, y): while(y): x, y = y, x % y return x
with open('6_input.txt') as fp: data = fp.read().splitlines() # print(data) def split_orbits(value): centre, orbiter = value.split(')') return centre, orbiter def all_objects(map): centres = [] orbiters = [] for value in map: centre, orbiter = split_orbits(value) centres.app...
# The valuation model for a stock # Author: Liang Tang # License: BSD import numpy as np import sys from sklearn import linear_model from pyvalue import constants from pyvalue.morningstar import financial class StockIntrinsicValue: def __init__(self): return @staticmethod def intrinsic_value(fin...
# https://leetcode.com/problems/binary-tree-level-order-traversal/ # Medium # Notes: uses multiple lists and did it using iterative methods. # Notes: 1 list to carry nodes and another to hold children. Must empty lists each iteration # Notes: Good time and space # Definition for a binary tree node. # class TreeNode: #...
# https://leetcode.com/problems/insertion-sort-list/ # Medium # My interpretation of insertion sort of a linked list # First, you shouldn't use a singly linked list for insertion sort because you often need to go back # I got around this by removing the node and iterating from the start of the list until I found the c...
# Варіант 1 import random arr = [random.randint(-100,100) for i in range(30)] MaxNumb=max(arr) arr.index(MaxNumb) print(arr) print("Max number is " + str(MaxNumb)) print("This number is in " + str(arr.index(MaxNumb)+1)+"th place") for i in range(29): if i%2 ==0: odds =[ n for n in arr if n%2] odds.sort(reve...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This code is an adaptation of the algorithms provided by Professor Lucas Silva de Oliveira ('Controller_TF.py' and 'Tank_NL.py') and it simulates the open loop dynamics of a coupled tank system with measurement noise and an inserted non-linearity (Gaussian), using the ...
largest = None smallest = None while True: num = input("Enter a number: ") if num == "done" : break try: fValue = float(num) except: print("Invalid Input") continue if largest is None: largest = fValue elif fValue > largest: largest = fValue if smallest is None: smallest = fValue elif fValue < ...
""" 置信区间 期望(均值/u) 标准差=均方差 区间估计可信度更高 参考 https://www.zhihu.com/question/26419030 Z校验值 Z P值 差异程度 >2.58 <0.01 非常显著 >1.96 <0.05 显著 <1.96 >0.05 不显著 """ import math # 两组的平均数都是70,但A组的标准差约为17.08分,B组的标准差约为2.16分,说明A组学生之间的差距要比B组学生之间的差距大得多 a = [95, 85, 75, 65, 55, 45] b = [73, 72, 71, 69, 68, 67] def avg(data): s =...
# Testing connections across a IP range on a specified port by attempting TCP three-way handshake # Output: printing on the screen, consecutive successful connections will be shown with only one line and only the latest successful connection will be shown # Program requirement: Python 2.7 import socket from ipaddress ...
import numpy as np import matplotlib.pyplot as plt # assume we have 1000 dogs greyhounds = 500 labradors = 500 #greyhounds are usually 28 inches grey_height = 28 + (4* np.random.randn(greyhounds)) # labradors are usually 24 inches lab_height = 24 + (4* np.random.randn(labradors)) # plot a histogram of the two heigh...
import operator x="hai" y="hello" x=operator.iadd(x,y); print(x) y="kiran" z="kumar" y=operator.iconcat(y,z); print(y) y="kirankiran" y+=z print(y) print('\n\n\n♥') li=[5,4,3,2,1] print('li: ',li) li2=li print('ids are same after assign') if li is li2 else print("not same after assing") li2.append(0) print('ids are ...
print('\n1♥importing module, using array() and printing') from array import * my_array1=array('i',[1,2,3]) print('trying to print direct arrayIdentifierName') print(my_array1)# prints the total discription import array as arr my_array2=arr.array('i',[4,5,6]) print('using index') for i in range(len(my_array2)): prin...
import random print('ROCK_PAPER_SCISSOS'.center(50, '*')) choice = ['R', 'P', 'S'] win, loss, tie = 0, 0, 0 quit_kw=['stop','exit','quit','terminate'] play_kw=['yes','ok','yeah','play'] def winner(player, computer): global win, loss, tie if player == computer: tie += 1;return 'you tie' elif playe...
import unittest from .controller import Item class UnitTestItem(unittest.TestCase): def test_is_item_purchasable_true(self): item_obj = Item() item_list = [ { "name": "Slurpee", "price": 80, "quantity": 18 }, { ...
# -*- coding: utf-8 -*- """ Created on Mon Jan 28 12:14:35 2019 @author: mluci """ import sqlite3 import os ####connect to the database#### def getdb(db_file): try: conn = sqlite3.connect(db_file) c = conn.cursor() return c except: return False ###check if database exists#...
##Brute Force Mockup of program used to crack Apple's firmware password (SIZE KNOWN) ##Steven Lamp from itertools import permutations def main(): psswrd = 'dts' bruteish(psswrd,3) def bruteish(crackMe, length): ################################################# #guesses = forceish(length) #for g in...
array = [['a','b','c'],['d','e','f']] # this works for any two-level list for sub in array: for e in sub: print e ''' Here's another way which works just for this specific array. print '\n'.join(array[0]) print '\n'.join(array[1]) '''
def Average(values): """ values must be an iterable yielding numbers. """ return sum(values)/len(values) #end def average(values) Mean = Average #alternative name def WeightedAverage(values, weights): """ values: a listing of data points. weights: a listing of weights for...
import random import matplotlib.pyplot as plt def horse_race(): horse_positions = [0,0,0,0,0,0,0,0,0,0,0] dead_horses = [] while len(dead_horses) < 4: die1 = random.randint(1,6) die2 = random.randint(1,6) dice_sum = die1 + die2 if dice_sum in dead_horses: pass...
# -*- coding: utf-8 -*- """ Created on Fri Jan 24 10:37:16 2020 @author: dpatel """ def climbStairs(n): dp = [0] * (n + 1) dp [0] = 1 dp [1] = 1 if n > 1: for i in range(2, n+1): dp[i] = dp[i-1] + dp[i-2] ...
# -*- coding: utf-8 -*- """ Created on Thu Jan 23 15:57:44 2020 @author: dpatel """ def coinChange(coins, amount): if not amount: return 0 dp = [amount + 1] * (amount+1) for i in range(amount+1): if i in coins: dp[i] = 1 continue ...
class Solution: def isPerfectSquare(self, num: int) -> bool: ansL = 0 ansR = 2 ** 31 - 1 while num != ansL ** 2 and num != ansR **2: if ansR - ansL == 1: return False suppose = (ansR + ansL) // 2 if suppose ** 2 > num: ansR ...
# -*- coding:utf-8 -*- ''' 对列表插入操作的实现 ''' class myList(object): ''' 自己实现的list类 ''' __list=[] def __init__(self,*value): self.__list.extend(value) def __str__(self): return str(self.__list) def myInsert(self,index,value): ''' :func...
def average(array): set_number = set(arr) total_distinct = len(set_number) sum = 0 for i in set_number: sum += i return sum / total_distinct if __name__ == '__main__': n = int(input()) # map(function, iterable) arr = list(map(int, input().split())) # change all input() to int()...
''' Creat a function by name pallindrome need a paramenter s1, The function return true if it is pallindrome else retrun false ''' def pallindrome(s1): #logic reverses1=s1[::-1] print (reverses1) if s1==reverses1: return True else: return False s1=(input("Enter first ...
# Writing to a file # One of the simplest ways to save data is to write to a file. When we write text to a file, the output will still be available after we close the terminal containing our programs output # Writing to an empty file # To write to a file, we need to call open() with a second argument telling python th...
import json # Here we set the file we write to, to a variable to open filename = "numbers.json" # We open the file in read mode (defaults to it if nothing is specified) as python only needs to read from the file with open(filename) as f: # json.load() loads the info stored in numbers.json and we assign it to a va...
# -*- coding: utf-8 -*- import re import os from num2words import num2words def int_to_en(num): d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourte...
# first find the BEST FIT line ( y=mx+b ) # m = ( (mean of x)*(mean of y) - (mean of xy) )/( (mean of x)^2 - (mean of x^2) ) # b = (mean of y) - m*(mean of x) from statistics import mean import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use('fivethirtyeight') ...
from sklearn.cluster import KMeans from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline import numpy as np class kMeans: def __init__(self): print("Running kmeans Network") def runModel(self, df): clustering=KMeans(init="random", n_clusters=2, random_state=8...
myList = [4, 3, 5.8, False, "hola"] print(myList) myList.append(8) print(myList) myList.append(9) print(myList) myList.extend(range(10,13)) print(myList) conteo = myList.count(3) print(conteo) myList.insert(9, True) print(myList) myList.remove(12) print(myList)
primerNumero = int(input("Ingrese el primer numero: ")) segundoNumero = int(input("ingresa el segundo numero")) if segundoNumero != 0: print(primerNumero /segundoNumero) else: print("Esta no puede ser realidad.") print("Fin")
lst = [[x for x in range (3)] for y in range(3)] for r in range(3): for c in range (3): if lst[r] [c] % 2 !=0: print("#")
subjects = ["Matematica", "Fisica", "Quimica", "Historia", "Lengua"] scores =[] for subject in subjects: score= input("¿Que nota has sacado en ", subject, "?") scores.append(score) for i in range(len(subjects)): print("En", subjects[i] , "has sacado", scores[i])
try: x= int(input("Ingrese un numero: ")) y = 1 / x print(y) except ZeroDivisionError: print("No puedes dividir entre ceron, lo siento. ") except ValueError: print("Debes ingresar un valor entero. ") print("FIN")
myList = [] for i in range(10): myList.append(i + 1) print(myList) myList.reverse() print(myList) myList.sort() print(myList) ubicacion = myList.index(3) print(ubicacion) myList.pop() print(myList) myList.pop(0) print(myList)
from sys import path path.append("..\\directorio") from directorio.area import areaCuadrado, areaCirculo, areaRectangulo from directorio.perimetro import perCadrado, perCirculo, perRectangulo def main(): print("--" * 30) print("programa para calcular areas y perimetros de figuras geometricas") print("--"...
import random class Game: X = 'X' O = '0' EMPTY = ' ' TIE = 0 NUM_SQUARES = 9 TREE_DEPTH = 9 MAX, MIN = 1000, -1000 def __init__(self): self.board = self.new_board() def display_instruct(self): """Display game instructions.""" print( """ ...
#! /usr/bin/env python contact_list = [ 'George:Hartwell:NY\n', 'Mary:Jones:NJ\n', 'Sue:Baker:PA\n', 'Hani:Ali:NJ\n', 'Gwen:Meyers:NJ\n', 'Druge:Gerrold:NY\n' ] input = raw_input('Please enter requested state abbreviation') input = input.upper() result_count = 0 print 'individuals in {0}...
#! usr/bin/python #memoizatin to make recursive fibonacci MemoTable = {} def MemoizedFib(n): if n <= 2: return 1 if n in MemoTable: return MemoTable[n] MemoTable[n] = MomoizedFib(n-1) + MemoizedFib(n-2) return MemoTable[n] res = MemoizedFib(10)
#! usr/bin/env python """ This program is meant to accept 2 variables, multiply exponentially and return a value. There should be appropriate top and bottom borders on the return value. Here are two runs of the program (bold is user input): $ python homework_2.py please enter an integer: 3 please enter another in...
#!/usr/bin/env python """Example code note""" def read_file(file_name): f = open(file_name) data = f.read() f.close() return data def split_lyrics(x): lyric_count = {} lyrics_list = x.split(" ") for word in lyrics_list: if word in lyric_count: pass # lyric_count[word] +=1 else: lyric_count[w...
import math import random def next_time(average_time): """ draw a time interval between two random events assume Poisson distribution """ return -math.log(1.0 - random.random()) * average_time def time_series(average_delta_time, N): """ return a list of N event times from t = 0 assume Poissio...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ pre...
#!/usr/local/bin/python3 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def traversal(self): num = 1 print(self.val,end='') curr = self.next while(curr and num < 5): print(curr.val,end='') ...