text stringlengths 37 1.41M |
|---|
class DynamicArray:
def __init__(self):
self._storage = [None] * 4
self._number_of_items = 0
def __len__(self):
return self._number_of_items
def __getitem__(self, index):
self._is_index_valid(index)
return self._storage[index]
#???
#def __setitem__(self, k... |
# 10
# / \
# 8 15
# / \ / \
# 4 9 12 20
class Item:
def __init__(self, key, value=None):
self._key = key
self._value = value
def __eq__(self, other):
return self._key == other._key
def __ne__(self, other):
return not (self == other)
def __lt__... |
#1. Eric Charnesky says do not cheat!
#2. Because the position has the Node behind the scenes ( is a wrapper class around Node), you can add/remove around a node in a linked list in O(1)
#3. Class Course:
class Course:
def __init__(self):
self.Name = “”
self.Number = “”
self.Credits = 0
self.Cost_per_credit = 0
... |
print ("Vowel Counter")
word = 0
vowel_count = 0
while 2 > 0:
vowel_count = 0
word = input("Input Word: ")
vowel_count = vowel_count+word.count("a")
vowel_count = vowel_count+word.count("e")
vowel_count = vowel_count+word.count("i")
vowel_count = vowel_count+word.count("o")
vowel_count = vow... |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
num_line = 0
s =0.0
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
else :
ipos = line.find(" ")
b= line[ipos+1:]
s = s + float(b)
num_line ... |
import csv
import os.path
def cargar_empleado(campos):
pregunta = "si"
lista_Empleados = []
while pregunta == "si":
empleado = {}
for campo in campos:
ok = True
while ok:
print(f"Ingrese {campo} del empleado: ")
dato = input("")
... |
r = int(input('Informe raio do circulo ' ))
a = 3.14 * r * r
print(f'A area do circulo é {a}') |
b = int(input('informe a base do quadrado '))
h = int(input('informe a altura do quadrado '))
a = b * h
d = a**2
print(f'O dobro da area informada é {d}') |
import heapq, random, time
class ElevatorControlSystem():
def __init__(self, number_of_floors, number_of_elevators):
if number_of_elevators <= 0:
raise AssertionError("Your building must have at least one elevator.")
if number_of_floors <= 0:
raise AssertionError("Your building must have at least one floor.... |
import binascii
def padding(txt, block_size):
padding_to_add = block_size - len(txt)%block_size
for i in range(0, padding_to_add):
txt+=bytes([padding_to_add])
return txt
def main():
txt = b"YELLOW SUBMARINE"
txt = padding(txt, 20)
print(txt)
if __name__ == '__main__':
main() |
import re
pattern = "[a-zA-Z]red"
regexp = re.compile(pattern, re.IGNORECASE)
file = open("names.txt")
print("Open the file " + file.name + " ...\n")
print("Match(es) is/are:\n")
count = 0
for line in file:
match = regexp.search(line)
if match:
count += 1
print(line, end ="")
pri... |
from datetime import datetime
from covid import Covid
covid = Covid()
for line in covid.list_countries():
line = line['name']
print(line)
while True:
country = input('Enter Country: ')
try:
DataJson = covid.get_status_by_country_name(country)
country = DataJson["country"]
... |
import numpy as np
board = [[3,0,0,8,0,1,0,0,2],
[2,0,1,0,3,0,6,0,4],
[0,0,0,2,0,4,0,0,0],
[8,0,9,0,0,0,1,0,6],
[0,6,0,0,0,0,0,5,0],
[7,0,2,0,0,0,4,0,9],
[0,0,0,5,0,9,0,0,0],
[9,0,4,0,8,0,7,0,5],
[6,0,0,1,0,7,0,0,3]]
def possible(row, c... |
import pygame as pg
#class for text that will displyed in game
class GameText:
def __init__(self, text, size, fontName, position, color):
self.text = text
self.size = size
self.name = fontName
self.position = position
self.color = color
self.bold = False
sel... |
"""String algorithms.
Some people, when confronted with a problem, think “I know, I'll use regular
expressions.” Now they have two problems.
Jamie Zawinski
"""
from typing import Dict
def edit_distance(s1: str, s2: str) -> int:
"""The minimum number ... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def which_day(date_time):
'''
To find out which weekday according to given timestamp
input: datetime string with the format of 'yyyy-mm-dd hh:mm:ss'
return: nth day of the week
'''
assert isinstance(date_time, str)
a... |
#!/usr/bin/env python
# coding: utf-8
# In[30]:
import csv
# In[31]:
text = open("username.csv", "r")
# In[32]:
with open('username.csv','r') as csv_file:
csv_reader=csv.reader(csv_file)
for line in csv_reader:
print(line)
# In[33]:
#join() method combines all contents of
# csvfile.csv ... |
num=int(input('enter numerator: '))
den=int(input('enter denominator: '))
quo= (num/den)
print (quo)
|
"""
This module exports the 'Hand' class, 'PlayerHand' and 'DealerHand' subclasses, and related methods.
"""
import time
draw_delay = 1 # The pause in seconds between drawn card actions
twenty_one = 21 # Ideal score value for both players
class Hand:
"""
A class defining the properties and methods of a han... |
# authors:
# filename:
# date:
#
# description: <insert description here>
### imports ###
# insert imports here
# ensure there are no overlaps
import random
###############
##### GLOBALS #####
# insert global variables here, explain what they are with comments
# and include what type they are, and/or expected to... |
print("MathGEN 1.0")
print("Разработчики: StupidKuklovod, kukold-code, Evgenia003. Дрим тим так сказать.\n")
print("В следующем окне введите число от 1 до 3 - тип уравнения.")
import math
a = int(input("Введите номер, соответствующий виду уравнения, которое вы хотите решить: "))
if a == 1:
x = int(input('введите ... |
def show_instructions():
# print a main menu and commands
print('Pirate Text Adventure Game')
print('Collect 6 items to win the game, or fail your mission.')
print('Move commands: go South, go North, go East, go West')
print("Add to Inventory: get 'item name'")
def show_status():
prin... |
#for loops
items=[]
prices=[]
item_name="none"
price=0
for i in range(3):
item_name=input("Enter item name:")
price=input("Enter price:")
items.append(item_name)
prices.append(int(price))
total_price=0
for i in range(3):
print("Item is "+items[i])
print("Item price is "+ str(prices[i]))
... |
DIGITS = "0123456789ABCDEF"
def hexify(i: int) -> str:
#return "00"
# FIXME
string = ""
if i == 0:
return "0"
while i > 0:
x_low = i & 15
string = DIGITS[x_low] + string
# x_high = (i >> 4) & 15
i = i >> 4
return string
print(hexify(0x0)) # Expected Ou... |
"""
Driver (main program) for symbolic calculator.
"""
from rpn_parse import parse, InputError
from lexer import LexicalError
import expr
help = """Type 'quit' to quit.
Assignment: 'var expression ='
Form expressions with +, -, *, /, ~ (negation)
Use a space between each element, e.g.,
for y_not gets z + 3:
yes: y... |
""" In class: Postfix, S-expressions"""
ops = {"+": lambda x, y: x + y, # lambda is a compact way of defining a function
"*": lambda x, y: x * y,
"-": lambda x, y: x - y,
"/": lambda x, y: x // y}
def eval_postfix(s: str) -> int:
"""
if "5 3 + 4 *": eval_postfix("5 3 + 4 *") -> 32
i... |
"""
alphacode.py: Convert PIN code to mnemonic alphabetic code
Authors: Noah Tigner
CIS 210 assignment 1, Fall 2016.
"""
import argparse # Used in main program to get PIN code from command line
from test_harness import testEQ # Used in CIS 210 for test cases
## Constants used by this program
CONSONANTS = "b... |
"""
Reading and writing Sudoku boards. We use the minimal
subset of the SadMan Sudoku ".sdk" format,
see http://www.sadmansoftware.com/sudoku/faq19.php
Author: M Young, January 2018
"""
import sdk_board
import typing
from typing import List, Union
import sys
from io import IOBase
class InputError(Exception):
p... |
"""
Solve a jumble (anagram) by checking against each word in a dictionary
Authors: Noah Tigner
Usage: python3 jumbler.py jumbleword wordlist.txt
"""
import argparse
def jumbler(jumble, dict_file_name):
"""
compare a jumbled anagram to a dictionary to find matches.
inputs:
jumble: the given ju... |
"""
drawflower.py: Draw flower from multiple squares using Turtle graphics
Authors: Noah Tigner
Credits: draw_square funtion based off on Miller & Ranum, "Python Programming In Context", pp34.
CIS 210 assignment 1, Fall 2016.
"""
import argparse # Used in main program to get num_squares and side_length
... |
#Rock, Paper, Scissors!!!
#Random answer from the computer (Rock, paper, or scissors)
#Best 2/3?
import random
numoflives = 3
numofpoints = 0
weapons = ["Rock", "Paper", "Scissors"]
print("I challenge you, to the death!")
print("\n")
print("Choose your weapon, type 'weapons' to see what you can use")
... |
# Author Vladimir SR
def lists_methods():
male_names = ["Alvaro", "Jacinto", "Miguel", "Edgardo", "David"]
male_names.append("Jose")
print(male_names)
male_names.extend(["Jose", "Gerardo"])
print(male_names)
male_names.insert(0, "Ricky")
print(male_names)
male_names.po... |
# Author Vladimir SR
import random
"""
Ejercicio 1
Escriba una función que tome una lista de números y devuelva la suma acumulada,
es decir, una nueva lista donde el primer elemento es el mismo, el segundo
elemento es la suma del primero con el segundo, el tercer elemento es la suma
del resultado anterior con el siguie... |
def knapsack_without_repeats(capacity, weight_list):
cost = 1
previous = [0] * (capacity + 1)
for i in range(1, len(weight_list) + 1):
current = [0]
for w in range(1, capacity + 1):
current.append(previous[w])
if weight_list[i - 1] <= w:
current[w] =... |
#ask for primes
p = int(input("How many primes? "))
#counts for primes
counts = 2
#counts for iterations
nums=2
while(counts<=p+1):
#count for the numbers
count = 0
#i is first prime number
i=2
#check for non-primes
while(i<= nums//2):
if (nums % i == 0):
#skip to the next n... |
# This function is used to convert colorful images into grayscale.
import cv2
def color2gray(input_path, output_path):
name = input_path.split('/')[-1]
output_path = output_path + 'gray_' + name
img_array = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE)
img_array = cv2.resize()
_ = cv2.imwrite(outp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 14:18:07 2021
@author: kamzon
"""
class Node:
def __init__(self,val):
self.l_child = None
self.r_child = None
self.data = val
""" insert node into BST"""
def insert(... |
# Joke Setup
types_of_people = 10
x = f"There are {types_of_people} types of people."
# Joke Punchline
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
# Print out the joke.
print(x)
print(y)
# Restate the joke, nesting the string as a variable inside an f-string
print(f"I sa... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import defaultdict
import xml.etree.cElementTree as ET
import re
import tool
"""
The tool module that there are some functions being used in the fileis
created by myself!
Firstly, parsing the xml, so that we can know the tags and the subtags
with some in... |
"""
Problem:
Design a data structure for a pet shelter. The pet shelter must be able to add
a dog or add a cat and associate a timestamp with each new pet (you can use an
auto-increment id).
The data structure must also support removeDog and removeCat, which remove the
dog which has been here the longest (i.e. dequeu... |
class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, data):
if self.root == None:
self.root = Node(data)
else:
sel... |
def list_mean(x):
if x==[]:
return "Must key in the numbers"
i=0
for h in x:
i=i+h
i=i/float(len(x))
return i
print list_mean([1,2,3,4])
print list_mean([1,3,4,5,2])
print list_mean([])
print list_mean([2])
|
status=True
while(status):
pl1=str(input("Enter player1 turn"))
pl2=str(input("Enter player2 turn"))
if pl1=="Rock" and pl2=="Scissors" or pl1=="Scissors" and pl2=="Rock":
print("Rock beats Scissors")
status=False
elif pl1=="Scissors" and pl2=="Paper" or pl1=="Paper" and pl2=="Scissor... |
# ****************************************************************
# AULA: Visão Computacional
# Prof: Adriano A. Santos, DSc.
# ****************************************************************
# Importando a biblioteca OpenCV
import cv2
# Imagem
aquivo = "./imagens/raposa.jpg"
# Carregando a imagem
image = cv2.imre... |
from abc import ABC, abstractmethod
import pandas as pd
class Abstrata(ABC):
def __init__(self, path_from, path_to):
self.path_from = path_from
self.path_to = path_to
@abstractmethod
def processa(self):
# Essa função irá herdar os comandas assim que for chamada
pass
|
# Python program to display calendar of given month of the year
# import module
import calendar
# To ask month and year from the user
year= input("Enter year: ")
month = input("Enter month: ")
# display the calendar
print(calendar.month(year, month)) |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Importing the dataset
dataset = pd.read_csv('D:/Udemy ML/ML_Complete/Part 3 - Classification/Dataset2/Classified Data.csv')
print(dataset.shape)
count=pd.value_counts(dataset['TARGET CLASS'])
print(count)
x=dataset.iloc[:... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (20.0,10.0)
#reading data
data=pd.read_csv('C:/Users/kiit1/Documents/headbrain.csv')
#collecting X and Y
X=data['Head Size(cm^3)'].values
Y=data['Brain weight(grams)'].values
#Finding Mean value
mean_X=np.mean(X... |
import natch
@natch.lt(0)
def factorial(x):
x = abs(x)
x = factorial(x)
x = -1 * x
return x
@natch.eq(0)
def factorial(x):
return 1
@natch.eq(1)
def factorial(x):
return 1
@natch.gt(1)
def factorial(x):
x = x * factorial(x - 1)
return x
for i in range(-5, 6):
result = facto... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# anuther :zhanglei
def read_file():
#afile = file('data.txt', 'r')
afile = open('data_write.txt','r')
for i in afile.readlines():
print i.strip().decode('utf-8')
afile.close()
def write_file():
name_list=[u'张三',u'李四',u'王五']
afile=open('dat... |
def red_color():
return 'red'
def blue_color():
return 'blue'
def white_color():
return 'white'
def is_white(button):
if button == white_color():
return True
return False
def is_red(button):
if button == red_color():
return True
return False
def is_blue(button):
... |
# Abrir arquivo em diretório
arquivo = open("c:/Users/Minecraft/Desktop/arquivo.txt")
# Ler linhas de texto do arquivo
"""
Linhas = arquivo.readlines()
#Mostrar linhas como elementos
for linha in Linhas:
print(linha)
"""
# Ler texto completo
texto = arquivo.read()
print(texto)
|
import re
import nltk
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
import string
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
def lemmatize_words(text):
return " ".join([lemmatizer.lemmatize(word) for word in text.split()])
from nltk.stem.porter import Porte... |
s = input().split(" ")
if int(s[0])!=0 and int(s[1])!=0 and int(s[2])!=0 and int(s[0]) + int(s[1]) + int(s[2]) == 180:
print("Yes")
else:
print("No") |
n = int(input())
m = int(input())
sum = 0
for i in range(-10, m+1):
for j in range(1, n+1):
sum += int(((i + j)**3) / (j**2))
print(sum) |
n = input()
#b = sum of digits of input
b = 0
for i in n:
b+= int(i)
#checkprime function
def checkprime(num):
t=1
for i in range(2,num):
if (num % i) == 0:
t=0
break
return t
i = 0
n = int(n)
while i < b:
n += 1
if checkprime(n)== 1:
... |
'''
Este website é igual uma loja de livros
'http://books.toscrape.com/'
Eu passo por todas as páginas do site, pego as urls da cada livros
e pego as informações da cada livro:
Título, categoria, preço e quantidade no estoque
Depois eu salvo no MySQL.
Coloquei um intervalo de 1 segundo para a url de cada livro,
se você... |
import math
import pygame
class Paddle():
""" The paddle at the bottom that the
player controls. """
def __init__(self):
super().__init__()
self.width = 100
self.height = 20
self.image = pygame.Surface([self.width, self.height])
self.rectangle = self.image.get_re... |
"""Implemention of the Maze ADT using a 2-D array."""
from arrays import Array2D
from lliststack import Stack
class Maze:
"""Define constants to represent contents of the maze cells."""
MAZE_WALL = "*"
PATH_TOKEN = "x"
TRIED_TOKEN = "o"
def __init__(self, num_rows, num_cols):
"""Creates a... |
string = "achal chanish mridul puneet"
names = string.split(" ")
print names
pop_name = names.pop(0)
print names
pop_name = names.pop(-1)
print names
|
#!/usr/bin/env python3
import skilstak.colors as c
print(c.clear)
def ask(question):
print(c.red + question + c.reset)
answer = input("> " + c.base3).lower().strip()
print(c.reset)
return answer
name = ask(c.b + "What is your name?")
def diecrew():
print(c.red + """You have lost members of your crew, ... |
import random
# Welcome to the game text:
def welcome():
print('Answer "yes" if given number is prime. Otherwise answer "no".\n')
# Function returns tuple with question and right answer:
def question_and_answer():
num = random.randint(1, 101)
step = 2
question = 'Question: {}'.format(num)
while... |
from numpy import *
arr=array([
[1,2,3,5,4,2],
[4,5,6,8,9,3]
])
print(arr.ndim)# attribute ndim num of dimension
print(arr.shape)#num of rows & colums
print(arr.size)
arr1=arr.flatten()#convert 2D to 1D
print(arr1)
arr2=arr1.reshape(2,2,3)# 3D array
print(arr2)
m=matrix(arr)
print... |
class computer:
pass
c1=computer()
c2=computer()
print(id(c1))
print(id(c2))
class comput:
wheels=4 # class variable
def __init__(self):
self.name="navin" #instance variable because values are change
self.age=20 #instance variable inside of init
def update(self):
... |
pos = -1
def search(list,n):
l=0
u=len(list)-1
while l <= u:
mid=(l+u)//2 # integer division
if list[mid]==n:
globals() ['pos'] = mid
return True
else:
if list[mid]<n:
l= mid+1
else:
u=mi... |
#!/bin/env python3
# -*- coding: utf-8 -*-
# version: Python3.X
""" 无边界地图
参考讨论区给出的算法进行实现
题目链接: http://www.qlcoder.com/task/75d8
"""
__author__ = '__L1n__w@tch'
class Point:
def __init__(self, x=None, y=None, is_alive=False):
# is_alive 为 True 表示是生命体
self.x, self.y, self.is_alive = x, y, is_alive... |
'''
EXTRACTING FEATURES
Jeff Thompson | 2018 | jeffreythompson.org
A simple example that recreates the one we built in Processing: load an image,
resize it and convert to grayscale, and create an array from the pixels.
In the 'Better' version next, we'll improve on this and feed it into some
machine learning algorit... |
import csv
def read_question():
with open("sample_data/question.csv", "r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ',', quotechar = '"')
list_to_return = []
for row in csv_reader:
list_to_return.append(row)
return list_to_return[1:]
def write_question... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 26 13:42:13 2014
@author: eocallaghan
"""
import pygame
from pygame.locals import *
import random
import math
import time
""" """ """ """ """ """ """ """ """ """ """ """ """ """ """
Model
""" """ """ """ """ """ """ "... |
# object interaction
class Player(object):
""" Player """
def blast(self, enemy):
print("The player blasts an enemy.\n")
enemy.die()
class Alien(object):
""" Alien """
def die(self):
print("Ugh! ...")
#main
print("\tAlien death")
hero = Player()
invader = A... |
# create own functions
def instructions():
"""Display game instructions"""
print(
"""
Prepare yourself. I am the master of Noughts and Crosses
Though you may try, you will be no match for me.
To make a move you should enter a number: 0 - 8
The number corresponds to a bo... |
# loop with a string
word = input("Enter a word: ")
print("\nHere is each letter: ")
for letter in word:
print(letter)
number = input("Enter a number: ")
print("\nHere is each number: ")
for integer in number:
print(integer)
input("\nexit")
|
# constants
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
# instructions
def display_instruct():
"""Display game instructions"""
print(
"""
'Prepare yourself. I am the master of Noughts and Crosses
Though you may try, you will be no match for me.'
... |
"""#a is a variale that contain value.
a = "Hello world"
#print a
print(a)"""
# hello world using class
class Myclass(object):#object is optional
def show(self):#self is a variable.
print("Hello world")
#x is object
x = Myclass()
x.show()
|
# COMP9021 19T3 - Rachid Hamadi
# Quiz 3 *** Due Thursday Week 4
# Reading the number written in base 8 from right to left,
# keeping the leading 0's, if any:
# 0: move N 1: move NE 2: move E 3: move SE
# 4: move S 5: move SW 6: move W 7: move NW
#
# We start from a position that is the unique p... |
class Employee:
company = "vinsys"
def __init__(self):#superficial constructor
print("I was initialized....")
print(self)
def __del__(self):#superficial destructor
print("Destructor called")
def calculatetax(self):
print ("calculating tax")
#def checkpasswd(self):
# if self.username == "Abhishek":
# pri... |
#! /usr/bin/python
from datetime import datetime, timedelta
import datetime
import calendar
#comments
# print on console
print "Hello Wolrd"
# if elif else
# conditinoal statment
a = "HELLO"
if a == "hello":
print "a has lowercase"
print a
elif a == "HELLO":
print "a has all caps"
else :
print "bad bad ba... |
#decorators takes a function (as a funciton argument) and add soem "decoration" then return it
# decorating functions/outermost function, accecpts function pointer(first class function) as an argument
# This first class function will be used in inner functions and invoked from this inner function
#But in closures, bo... |
#!/usr/bin/python
from math import sqrt
for n in range(80, 5, -1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it!" |
# -*- coding: UTF-8 -*-
# filename: menushow.py
# verson 1.0
# 2016.10.24 by HanPengfei
def menushow(fathermenu, menucount = 1):
"""
This is a module that provides the display menu,
you shoule give me the fathermenu'name and menucount,
or default menucount is 1
"""
index = 0
max_count = int... |
import random
pickList = []
randomNum = random.randint(1,46)
userInput = int((input("How many picks:")))
while True:
for i in range(userInput):
pickList.append(randomNum)
if randomNum not in pickList:
continue
else:
pickList.append(randomNum)
break
print... |
#
# Queue implementation with 2 Stacks
# A queue is a list where items are added and
# removed from opposite sites
#
# A queue implements following operations:
#
# add(item): Add an item to the end of the list
# remove(): Remove the first item in the list
# peek(): Return top of the queue
# isEmpty(): Return true iff ... |
'''
Exemplos While
Rafael Alves
05/04/2021 - Senai - Jaguariúna - SP
'''
'''
n = 5
while n > 0:
if n > 1:
print('Fail error: n maior que 1')
else:
print('Fail error: n menor que 1')
print(n)
n -= 1
print('fogo!')
'''
'''
a = 1
b = 1000
while a!=b:
print('Rafael: '+str(a))
a ... |
'''
Exemplos String
Rafael Alves
05/04/2021 - Senai - Jaguariúna - SP
'''
#print('SENAI' == 'ETEC')
#print('SENAI' > 'ETEC')
#print('SENAI' != 'SENAI')
# Concatenar
#print('SENAI'+'Jaguariúna\t'+'SP')
#print('SENAI\n'*4)
#Indexação
#varStr = "Jaguariúna"
#print(varStr[3] + ' - '+ varStr[-7])
'''
num = 30563
num ... |
import numpy
# Matrix Transpose
m = numpy.mat([[1, 2], [3, 4], [5, 6]])
print("Original matrix\n", m)
print("Transposed matrix:\n", m.T)
|
#! /usr/bin/python
# A program to count the lines of a python program
# mcb3k with help from alm4x 4.2.2k11 v0.6
# Goal: by v1.0, count all logic lines, or all phys. lines, user's choice
def physLineCounter(pyScript):
"""takes a python script and returns a list of physical lines of code, i... |
list_one = [-423, 'Eye', 'sigh', 'Profession', 'Go', 'occupy', -51, 21, -345, 74, 'undertake', 'tiptoe', 11, -475,
'swipe', 'Burial', 280, 343, 218, 'general']
list_two = ['Conductor', -494, 'Difficulty', -234, -325, -466, 'loot', 457, 'blast', 'equal', -387, 'Bless', 'Candle',
'extinct', 495, '... |
"""
Program is driven by a menu that allows users
the ability to add/delete items based on calendar events
The events will be sortable by date
"""
import json
from datetime import datetime
running = True
def menu():
# Choose Number
print("""
-==Menu==-
1.) Create
2.) Delete
3.) Search
4.) Display
5.) Quit
"... |
def main():
#escribe tu código abajo de esta línea
num=0
total=0
cantidad=0
while num>=0:
num=float(input())
total=total+num
cantidad+=1
else:
total= (total-num)/(cantidad-1)
print(total)
if __name__=='__main__':
main()
|
def adjacent(position):
x, y = position
return (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)
def explore(position, walls, keys, doors, gainedKeys, openedDoors):
options = []
explored = {}
queue = [(position, 0)]
while len(queue) > 0:
p, step = queue.pop()
step += 1
for... |
def main():
#f = open("textfile.txt", "w+") # create and write
#f = open("textfile.txt", "a") #appends
#for i in range(10):
# f.write("Thia ia line " + str(i) + "\r\n")
f = open("textfile.txt", "r") # reads file
if f.mode == 'r':
#contents = f.read()
fl... |
"""
import matplotlib.pyplot as plt
#%matplotlib inline # con esto solo es necesario imprimir y omites el show()
gastos = [50,120,80,95]
meses = ["enero", "febrero", "marzo", "Abril"]
mapeo = range(len(meses))
plt.plot(gastos)
plt.xticks(mapeo,meses)
print(list(mapeo))
plt.show() # si no pones la clausula debes escr... |
try:
seleccion =input("""\nMenu
1.Suma de dos numeros
2. Resta de dos numeros
3. Multiplicacion de los dos numeros
seleccion:
""")
if seleccion == 1:
num1 = int(input("Ingresa primer numero: "))
num2 = int(input("Ingresa segundo numero: "))
resultado = num1 + num2
... |
"""
while True:
try:
n = input("Introduce un numero: ")
5/n
except Exception as e:
print("ha ocurrido un error ", type(e).__name__)
"""
"""
def mi_funcion(algo=None):
try:
if algo is None:
raise ValueError("error no se permite un valor nulo")
except ValueErr... |
"""
#ARCHIVOS PLANOS
#1 READLINE()
from io import open
fichero= open('fichero.txt','r')
texto = fichero.readlines()
fichero.close()
print(texto)
#2 WITH DE MANERA AUTOMATICA,
with open ("fichero.txt","r") as fichero:
for linea in fichero:
print(linea)
#APPEND
fichero = open('fichero.txt', "a")
fichero.wri... |
print("-----F L A M E S-----")
name1 = input('Enter your name: ').lower().replace(" ","").replace(".","")
name2 = input('Enter your partner\'s name: ').lower().replace(" ","").replace(".","")
def flames(name1, name2):
n1 = sum(letter in name2 for letter in name1)
n2 = sum(letter in name1 for letter in name2)
... |
# Import the pygame library
import pygame
import math
# Initialize the game engine
pygame.init()
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Dimensions
dimensions = (700, 500)
screen = pygame.display.set_mode(dimensions)
# Window title
pygame.display.set_caption("Kath ... |
# coding: utf-8
# # 4.1 선형대수
# In[1]:
height_weight_age = [70,170,40]
grades = [95,80,75,62]
# In[4]:
def vector_add(v,w):
return [v_i + w_i for v_i,w_i in zip(v,w)]
def vector_subtract(v,w):
return [v_i - w_i for v_i,w_i in zip(v,w)]
# In[7]:
def vector_sum(vectors):
result = vecotrs[0]
f... |
from PIL import Image, ImageDraw
name=''
img = Image.new("RGB", (300, 1320))
img1 = ImageDraw.Draw(img)
pos=(0,0)
def printTable(table,iteration):
global name
# img = Image.new("RGB", (1500, 330))
# img1 = ImageDraw.Draw(img)
global img1
global pos
img1.rectangle([pos,(pos[0]+300,pos[1]+30)]... |
def func(a):
print (a+2)
return a+2
x=1
print(x+1)
y=str(x)+'1'
print(y)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.