text
stringlengths
37
1.41M
#!/usr/bin/python3 from random import randrange # Checking if our big number is prime def checkPrime(n,k): # 2 is prime if n == 2: return True # 3 is prime if n == 3: return True # if it can be divided by 2 is not a prime if n <= 1 or n % 2 == 0: return False ###...
############################### #Claroty Automation Assignment# #########Shahar Sadeh########## ############################### from selenium import webdriver from selenium.common.exceptions import NoSuchElementException #open Chrome web driver driver = webdriver.Chrome() driver.get("https://www.google.com/...
# Exercicio 10 class BombaCombustível: def __init__(self, tipoCombustivel, valorLitro, quantidadeCombustivel): self.tipoCombustivel = tipoCombustivel self.valorLitro = valorLitro self.quantidadeCombustivel = quantidadeCombustivel def abastecerPorValor(self, valorLitro, quantidadeCombus...
<<<<<<< HEAD x = 2 def palindrome(x): #x = str(input('Add a string')) x = x.replace(' ', '') x = x.lower() for i in range(len(x)): if x[i] == x[-(i+1)]: continue else: return False return True def main(): palindrome(x) ======= def palindrome(str): ret...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ # Import libraries necessary for this project import numpy as np import pandas as pd from time import time from IPython.display import display # Allows the use of display() for DataFrames from sklearn.metrics import accuracy_scor...
sentence = input("Enter the sentence: ") words = set(sentence.split()) sorted_words = ' '.join(sorted(words)) print(sorted_words)
example = input("Enter the string: ") alphabets = [False] * 26 example_list = list(example.lower()) for alphabet in example_list: if alphabet != ' ': alphabets[ord(alphabet) - 97] = True for alphabet in alphabets: if alphabet == False: print("Its not a panagram") exit() print("Its a p...
import numpy as np def inverse(array): print(np.linalg.inv(A)) if __name__ == "__main__": row = int(input("Enter the number of rows: ")) col = int(input("Enter the number of columns: ")) print("Enter the matrix:") array = [[int(input()) for j in range(col)] for i in range(row)] A = np.array(ar...
import random upper_case = [chr(char) for char in range(65, 65+26)] digits = [chr(char) for char in range(48, 48+10)] lower_case = [chr(char) for char in range(97, 97+26)] special_charachters = [chr(char) for char in range(33, 48)] + [chr(char) for char in range(58, 65)] + [chr(char) for char in range(91, 97)] + [chr(...
numbers = list() print("Enter the list of numbers: ") number = 0 while number != -1: number = int(input()) numbers.append(number) numbers.pop(len(numbers) - 1) max_value = numbers[0] min_value = numbers[0] sum = 0 for x in numbers: max_value = max(max_value, x) min_value = min(min_value, x) sum +...
# Day 03 - Part 2 print "Day 03 - Part 2" with open("./day03-input.txt") as f: content = f.read().splitlines() def has_tree(spot): if spot != "#" and spot != ".": raise ValueError("Unexpected character") return spot == "#" def count_trees_in_slope(arboreal_map, right, down): trees_count = 0 horizontal_posi...
# Print "hello world" to the console when you push # on pin 17 # We will use the Button class from the gpiozero library # to control the pins on the Raspberry Pi: from gpiozero import Button # Let's initialize a Button object, and connect it to # pin 17: btn = Button(17) # Next, we need to define a function that wil...
class Solution: def largestMerge(self, word1: str, word2: str) -> str: a = list(word1) b = list(word2) c = '' while len(a) > 0 or len(b) > 0: if a > b: c += a[0] del a[0] else: c += b[0] ...
import requests already_asked_questions = [] def classify(text): key = "bf0ccdb0-2da2-11e9-9bd9-6d74cb2262f9dca94532-bfda-4919-9b85-e581ed9e711e" url = "https://machinelearningforkids.co.uk/api/scratch/"+ key + "/classify" response = requests.get(url, params={ "data" : text }) if response.ok: ...
booklist = [] book = {"id": 1, "title": "Where The Wild Things Are", "author": "Maurice Sendak", "onloan": False} booklist.append(book) booklist.append({"id": 2, "title": "The Very Hungry Caterpillar", "author": "Eric Carle", "onloan": False}) booklist.append({"id": 3, "title": "The Giving Tree", "author": "Shel Silve...
import os def clearscreen(): os.system('cls') def do_user_menu(user): selection = "0" while(selection != "5"): clearscreen() selection = show_user_menu(user) if(selection not in ["1", "2", "3", "4", "5"]): clearscreen() print(f"Invalid menu option [{sele...
class Person: def move(self): print("Person: Moves 4 paces") def rest(self): print("Person: Gains 4 health points") class Doctor(Person): def heal(self): print("Doctor: Heals 10 health points") class Fighter(Person): def fight(self): print("Fighter: Do 10 health...
print('Введите целое трехзначное положительное число:') a = int(input()) a1 = a // 100 a2 = (a // 10) % 10 a3 = a % 10 print('Сумма цифр числа', a, 'равна', a1 + a2 + a3) print('Произведение цифр числа', a, 'равно', a1 * a2 * a3)
""" Binary Search-> Simples searching technique. Search entire list one by one. """ pos = -1 def search(nums, n): for i in range(len(nums)): if nums[i] == n: globals()['pos'] = i return True return False nums = [10, 20, 30, 2, 5, 9, 18, 15] n = 15 if search(nums, n): pr...
""" Polymorphism - There is no direct implementation of Method Overloading in Python. """ class Student: def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 def sum(self, a=None, b=None, c=None): s = 0 if a != None and b != None and c != None: s = a + b + c ...
import string import random chars = string.ascii_letters + string.digits + string.punctuation def main(): """The main program""" # get length of the password the user wants length = input("How many characters do you want in the password? ") print(f"You have selected a {length}-character length passw...
# Q1 print('Q1: reverse a string.') string = input('Enter String :') B = [] for i in range(1, len(string) + 1): B.append(string[-i]) print('Reverse String:', ''.join(B)) # Q2 print('Q2: prints the number of uppercase letters and lowercase') def upperandlowercount(): string2 = input('Enter String...
# 도서관 시스템 코딩 # 1.회원 2.관리자 # 회원 >> 1.로그인 2.책대여 3.책반납 4.책찾기 0.로그아웃 # 관리자 >> 1.로그인 2.책등록 3.책목록보기 4.책페기 0.로그아웃 from loginsystem import loginservice from loginsystem import login from libsystem import rootmenu # main 함수 def root(): log=login() if log==1: log=2 return log def menu(sel): ...
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
'''Reserve Words False Class return is finally None if for lambda continue True def from while nonlocal and del global not with as elif try or yield assert else import pass break except in raise''' print('Hello World') print(" *") print(" ***") print(" *****") print("*******") print("...
#https://www.hackerrank.com/challenges/kaprekar-numbers # Enter your code here. Read input from STDIN. Print output to STDOUT def isKaprekar(num): square = num**2 numDigits = len(str(square)) for split in range((numDigits)/2, -1, -1): if split == 0 or split == numDigits: left = 0 ...
""" Divide two integers without using multiplication, division, or mod operator. """ class Solution: def divide(dividend, divisor): assert isinstance(dividend, int) assert isinstance(divisor, int) if divisor == 0: raise Exception # binaryList = [divisor] # mult...
class node: def __init__(self, val): self.val = val self.left = None self.right = None def iter1(self): if self.left: for x in self.left.iter1(): yield x yield self.val if self.right: for x in self.right.iter1(): ...
#Sudoku Swap #Taken from https://www.hackerrank.com/contests/w15/challenges/sudoku-swap # Enter your code here. Read input from STDIN. Print output to STDOUT def checkAllRows(grid): """ Returns a dictionary mapping row number to a pair of indices (x, x) where x appears twice in that row. """ swaps = {}...
#https://www.hackerrank.com/challenges/pangrams import sets import string inp = raw_input().lower() chars = set() for i in range(len(inp)): chars.add(inp[i]) for char in string.ascii_lowercase: if char not in chars: print "not pangram" break else: print "pangram"
""" # [ColorfulRoad](http://community.topcoder.com/tc?module=ProblemDetail&rd=15708&pm=12837) *Single Round Match 596 Round 1 - Division II, Level Two* ## Statement There is a one-dimensional road. The road is separated into N consecutive parts. The parts are numbered 0 through N-1, in order. Ciel is going to walk fro...
# Enter your code here. Read input from STDIN. Print output to STDOUT #k=2 --- 1, 3, -1, -3... #k=3 --- 0, 2, 4, 6... #k=4 --- 1234 --- 10, 8, 6, 4, 2, 0... #k=5 --- 12345 --- 15, 13, 11, 9, ... def solve(n, k): totalSum = sum(range(1, n+1)) return(totalSum >= abs(k) and totalSum%2 == k%2) numCases = input() ...
def insertion( x, y, i, j ): # create mask with 0's between i and j # all 1s ones = -1 # all 1s up to j, then 0s # 111110000000 ones << j #all 1s up to j, 0s up to i, 1s to end # 111110000011 ones |= ( -1 << j ) # mask x with this newly created mask x &= ones # shift y by...
#https://www.hackerrank.com/challenges/sherlock-and-the-beast # Enter your code here. Read input from STDIN. Print output to STDOUT def maxDecentNum(numDigits): for i in range(numDigits, max(-1, numDigits-(3*5)-1), -1): if i % 3 == 0 and (numDigits-i) % 5 == 0: return int("5"*i + "3" * (numDigi...
#http://community.topcoder.com/stat?c=problem_statement&pm=13524 """ Problem Statement for AliceGameEasy Alice and Kirito just played a game. The game consisted of a finite (possibly empty) sequence of turns. You do not know the exact number of turns. The turns were numbered starting from 1. In each turn, exa...
# given a sorted array with two elements swapped, find and fix the two elements swapped # so that the array is sorted. def fixSwapped(arr): # find first element that is lower than the previous assert len(arr) >= 2 i = 1 firstSwappedIndex = None while i < len(arr): if arr[i] < arr[i-1]: ...
#https://www.hackerrank.com/contests/epiccode/challenges/dance-in-pairs # Enter your code here. Read input from STDIN. Print output to STDOUT n, k = map(int, raw_input().split(" ")) boys = map(int, raw_input().split(" ")) girls = map(int, raw_input().split(" ")) boys.sort() girls.sort() totalMatches = 0 girlIndex = 0...
#http://community.topcoder.com/stat?c=problem_statement&pm=13783 def gcd(x, y): # This can be done using fractions.gcd, but wheres the fun in doing that? while y: tmp = y y = x % y x = tmp return x def testGcd(numTimesToTest): import fractions import random for i in range(numTimesToTest): ...
""" # [AlternateColors](http://community.topcoder.com/tc?module=ProblemDetail&rd=15186&pm=12343) *Single Round Match 564 Round 1 - Division II, Level Two* ## Statement Bob is playing with his ball destroyer robot. Initially, Bob has *r* red balls, *g* green balls and *b* blue balls. The robot will repeat the following...
#https://www.hackerrank.com/challenges/time-conversion/ time = raw_input() hour, rest = time.split(":", 1) hour = int(hour) pm = time[-2:] == 'PM' if hour == 12: pm = not pm if not pm: print time[:-2] else: hour += 12 if hour >= 24: hour -= 24 print "%02d:%s" % (hour, str(rest[:-2]))
# given a string, return the longest substring that has no duplicate characters. import sets def longestUniqueSubstring(s): if not s: return "" lastSeen = set() lastSeen.add(s[0]) start = 0 end = 1 bestStart = 0 bestEnd = 1 while end < len(s): if s[end] not in lastSeen...
""" dict客户端 """ from socket import * import sys from time import sleep # 服务器地址 ADDR = ("127.0.0.1", 8888) def main_l1(): print("=======一级界面========") print("=======登入:login========") print("=======注册:register=====") print("=======退出:exit=====") def main_l2(): print("=======二级界面========") ...
a=['a'] b='ABABABAB' import re print(re.findall('',b)) print(b.count('BA'))
#Rehaan Advani #Chapter 3 Programming Assignments import math def proj3_1(): print("This program will calculate the surface area and volume of a cylinder!") r = eval(input("The radius of the cylinder: ")) h = eval(input("The height of the cylinder: ")) sa = 2 * math.pi * r * (h+r) v = math.pi * r*...
import _tkinter from graphics import * def main(): win = GraphWin("Tic-Tac-Toe") win.setCoords(0.0, 0.0, 3.0, 3.0) Line(Point(1,0), Point(1,3)).draw(win) Line(Point(2,0), Point(2,3)).draw(win) Line(Point(0,1), Point(3,1)).draw(win) Line(Point(0,2), Point(3,2)).draw(win) for i in range(10):...
#!/usr/bin/python3 """ Write a function that queries the Reddit API and returns the number of subscribers (not active users, total subscribers) for a given subreddit. If an invalid subreddit is given, the function should return 0. """ import requests def number_of_subscribers(subreddit): if type(subreddit) is not...
class Generator: def __init__(self): pass def generate(self, ast): if type(ast) is not list: return ast if len(ast) == 2: return self.binOp(ast) if len(ast) == 1: return self.generate(ast[0]) def binOp(self, ast): assert len(ast)...
n = (int(raw_input("Start from: "))) - 1 m = int(raw_input("End on: ")) while n < m: n += 1 print(n)
# Сначала пример без использования регулярных выражений формат номера: # 8-ххх-ххх-хх-хх def isPhoneNumber(text): if len(text) != 15: return False if text[0] != '8':# Проверка на вхождение 8" return False if text[1] != '-':# Проверка на вхождение -" return False for i in rang...
DATABASE = { 'Серёга': 'Омск', 'Соня': 'Москва', 'Миша': 'Москва', 'Дима': 'Челябинск', 'Алина': 'Красноярск', 'Егор': 'Пермь', 'Коля': 'Красноярск' } # функция определеня количества друзей def format_friends(friends_count): if friends_count == 1: return 'У тебя 1 д...
import math def func (x,y,z): #return x + y + z return (math.sqrt(x)+x)/2 + (math.sqrt(y)+y)/2 + (math.sqrt(z)+z)/2 x = int(input ()) y = int(input ()) z = int(input ()) k = func (x,y,z) print (k)
import tkinter as tk def func(): try: x = float(entry_1.get()) y = float(entry_2.get()) label.config(text="Сумма числе будет равна {}".format(x + y)) except ValueError: label.config(text="Ошибка введите цифры") root = tk.Tk() entry_1 = tk.Entry(root) ent...
# здесь подключите библиотеку random и дайте ей краткое имя import random as r answers = ['Норм.', 'Лучше всех :)', 'Ну так', 'Отличненько!', 'Ничего, жить буду'] def how_are_you(): # напишите ваш код здесь a = r.choice(answers) return a print(how_are_you())
x = float(input('ведите х ')) import math if x > 0: y = (math.sin(x))**2 print (y) else: y = 1 - 2*math.sin(x**2) print (y)
# Разность двух множеств выводится на экран функцией print_valid_cities # списком с разделением запятой def print_valid_cities(a,b): c = a.difference(b) print(','.join(c)) # Пересечение двух множеств выводится на экран функцией print_common_cities # списком с разделением запятой def print_common_cities...
a = int(input ("введите трехзначное число ")) b = int(a//100) c = int(a/10 - 10*b) d = int(a - 100 * b - 10 * c) if (a > 99 and a < 1000): print ('поменяем последний и первый знак местами: ', 100 * d + 10 * c + b) else: print ('это не трехзначное число')
#слон бьет поле или нет? x = int(input ('введите столбец начальной клетки ')) y = int(input ('введите строку начальной клетки ')) a = int(input ('введите столбец конечной клетки ')) b = int(input ('введите строку конечной клетки ')) if (a-x) == (b-y) or (a-x) == (y-b): print ('YES') else: print ('NO')...
word = input('введите слово ') number = len(word) k = 0 while k < number: print (word[k],sep = '\n') k = k + 1 word = input('введите слово ') number = len(word) k = 0 while k < number: print (word[k],end = '\n') k = k + 1
from math import pi, sqrt import sys class FlexCircle(object): """ Class that computes properties of a circle based on either radius, area or perimeter """ def __init__(self, r): """Constructs radius r""" self.set_radius(r) def set_area(self, a): """ Assigns n...
def add(a,b): c=0 if (isinstance(a,int) or isinstance(a,float)) and (isinstance(b,int) or isinstance(b,float)): c=a+b else: print("请输入整数或者小数") print(c) add(1,34) add(12.4,13.4) #add("454",233) #add("889","899") add(454,"7889") print("testtestetetr") print("jirjoirjoi")
def createCollatzSequence(num): #print("The number is") #print(num) counter=0 while(num>1): if(num%2==0): num=num/2 else: num=num*3 +1 counter+=1 #print(counter) return counter maxNum=0 numCollatz=0 for x in range (1,1000000): if (creat...
print("hello world") a = 1 print(a) if a == 2: print("a is 2") else: print("a is ", a) print("After if statement") print("Before loop") while(a < 10): print(a) a = a + 1 print("After loop")
#!python3 import os search = "file" replace = "textdoc" type_filter = ".txt" targetpath = 'C:\\Users\\soul\\MyScripts\\junk\\' dir_content = os.listdir(targetpath) # print(os.path.isfile(dir_content[0])) print(dir_content) # print(type(dir_content)) # list comprehension # isfile by default takes current path, to mak...
#!/usr/bin/python import urllib2, urllib # Get the stored sunrise time and log it response = urllib2.urlopen('http://piserver/darksky/sunrise/') args = {'location': 'weather', 'event': 'sunrise', 'value': response.read()} response = urllib2.urlopen('http://piserver/log/?' + urllib.urlencode(args)) print(response) # ...
# -*- coding: utf-8 -*- """ ----------------------------------------------------------------------------- Python - Pandas Examples Copyright : V2 Maestros @2015 ----------------------------------------------------------------------------- This file contains sample code...
# -*- coding: utf-8 -*- # http://blog.csdn.net/cain/article/details/6605705 参考 import threading, time def a(tjoin): print('i am running') tjoin.start() tjoin.join() # 此时,不会直接运行下一步,而要等待tjoin里所有的数据打印完,即这个线程结束才可以继续下面的线程 print('i can end') def b(num): for i in range(0,int(num)): print('ye...
# Return indices of two unique numbers whose sum is equal to target (Only one guaranteed solution exist) # Tip: Convert array into tuple using enumerate and use hashmap to find value and track indices of num and target minus num class Solution(object): def twoSum(self, nums, target): d={} for i,nu...
# Given heights of the bars inside the container, Return the maximum amount of water a container can store # Tip: choose two lines such that we could maximize the min of two heights and the distance between the bars. class Solution(object): def maxArea(self, heights): l, r = 0, len(heights) - 1 re...
# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine all parenthesis are valid # Tip: Use hashmap to create closing to open parenthesis mapping and use stack to push pop class Solution(object): def isValid(self, s): hashmap = { "]":"[", "}":"{", ")":"(" } ...
''' Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left p...
import unittest from node import Node """ 0 3 2 5 4 """ class TestNodeTraversal(unittest.TestCase): def setUp(self) -> None: self.root = Node(0) inner_right = self.root.insert_right(2) inner_right.insert_right(4) inner_left = self.root.insert_left(3) inner_l...
def celsius(num): conversion = (num * (9 / 5)) + 32 return conversion def fahrenheit(num): conversion = (num - 32) * (5/9) return conversion prompt = input("Enter a temperature in C: ") num = float(prompt) print("Your temperature in F: {}".format(fahrenheit(num))) prompt = input("Enter a temperatu...
from src.car import Car class Slot: def __init__(self, number): self.number = number self.empty = True self.car = None def make_it_empty(self): self.empty = True del self.car self.car = None print "Slot number " + str(self.number) + " is free" def...
import cv2 import numpy as np def fillholes(im_in): # Threshold. # Set values equal to or above 220 to 0. # Set values below 220 to 255. th, im_th = cv2.threshold(im_in, 220, 255, cv2.THRESH_BINARY) # Copy the thresholded image. im_floodfill = im_th.copy() # Mask used to flood filling. # Notice the s...
from PIL import ImageFilter class Detector(object): """Perform edge detection and return the Image.""" @staticmethod def detect(img): # type: (Image) -> Image """Mark edges in the image.""" return img class DummyDetector(Detector): """Super simple edge detection. Specifically: 1) Naively smooth the image...
a = (1, 2, 3, 4, 5) print(type(a)) print(a[-2]) print(max(a)) a = list(a) # 이걸쓰면 튜플을 다시 리스트로 만들 수 있음 a[0] = 10 print(a) a = tuple(a) # 리스트 수정이 끝났으면 다시 튜플화 시킬수도 있음 brr = 'korea' print(brr[0]) # brr[0] = 'o' <- 이거 하면 오류남. 문자열은 튜플로 처리되기 때문임.
"""딕셔너리는 키 값으로 구성되면 접근자체를 '키' 값으로한다. 키값을 index 로 쓰는 것은 권장되지 않는다.""" person = dict(zip(('name', 'age', 'addr'),('ㅇㅇㅇ', 30, 'busan'))) # zip 함수를 이용해서 키 밸류 자체를 리스트이용하는 개념임. 실사용 예 많음. # person = {'name': '홍길동', 'age': 20, 'addr': 'busan' } # 디폴트로 일단 Dict 로 인식함. # print(person['name']) # 이렇게 키값으로 접근함. -파이썬으로는 이렇게 쓰면되는데 pe...
#Brandon Phipps, John Hampton, Jon-Paul Casias #RSA encrypter and decrypter import random #main driver function def main(): answer = '' #determines whether user wants to encrypt or decrypt reRun = '' #determines whether user wants to encrypt or decrypt another message t = True while...
"""JSON Sanitization""" # clean takes in some string and eleminates escape characters def clean(someString): # check if the string is alphanumeric if str(someString).isalpha(): return True # check if the string are numbers
movie_title=["The Devil Wears Prada","Roman Holiday","Aladdin","Titanic","The Fast and the Furious"] parental_rating=["PG-13","NR","G","PG-13","PG-13"] bechel_rating=["3","3","0","3","3"] imdb_rating=["6.8","8.1","8.0","7.7","6.5"] genre=["Comedy/Drama/Romance","Comedy/Drama/Romance","Animation/Adventure/Comedy","Drama...
a=int(input('Primeiro número: ')) b=int(input('Segundo número: ')) c=int(input('Terceiro número: ')) if a>b or a>c: print(f'Maior {a}') elif b>a or b>c: print(f'Maior {b}' ) elif c>b or c>a: print(f'Maior {c}') if a<b or a<c: print(f'Menor {a}') elif c<b or c<a: print(f'Menor {c}') elif b<a or b<c: ...
def factorial( n ): if n == 0: return 1 else: return factorial( n-1 ) * n def printRev( n ): # NOTE: Recibe el numero tres y lo imprime en la pantalla if n > 0: # NOTE: Imprime una secuencia en reversa hasta llegar a un numero mayor a cero print( n ) printRev( n - 1 ) def fibonacci( n ): if n ...
# Python Word Game # # Technical Interview Deliverable # Created by: Kitsao Emmanuel # Implemented by: Kitsao Emmanuel # from wordgame import * import random import string import sys import time import random # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIS...
''' NOTA IMPORTANTE: read() en files lo que hace es convertir todo el archivo en un string gigante por ejemmpo f = open (filename, 'rU') string_gigante = f.read() string_gigante contiene todo el archivo en un string ''' import sys def Names(filename): f = open(filename,'rU') text = f.read() print text f.close...
valor_1=int(input("digite el valor para comparar con los numeros en las posiciones impares: ")) valor_2=int(input("digite el valor para comparar con los numeros en las posiciones pares: ")) tamaño=int(input("digite el tamaño de la lista a comparar: ")) lista=[] m=0 for i in range(tamaño): valores=int(input("di...
#!/usr/bin/python -tt # coding=utf-8 """ Averiguar si dos vectores son iguales y tienen el mismo contenido. Si no es así, especifficar la primera posición en la cual se hicieorn diferentes. """ import sys import pdb def analized_vertor(list_1=[1,2,3,4,5,6,7,8,9],list_2=[1,2,3,4,5,6,7,8454,9]): if str(list_1) == str(...
#!/usr/bin/python -tt # coding=utf-8 """" Lilah has a string, s, of lowercase English letters that she repeated infinitely many times. Given an integer,n , find and print the number of letter a's in the first n letters of Lilah's infinite string. For example, if the string s='abcac' and n=10, the sub...
import pdb """ John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n =7 socks with colors ar=[,1,2,1,2,1,3,2]. There...
import sys def base10_to_base62(num): alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" array_shortener = [] resultado = '' while num>0: array_shortener.append(num%62) num = num//62 for x in reversed(array_shortener): resultado+=alphabet[x] return resultado #544...
#!/usr/bin/python -tt # coding=utf-8 class Clase1(object): def __init__(self): self.atributo_clase_1 = "soy un atributo de la clase 1" def metodoClase1(self): print "soy un metodo de la clase 1" class Clase2(object): def __init__(self): self.attributo_clase_2 = "soy un atributo de la clase 2" def metodoC...
filas=5 columnas=5 matriz=[] for i in range(filas): matriz.append([]) for j in range(columnas): matriz[i].append(None) for i in range(filas): for j in range(columnas): if i+j==filas-1 or i==j: matriz[i][j]=1 else: matriz[i][j]=0 for x in matriz: print (x)
# hex string num_hex = '0F' # convert hex to decimal num_dec = int(num_hex, 16) print('Value in hex:', num_hex) print('Value in decimal:', num_dec)
""" el metodo listdir del modulo os se llama asi : os.listdir(le envio un path) le envio un path como argumento y lo que retorna son todos los nombres de los archivos que hay en ese path nota obvimante el path que le envio lo hago con los argumentos de la consola y se lo envio de esta forma python2 utilities1.py...
""" ver si los valores ubicados en las posiciones pares de una lista son todos iguales con listas hasta de tamaño 100 """ def pares(): tamano=int(input("que tan grande es la lista: ")) if tamano>=1 and tamano<=100: arr1=[] arr2=[] for v in range(tamano): v1=int(input("coloque los valo...
#!/usr/bin/python -tt # coding=utf-8 def triangulo(): matriz=[ [1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1]] tuplas = (('s','superior'),('i','inferior'),('n','sin orientacion')) superior=0 inferior=0 rta = None for i in range(len(matriz)): for j in range(len(matriz)): if i<j: sup...
#!/usr/bin/python -tt # coding=utf-8 """ documentation: https://docs.python.org/3.4/library/functions.html https://docs.python.org/3.4/library/functions.html https://docs.python.org/3.4/library/functions.html """ # -------------------------------any()------------------------------- """ any() va retornar un bool...
#!/usr/bin/python -tt # coding=utf-8 lista = [4,2,6,8,5,7] pivote = 0 for x in range(len(lista)): print x """ Método de ordenamiento de burbuja revisa cada elemento de la lista con el siguiente elemento, intercambiandolos de posicion si esta en el orden equivocado """ # 4 2 6 8 5 7 # 2 4 6 8 5 7 # 2 4 6 ...
# un objecto es lo mismo que una clase class Humano(): def __init__(self): self.nombre = 'juan' self.edad = 23 self.peso =63 self.estatura = 1.2 def correr(self): print("El humano esta corriendo ") def reir(self): print("el humano esta riendo") copia_humano = Humano() print(copia_hum...
import pdb matriz=[] fila = 8 columna = 8 for i in range(fila): matriz.append([]) for j in range(columna): matriz[i].append(None) for x in matriz: print(x) print("*********************") contador = 0 for i in range(len(matriz)): for j in range(len(matriz[i])): matriz[i][j] = contador contador+=1 for x i...
value = int(input("Enter a value: ")) if (value % 2) == 0: print("{0} is Even".format(value)) else: print("{0} is Odd".format(value))