text
stringlengths
37
1.41M
new_dictionary = {"name": "Bob", "age": "43", "weight": "150"} name_list = ["Thomas", "Richard", "Harold"] def add_list(n): """ Can a list be held within a dictionary as a value? Arg: n(lst): A list that will be added to the dictionary. Return: Return and print a dictionar...
from os import listdir from os.path import isfile def question01(): """How do I print all the files in a directory?""" print("Question 1: How do I print all the files in a directory?") path = "../" for item in listdir(path): # directories will be printed without this conditional if i...
#!/usr/bin/env python # Import the modules needed to run the script. import sys import os import time # Main definition - constants menu_actions = {} # ====================== # MAILROOM MADNESS # ======================= # It should have a data structure that holds a list of your donors and # a history of the amount...
#!/usr/bin/env python from __future__ import print_function fruits = [] def display(l): """ Display a list as a formatted string. Args: l: the list to be displayed. """ list_str = ', '.join(l) print('\n' + list_str) def series_1(): """First series""" global fruits fru...
"""When manually iterating over an object, is it possible to view the current value of your index? """ wallet = [100, 98, 87, 25, 4, 0] iterWallet = iter(wallet) next(iterWallet) # 100 iterWallet.next() # 98 next(iterWallet) # 87 """How is "return" different from "yield"?""" def wallet1(spent): money = 100 mo...
def finally_vs_else(): """ When might you use finally vs. else in an try block?""" print("Case 1 finally with a faliure in the try block") try: if 'cows' & 'cows': print ("Success!") except: print("This Failed") finally: print("This will happen no matter what goe...
# Paths (1 question) # Question 1 import os def read_a_file(): """ How do you view a list of all the files in a directory? Result: Prints files in that directory. """ file_path = "~/Desktop" files_and_dirs = os.listdir(file_path) for files in files_and_dirs: print files
# Is your name on the list? def check_list(name): """ Print whether name is or is not on the roster. Args: string: name of person to be checked Return: prints result if person is on the list or not. """ roster = [u"Earl", u"Russell", u"Richard", u"Kam", u"Bruce"] roster_che...
#!/usr/bin/env python def main(): fruits_list = ['Apples', 'Pears', 'Oranges', 'Peaches'] print fruits_list add_fruit = raw_input(u'what fruit do you want to add to ' 'the end of the list? ') fruits_list.append(add_fruit) print fruits_list user_has_answer = False ...
# File Reading and Writing (2 questions) # Question 1 import io def read_a_file(): """ How do I read a file? Result: The file is printed. """ examine_file = io.open('file_name.txt', encoding='utf-8') file_data = examine_file() examine_file.close() print(file_data) read_a_fil...
s = "Do something every day that you dont want to do" def file_exception(x): '''function definition: This function answers the question is my file and if so what some of its contents. If it exists show me the beginning of the file arguments: a file''' try: header_size = 4096 f = open(x) ...
""" 1. in the update function, use a loops to decrease the y positions by 1. To modify list values, you must use square-bracket notation with the index location. eg. 'my list location' """ import random import arcade WIDTH = 650 HEIGHT = 480 star_x_positions = [] star_y_positions = [] for star in range(50): x =...
import streamlit as st import numpy as np import pandas as pd import json import pickle import reference_book as rb def main(): model = load_data() st.title('Questionario - Open Sex Role Inventory') st.text( """ Olá, bem vindo! Este questionario foi baseado em u...
def findPrime(n): count = 0 for num in range(n): if num > 1: for i in range(2, n): if (num % i) == 0: break else: count += 1 print(i, count) findPrime(10)
import numpy as np a = np.arange(1, 101) print(a[::-1]) #reverse Order print(a[3:7]) print(a[7::-1]) #reverse from a Specific Point b = a.reshape(2,5,10) #print(b) #print(b[1], end="") print(b[1, 3, 5:3:-1])
import math def move(): text = input("enter move e.g. UP 5:").split(' ') print (text) str = text[0].upper() displacement = int(text[1]) if (str == "UP"): return (0, displacement) elif (str == "DOWN"): return (0, -1 * displacement) elif (str == "RIGHT"): return (displ...
""" Group: ---> (Alexander Rzehak, Aydeniz Soezbilir) <--- Your tasks: - Fill in your names. - Complete the methods at the marked code blocks. - Please comment on the most important places. Test your implementation at least with: perceptron.py orinput.txt oroutput.txt 1000 0.001 perceptron.py xorinput.txt xo...
import re def mot_correspondant(mot:str,motif:str)->bool: """[summary] verifie si un motif et present dans mot Args: mot (str):mot fournit motif (str): motif peux contenir des jokers (.) Returns: bool: True si motif present False sinon """ correspond = False if re.matc...
import random def guess(x): random_number = random.randint(1, x) # once the computer has selected a number, now we need to guess guess = 0 # we don't want our guess to initialize the variable # to something that could be the random number. # otherwise, the game would be ov...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Programa que busca integrar la ecuacion de poisson en 2D ''' # librerias from __future__ import division import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d # funciones estructurales def r(i, j, Lx, Ly, h): x = i * h - Lx...
x = int(input("What year do you want to start with?: ")) n = int(input("How many years do you want to check?: ")) for x in range(x,x+n): if x%4 == 0 and x%100 != 0 or x%400 == 0: print(x, "is a leap year") elif x%4 != 0: print(x, "is not a leap year") # If a year is divisible by 4, not di...
import math P = (int(input("Enter the amount you would like to deposit: "))) i = (int(input("Enter the interest rate: "))) t = (int(input("Enter the number of years of the interest rate: "))) r = float(i / 100) interest = input("Do you want simple or compound interest?: ") CI = P*pow((1+r),t) CI = float(round(CI,2)) ...
string = 'i hope this is correct' for letter in 'hptse': #letters I want to delete string = string.replace(letter, '') #replace these letters with nothing i.e. remove them print(string)
class HashTable: def __init__(self, txt_name): self.ht = set() self.read_txt(txt_name) self.counts = 0 def read_txt(self, txt_name): """ read txt and store it in a hash table (set) """ with open(txt_name) as f: for line in f: ...
import heapq class MinimumSpanningTree: def __init__(self, txt_name): self.v_cv = {} self.n = 0 self.read_txt(txt_name) def read_txt(self, txt_name): """ read txt and store it in a heap """ with open(txt_name) as f: first_line = f.readlin...
import math def test_if_prime(x): # Returns True if x is a prime number. result = True for i in range(2,math.ceil(x/2)+1): if x%i==0: result = False break return result def next_prime_number(x): # Finds the next prime number that comes after x. x doesn't have to be ...
from Graph import * import unittest """ Node attributes: key (unique) value = None parent = None searchStatus = "undiscovered" distance = math.inf discoveryTime = math.inf finishTime = math.inf Graph attributes: adjacencyMap --> dictionary of the form adjacencyMap[key] = {adjacent keys}. valueMap ------> defaultdic...
from termcolor import colored import sys def del_repeate(text): cut_txt = '' for i in text: if i not in cut_txt and i != ' ': cut_txt += i elif i == 'J' and 'I' not in cut_txt: cut_txt += 'I' print(colored("Short form: ", 'magenta', attrs=['bold']) + colored(cut_...
class BasketballPlayer(): def __init__(self, first_name, last_name, height_cm, weight_kg, points, rebounds, assists): self.first_name = first_name self.last_name = last_name self.height_cm = height_cm self.weight_kg = weight_kg self.points = points self.rebounds = reb...
d1 = {2:3, 8:19, 6:4, 5:12} d2 = {2:5, 4:3, 3:9} d3 = {} for k1 in d1.keys(): if not k1 in d2.keys(): d3[k1] = d1[k1] for k2 in d2.keys(): if not k2 in d1.keys(): d3[k2] = d2[k2] print(d3)
# -*- coding: utf-8 -*- """ Created on Sat Nov 02 14:23:10 2013 @author: 子怿 """ def Listrank(L): length = len(L) for i in xrange(length): for j in xrange(i+1,length): if L[i]>L[j]: L[i],L[j] = L[j],L[i] return L L = [3,7,1,99] print Listrank(L)
# -*- coding: utf-8 -*- """ Created on Sat Nov 02 18:29:09 2013 @author: 子怿 """ def Xulie(L): up = sorted(L) down = sorted(L,reverse=True) if L == up: print "UP" elif L == down: print "DOWN" else: print "WRONG" Xulie([2,3,4,5])
#!/usr/bin/env python # coding: utf-8 # In[1]: color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] color = [x for (i,x) in enumerate(color) if i not in (0,4,5)] print(color) # In[ ]:
import random #Random Library def homophonic_encrypt(): print("You are going to encrypt a plaintext using a homophonic cipher") message = input("Please enter a message: ") encrypted_message = "" for x in message: if x == " ": encrypted_message += " " continue ...
Variable uses by type and meaning type <string> = a,b,s a = "Well, Shankar always have a story to tell!" type <int> = i,j,k,l,m,n,num type <list> = alpha, beta, gamma Input commands >>> a = input() #it always takes a string as an input but rest depends on you how to manupulate it >>> i = int(input(...
try: f = open("file.txt") except FileNotFoundError: print ("Sorry") except Exception: print ("something wrong") else: print ("in else") finally: print ("final act")
# 標準入力から、2次元リストを読み込む # 標準入力のデータ # 0,0,1,1,0,0 # 0,1,0,0,1,0 # 1,0,0,0,0,1 # 1,1,1,1,1,1 # 1,0,0,0,0,1 # 1,0,0,0,0,1 # _ letter_A = [] while True: line = input() if line == "_": break # ここに、読み込んだデータをリストに追加するコードを記述する letter_A.append(line) print(letter_A)
# 標準入力から、2次元リストを読み込む # 標準入力のデータ # 0,0,1,1,0,0 # 0,1,0,0,1,0 # 1,0,0,0,0,1 # 1,1,1,1,1,1 # 1,0,0,0,0,1 # 1,0,0,0,0,1 # _ letter_A = [] while True: line = input() if line == "_": break # ここに、読み込んだデータをリストに追加するコードを記述する letter_A.append(line) print(letter_A)
class student : def __init__(self): self.new_student = [] def add_data(self): self.new_student.append(input("학과: ")) self.new_student.append(input("학번: ")) self.new_student.append(input("이름: ")) self.new_student.append(int(input("국어: "))) self.new_st...
import json import sys print ("Hello Drew") filename = sys.argv[1] with open(filename) as infile: spelling_words = json.load(infile) prompt_1 = "Please guess the spelling: " # check user guess def get_user_guess(meaning, prompt): print (meaning) user_guess = input(prompt) return user_gue...
# ## python --version -> Python 2.7.10 # import math def move(max, current, direction): if direction > 0: if current < max: return current + 1 elif current == max: return 1 else: if current == 1: return max elif current > 1: return current - 1 inputs = raw_input().strip()....
# Filter out the string which its length less than 3 names = ['Bob','Tom','alice','Jerry','Wendy','Smith'] names = [name for name in names if len(name) > 3] # Get all combinations (x, y), which x and y are both in 0 - 9, but x is an even number, y is an odd number. [(x, y) for x in range(10) if x % 2 == 0 for y in r...
# Source - http://stackoverflow.com/a/20465181 def isqrt(n): x = n y = (x + n // x) // 2 while y < x: x = y y = (x + n // x) // 2 return x def fermat(n): a = isqrt(n) b2 = a*a - n b = isqrt(n) count = 0 while b*b != b2: a = a + 1 b2 = a*a - n ...
# -*- coding: utf-8 -*- """ Created on Mon Oct 19 20:01:36 2020 @author: Iris """ ''' a, b, *c = range(1, 10) print(a, b, c) a, b, c = [1, 10, 100] print(a, b, c) a, *b, c = 'hello' print(a, b, c) a = 1 b = 2 c = 3 d = 4 d,c,b,a = a,b,c,d print(a,b,c,d) ''' def find_max_and_min(items): """找出列表中最大和最小的元素 :p...
lista = [] n = input("Ingrese el largo de la lista: ") for i in range(0,n): if(i%3==0) & (i%7==0): lista.append(i) print lista
# -*- coding: utf-8 -*- import weakref class FloatVar(float): """A float holding information about its source. FloatVar instances are usually created by accessing a range variable from a mechanism. The FloatVar can be used immediately as a float giving the value of the referenced variable, or it...
# Given an array of integers, every element appears twice except for one. Find that single one. # # Note: # Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? # class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 20 16:58:03 2020 @author: avmejia """ def calculo(x, y): z = x + y return z def main(): p = 5 q = 2 r = 10 r = calculo(p,q) print(r) main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 20 17:00:34 2020 @author: avmejia """ def func1 (a, b): print(a, b) def func2 (x, y): x = 10 y *= 2 func1 (y, x) def main() : p = 2 q = 3 func2(p, q) func1(p, q) main()
class ShoppingCart(object): """Create shopping cart object for website users""" items_in_cart = {'mango': 0, 'apple': 0, 'pear': 0, 'banana':0 } items_price = {'mango': 3, 'apple': 2, 'pear': 2, '...
num = 1 soma = 0 while num < 501: if num % 2 == 0: soma = soma + num print('A soma é {}'.format(soma)) num+= 1
valor = float(input("Digite o valor da compra: ")) taxa = float(input("Digite o valor da taxa: ")) tempo = float(input("Quanto tempo você atrasou: ")) press = valor + (valor * (taxa/100) * tempo) print("O valor da prestação é {}".format(press))
vetorA = [1,1,1,1,1,1,1,1] vetorB = [1,1,1,1,1,1,1,1] for x in range(0, 8, 1): vetorA[x] = int(input("Digite um número: ")) vetorB[x] = vetorA[x] * 3 for x in range(0, 8, 1): print(f'Indice {x} -> vetorA = {vetorA[x]} = vetorB = {vetorB[x]}')
alt = float(input("Qual a altura da lata: ")) raio = float(input("Qual o raio da lata: ")) vol = 3.1415 * pow(raio, 2) * alt print("o volume da lata é {}".format(2))
sm = float(input("Informe o seu salário: ")) pr = float(input("Informe a taxa de acréscimo: ")) ns = sm * pr / (100) print('O acréscimo será de R$ %.2f'%ns) print('O novo salário será R$ %.2f'%(sm + ns))
alt = float(input("Qual a altura da caixa: ")) lar = float(input("Qual a largura da caixa: ")) comp = float(input("Qual o comprimento da caixa: ")) vol = comp * lar * alt print('O volume da caixa é {}'.format(vol))
import turtle tina= turtle.Turtle() r = 100 gap = 10 tina.pensize(5) tina.pencolor("#663300") tina.fillcolor("#666600") tina.begin_fill() while r > 0: tina.circle (r,360) r = r - gap tina.penup() tina.setheading(90) tina.forward(gap) tina.setheading(0) tina.pendown() tina.end_fill() tina.hi...
import turtle tina= turtle.Turtle() tina.pensize(10) tina.pencolor("#ff6600") tina.circle (100,360) tina.penup() tina.goto(0,100) tina.pendown() tina.setheading(90) tina.pencolor("#ffffff") tina.fillcolor("#ff9900") for i in range(0, 8, 1): tina.begin_fill() tina.backward(90) tina.right(90) tina.circle...
from tkinter import * from tkinter import messagebox as mb def crt(hos): if hos.max_patients==0: mb.showerror("!! ALERT !!", "Sorry, no beds available please!! go to another hospital!!") return global x,y,z,q,m,w,v def write(): count = 0 j =[] j.append(w.g...
class homework(): def gas(self): i=1 miles=gass=0.0 print("输入0退出程序哟亲~") while 1: mile=input("输入第"+i+"个英里") gas=input("输入第"+i+"个油") if gas==0 or mile==0: break miles+=mile gass+=gas ave=mil...
a=(1,2,3,4,5)#元组 不可更改 print(a) zidian={'IP':'8.8.8.8','name':'google','place':'USA'} print(zidian) del zidian['place'] print(zidian) print(zidian.pop('name'))#输出并删除某个键 zidian['place']='Hong Kong'#添加键位和内容 print(zidian['IP']) print(zidian.get('IP')) print(zidian.get('name','404'))#若没有name,就返回404 import rando...
car={'name':'BMW','price':'100','place':'china'} print(car) print(car['name'])#输出对应键位的值 del car['price']#删除价格 print(car) #长字典 language={ 'tom':'java', 'joho':'C艹', 'trump':'python' } print('tom最爱的语言是:'+language['tom'].title())# title可以使第一个字母大写 for name in language.keys():#只输出键名 print(name...
print('摄氏度是{:.2f}'.format(( int(input('华氏度是?'))-32)*5/9)) print('最小值是{}'.format(min([int(n) for n in input().split()]))) print(sorted([int(n) for n in input().split()])) print(sum (1/i for i in range(1,int(input("算几个数?")))))
def paixu(list1,k): l1=list1[:k] l2=list1[k:] t1=l1.reverse() t2=l2.reverse() l=l1+l2 #l成功生成 l.reverse()#不能直接print print(l) #正确的简约切片法 def pai(lst,k): l=lst[k:]+lst[:k] return l print('正确:',pai([1,2,3,4,5,6,7,8],3)) paixu([1,2,3,4,5,6,7,8],3)
#Ai核心代码,估值俩亿~ while 1: print(input('').replace('吗','').replace('?','!').replace('你','我')) print('----------------')
#!/bin/python3 import math import os import random import re import sys from collections import Counter # # Complete the 'sockMerchant' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER n # 2. INTEGER_ARRAY ar # def sockMe...
import matplotlib.pyplot as plt x_values = range(1, 1001) y_values = [x**2 for x in x_values] plt.style.use('seaborn') fig, ax = plt.subplots() ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Reds, s=10) ax.set_title("Square Numbers", fontsize=24) ax.set_xlabel("Value", fontsize=14) ax.set_ylabel("Square of ...
def fibonacci(second_last, last): next_num = second_last + last return next_num def call_fib(): even_fib_numbers = [2] second_last = 1 last = 2 fib_number = 0 while fib_number < 4000000: fib_number = fibonacci(second_last, last) if fib_number%2==0: even_fib_nu...
import sys import random import argparse def input_file(file_name): """File acronyms to be read from""" try: with open(file_name) as fo: acronyms = fo.read().splitlines() except(FileNotFoundError) as err: print( "File: \"{0}\" not found.\nExiting with error: \n{1}\n...
import numpy as np import pandas as pd def append_intercept(X: pd.DataFrame) -> pd.DataFrame: """ Append a column of ones to the beginning of the dataset. Parameters ---------- X : pd.DataFrame Observed features data Returns ------- pd.DataFrame Design matrix """ ...
import pygame from utils import make_grid, Node, get_clicked_pos, draw from algorithm import aStar_algorithm, Dijkstra_algorithm, generate_walls, bfs from pygame_widgets import Button, Slider, TextBox, ButtonArray import time import webbrowser # INIT THE PYGAME WINDOW pygame.init() WIDTH = 600 WIN = pygame.display.se...
import re token = r"\[\]" line = "[]" if re.match(token, line): print("ok") pattern = re.compile(token, re.IGNORECASE) tokens = pattern.findall(line) print(tokens) else: print("not valid")
class xrange(object): def __init__(self, *args): self.arguments = args self.range = [] for i in self.gene(*args): self.range.append(i) self.current = 0 def __next__(self): self.current += 1 return self.range[self.cu...
# 4. Написать программу для вычисления пересечения двух списков. Например, А=[1,2,4,5], B=[3,4,5], то А В=[4,5]. astr = input("input a (ex. 1,2,4,5)\n").split(",") a = [] for i in astr: a.append(int(i)) bstr = input("input b (ex. 3,4,5)\n").split(",") b = [] for i in bstr: b.append(int(i)) print(set(a).int...
# Le joueur humain joue par inputs dans la console pour l'instant, a terme on remplacera les inputs par des clics ( partie graphique ) from joueur import joueur class joueur_humain(joueur): def __init__(self,nom): joueur.__init__(self,nom) self.type="humain" def joue_une_carte(self,cartes...
from Particle import Particle class Partition : threshold = 5 def __init__(self, index = (0,0)) -> None: self.index = index self.particle_list = [] def num_particles(self): return len(self.particle_list) def add_particle(self, p = Particle()): self.particle_list.appen...
dir_list = ["NORTH", "SOUTH", "EAST", "WEST"] class InputError(Exception): pass class ToyRobot: def __init__(self, x=0, y=0, direction="NORTH"): self.x = x self.y = y self.direction = direction def place(self, input_x, input_y, input_direction): if input_x in range(5) an...
# 3D Rotation Matrix in the y direction taking an array of size 3 import numpy as np def rot3y(coor, th): # The rotation matrix itself rott = np.array([[np.cos(th), 0, np.sin(th)], [0, 1, 0], [-np.sin(th), 0, np.cos(th)]]) coor = coor[:,np.newaxis] # Make the shape vertical coor...
print("==================================================================================") print("Inverte uma sequencia de números de uma lista") print("==================================================================================") print("Esse programa imprime uma sequencia de números com final 0") print...
# a = int(input('Entre com um valor: ')) # for num in range (a+1): # div = 0 # for x in range (1, num +1): # resto = num % x # if resto ==0: # div += 1 # if div == 2: # print(num) pri = int(input('Primeiro bimestre: ')) while pri > 10: pri = int(input('Vo...
#coding:utf8 #exo1: #display "hello world" in terminal print("Hello world") #display "hello world" in terminal with variable bruno="Hello world" print(bruno) #exo2: #display result of arithmitiques operations print("res_mulication:",3*3,"res_addition:",4+9+78,"res_substraction:",12-7,"res_power:",5e4) try: print("...
#coding:utf8 import timeit import numpy as np times = 10000 size = 1000 np_ary = np.array(list(range(size))) ary = list(range(size)) def for_each_np_ary(): ret = 0 for v in np_ary: ret += v return ret def for_each_ary(): ret = 0 for v in ary: ret += v return ret print('A...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } #weekdaysand month_name added to turn weekdayand month numbers into names weekdays={0:'monday',1:'tuesday',2:'wednesday',3:'thur...
def Merge(A, B): C = A + B for i in range(len(C) - 1): while C[i] > C[i + 1]: C[i], C[i + 1] = C[i + 1], C[i] return C a = list(map(int, input().split())) b = list(map(int, input().split())) print(' '.join(map(str, Merge(a, b)))) # Даны два целочисленных списка A и B, упор...
def dist(point): return point[0] ** 2 + point[1] ** 2 n = int(input()) points = [] for i in range(n): point = tuple(map(int, input().split())) points.append(point) print(' '.join(map(str, points))) points.sort(key=dist) for point in points: print(' '.join(map(str, point))) # В качестве ...
a = int(input('Vvedite chislo: ')) count = 1 countMax = 0 while a!= 0: b = a a = int(input('Vvedite chislo: ')) if a == b: count += 1 if count > countMax: countMax = count else: count = 1 print(countMax)
# CS3210 - Principles of Programming Languages - Fall 2019 # A Lexical Analyzer for an expression from enum import Enum import sys # all char classes class CharClass(Enum): EOF = 1 LETTER = 2 DIGIT = 3 OPERATOR = 4 PUNCTUATOR = 5 QUOTE = 6 BLANK = 7 OTHER ...
#ASSIGNMENT 6 #1.TAKE 10 INTEGERS FROM USER AND PRINT IT ON SCREEN. for n in range(0,10): n=print(int(input("enter the integers:"))) print(n) #2.write an infinite loop. Infinite loop never ends. condition always true. i=1 while i<10: print("hello world") print(i) i=1 while i!=-1: print("hello world") print(i) ...
##(ROCK,PAPER,SCISSORS) GAME #import the module from random import randint #create a list list = ["Rock", "Paper", "Scissors"] system = list[randint(0,2)] #welcoming the user. print(''' ************************************** Welcome to (ROCK,PAPER, SCISSORS) game **********...
#A simple project on Morse code translation from plain Text to morse code and vice versa #Importing the user defined modules import encryption as cipher import decryption as decipher print("\t\t\t\t***********************") print("\t\t\t\t THIS IS MORSE CODE TRANSLATOR ") print("\t\t\t\t***...
class ShopList: def __init__(self, grocery_store): self.grocery_store = grocery_store self.groceriesf = [] self.groceriesw = [] self.groceriess = [] def add(self, item): self.groceriesf.append(item) def add2(self, item): self.groceriesw...
import numpy as np a = np.arange(12).reshape(-1,4) print(a) #a배열과동일한 shape의 배열을 생성하고 0으로 채워주세요. b = np.zeros_like(a) c = np.zeros(a.shape, dtype="int32") print(b) print(c) #print(np.max(a)) #print(np.max(a,axis=0)) #print(np.max(a,axis=1))
#!/usr/bin/env python """ Print a random password of 10 characters. """ from random import Random import sys # No i 1 o 0 l ALPHABET = 'qwertyupasdfghjkzxcvbnmQWERTYUPASDFHJKLZXCVBNM2345789' # 10 characters or the argument in parameter: RESULT_LEN = int((sys.argv[1:2] or [10])[0]) def has_digit(sequence): """ ...
# -*- coding: utf-8 -*- import array class Fibonacci(): """This class creates the fibonacci series upto the certain input limit (i.e. numCount), which controls the length of output array. Syntax Example: fibo = Fibonacci() x = 20; #value 20 to get first 20 numbers of fibonacci ...
#Print the numbers from 1 to 5, it doesn't print the number 5 for value in range(1,5): print(value) print("----") #Print the numbes from 1 to 6, it doesn't print the number6 for value in range(1,6): print(value) print("----") #Using range() to make a list of numbers """ To make a list of numb...
""" because a function definition can have multiple parameter, a function call may need multiple arguments positional arguments: which need to be in the same order the parameters were written keyword arguments: each argument consists of a variable name and a value """ #python must match each argument in the function ...
#using a while loop with lists and dictionaries """ a for loop is effective for looping through a list, but you shouldn't modify a list inside a for loop ecause python will have trouble keeping track of the items in the list. To modify a list as you work through it, use a while loop. while loops with lists and dictiona...
#upper case cars=['audi','bmw','subaru','toyota'] for car in cars: if car=="bmw": print(car.upper()) else: print(car.title()) print('----') """ Conditional tests if statement is an expression that can be evaluated as True or False and is called a conditional test. """ #this eq...
height=input("How takk are you, in inches? ") height=int(height) #compare height to 36 bc height=int(height)converts numerical value if height >= 36: print("\nYou're tall enough to ride!") else: print("'\nYou'll be able to ride when you're a little older.") """ when you use numerical input to do calculati...
my_foods=['pizza','falafel','carrot cake'] #make a new list called friend_foods friend_foods=my_foods[:] print("My favorite foods are: ",my_foods) print("\nMy friend's favorite foods are:",friend_foods) print("----") #add a new food to each list #add cannoli to my_foods my_foods.append('cannoli') #add ice ...