text
stringlengths
37
1.41M
#!/usr/bin/env python2 # upi: mbea966 # name: Madeleine Beagley import glob import os import sys # extract filename from command line input if (len(sys.argv) == 2): filename = sys.argv[1] else : print 'Enter a single filename as input' exit() versionPath = os.getcwd() + '/.versiondir/.' + filename # fi...
Val=(input("Your name: ")) days=int(input("No of Days you were present: ")) desig=input("What is your designation? ") select_month=input("Enter the desired Month: ") month = {"jan":31, "feb":29, "march":31, "apr":30, "may":31, "jun":30, "jul":31, "aug":31, "sep":30, "oct":31, "nov":30, "dec":31} fee = 0 if de...
A, B, C = [float(i) for i in input().split()] areaTriangulo = (A * C) / 2 areaCirculo = 3.14159 * (C ** 2) areaTrapezio = ((A + B) * C) / 2 areaQuadrado = B ** 2 areaRetangulo = A * B print("TRIANGULO: {0:.3f}".format(areaTriangulo)) print("CIRCULO: {0:.3f}".format(areaCirculo)) print("TRAPEZIO: {0:.3f}".format(areaT...
def classifica_ponto(ponto: list): if ponto[0] > 0: if ponto[1] > 0: print("Q1") elif ponto[1] < 0: print("Q4") else: print("Eixo X") elif ponto[0] < 0: if ponto[1] > 0: print("Q2") elif ponto[1] < 0: print("Q3")...
a = int(input("ingrese num: ")) b = int(input("ingrese otro num: ")) c = a-b print(c)
import random spisok = [random.randint(0,10) for i in range(10)] print(spisok) iskaemoe = int(input("Введите искаемое число: ")) indeks = spisok.index(iskaemoe) print("Число " + str(iskaemoe) + " в списке под номером " + str(indeks))
from random import shuffle def makeBoard(): K1=[[9,4,3,1,2,7,8,6,5], [1,2,7,6,5,8,3,9,4], [5,6,8,3,4,9,7,2,1]] K2=[[7,5,2,4,3,1,9,8,6], [6,3,9,2,8,5,1,4,7], [4,8,1,7,9,6,5,3,2]] K3=[[8,1,4,9,7,2,6,5,3], [2,9,6,5,1,3,4,7,8], [3,7,5,8,6,4,2,1,9]] shuffl...
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that perso...
import json #from matplotlib import pylab #from pylab import * from urllib2 import urlopen, Request from urllib import urlencode import time import os.path import requests class Photon: """A particle object belongs to a class developed to help you communicate to your photon in the wild. Each photon has two attribu...
# import the random package so that we can generate a from random import randint #set up some variables for player and AI lives player_lives = 5 computer_lives = 5 # choices is an array is a container that can hold multiple values choices = ["rock", "paper", "scissors"] # set the computer variable to one of these c...
""" wizard.py wizard mode for html_builder Russell Lee """ import site_generator from dataclasses import dataclass # FileParameters helps organize how to export the files @dataclass class FileParameters: mode: str settings: list title: str text: str number: str multi: list titles: list de...
from pymcutil.position.rc import RC from pymcutil.position.vector_3d import Vector3D class Position(Vector3D): """ Position AKA location representation containing x, y, z coordinates that may be relative. Note that all position operations are defined under the inherited Vector class, meaning we can convenient...
import abc from typing import Any class Serializable(abc.ABC): """ An object that can be serialized into a composition of basic values. """ @property @abc.abstractmethod def serialized(self) -> Any: """ Returns a serialized representation of the object. This *serialized representation* should...
#!/usr/bin/env python import string import keyword alphas = string.letters + '_' nums = string.digits print 'Testees must by at least 2 character long' myInput = raw_input('sample is: ') if len(myInput) > 1: if myInput[0] not in alphas: print 'first character must be alphabetic' else: for x in myI...
#!/usr/bin/env python ' readTextFile.py -- read text file' import os filename = raw_input('Enter file name: ') # open the file while True: if os.path.exists(filename): handler = open(filename, 'r') break else: print "file {0} does not exist".format(filename) for line in handler: ...
import sys if sys.version[0] != '2': print('please run all code with python2!') exit(0) import cv2 import numpy as np def stats(img): return {'mean': np.mean(img), 'std': np.std(img), 'max': np.max(img), 'min': np.min(img), 'size': img.shape, 'dtype': img.dtype } def imshow(title, image): cv2....
"""This module contains helper functions for ATS test module.""" import json def read_file(path_to_file): """Read file and return list.""" with open(path_to_file) as data_file: input_list = data_file.read().splitlines() # print data return input_list def append_protocol(url_to_test): ""...
# 练习1: 打印三角形 num = 10 index = 1 while index < num: stars = "*" * index print (stars) index += 1
# Your task is to convert a number into a string that contains raindrop sounds corresponding to certain potential # factors. A factor is a number that evenly divides into another number, leaving no remainder. The simplest way to # test if a one number is a factor of another is to use the modulo operation. # The rules ...
import pygame import math import random class Enemy: def __init__(self, x=0, y=0): self.enemyX = x self.enemyY = y self.create_enemy() def draw_player(self, enemyX, enemyY, enemyImg,screen): screen.blit(enemyImg, (enemyX, enemyY)) def create_enemy(self): # Enemy ...
import tensorflow as tf # CREATE TENSOR WITH tf.Variable() changeable_tensor = tf.Variable([1, 2]) unchangeable_tensor = tf.constant([1, 2]) print(changeable_tensor) print(unchangeable_tensor) # LET'S TRY CHANGING ONE OF OUR ELEMENTS IN CHANGEABLE TENSOR print(changeable_tensor[0]) # changeable_tensor[0] = ...
#!/usr/bin/python3 word = "Holberton" word_first = word[:3] word_last = word[-2:] middle_word = word[1:-1] print("First 3 letters: {}".format(word_first)) print("Last 2 letters: {}".format(word_last)) print("Middle word: {}".format(middle_word))
#Para declarar uma variável global dentro de function global variavel #Variável global f= 0 print(f) f = "abc" print(f) #Forma de Concatenar print("Isto é uma string " + str(123)) #Criar Função equivale ao método no c# #Variável local def PrimeiraFuncao(): global f f= "def" print(f) PrimeiraFuncao() ...
## O break interrompe a execução do loop def loopBreak(): for x in range(5, 10): if(x == 7): break print("o valor de x é : ", x) loopBreak() print() ## O Continue interrompe uma execução do loop e pula para o próximo item def loopContinue(): for x in range(5, 10): if(x == ...
for _ in range(int(input())): n=int(input()) s=str(n) if "21" in s or n%21==0: print("The streak is broken!") else: print("The streak lives still in our heart!")
import turtle def main(): window = turtle.Screen() Juan = turtle.Turtle() make_square(Juan) turtle.mainloop() def make_square(juan): length = int(input('Digite el tamaño del lado del cuadrado: ')) for i in range (4): make_line_and_turn(juan, length) def make_line_and_turn(juan, len...
# -*- coding: utf-8 -*- ''' list相关 元组 ''' L = ["Adam", 95.5, "Lisa", 85, "Bart", 59] print(L) L = [95.5, 85, 59] print(L[0]) print(L[1]) print(L[2]) print(L[-1]) L = ['Adam', 'Lisa', 'Bart'] L.insert(2, "Paul") print(L) # 插入 L = ['Adam', 'Lisa', 'Bart'] # 方法一 L.insert(2, 'Paul') print(L) # 移除首位 L = ['Adam', 'Lis...
# -*- coding: utf-8 -*- """ #格式化输出 print ('{} ({}<{})'.format(x,s,g)) '%s/%s' % (self.p, self.q) print("===") # https://www.runoob.com/python/python-strings.html print("\n".join("%s" % i for i in range(7, 101, 7))) =============================== 初识Python https://www.imooc.com/learn/177 简介:Python教程基础分《...
import numpy as np import pandas as pd df = pd.read_csv("God_Stats.csv", index_col = 0) def Level_Calc(x, y, z): a = x + y*z return a def Attack_Speed(x, y, z): a = x*(1 +((y/100)*z)) return a columns = ["Health", "Mana", "Pysical Prot", "Magical Prot", "MP5", "HP5", "Basic Attack D...
import random from functools import total_ordering @total_ordering class Player: def __init__(self, score, name): self.score = score self.playing = True self.name = name def player_is_valid(self, other): return hasattr(other, 'score') def __gt__(self, other): if ...
''' Created on 2020/05/16 @author: seal0 Find the worst combination of 2-approximate for Knapsack d: list of w/v. d is sorted from larger one. w: weight of a bag v: value of a bag Find proper d and w under the following constraints: out = v1+v2+...+vh opt = 2 * out To find such d and w, the bigges...
class Sale(): """This is the product model""" def __init__(self, item, price, amount_sold): self.item = item self.price = price self.amount_sold = amount_sold def make_dict(self,item_id): """receives the item as an object and turns it to a dict""" return dic...
from abc import * class AI: """ The base AI class. Entity classes inherit from this. Instantiated from it to make specific AIs Each subclass must have the following, or they can't be instan: react_attack() idle() attack() action() escape() on_discover...
#!/usr/bin/python a= int(input()) #get input from user for i in range(1,21): print("{0} * {1} = {2}" .format(a,i,(a * i))) #format to print
# Enter your answrs for chapter 6 here # Name: Aparna Sud # Ex. 6.6 def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] # If you call a string with 2 letters, 1 letter, or a blank string '', you get '' as an output because it reads the middle letter as blank ...
import requests from bs4 import BeautifulSoup class SearchRepos: """ Scrape the list of links available in the Github repository : https://github.com/vinta/awesome-python. Search them by exact name from the console. Search result is the github url of the result repo. """ def __init__(self) -> None: ...
s1 = set() t1 = ('a',1) t2 = ('b',2) s1.add(t1) s1.add(t2) for s in s1: print('----')
def read_File(readPath): d1=dict() with open(readPath,'r')as f: for line in f: attribute = ((line.split('|||'))[2].strip()).upper() # 属性 b=attribute.encode(encoding='utf-8',errors='strict') a=len(b) c=attribute[0] if(c not in d1): ...
#https://programmers.co.kr/learn/courses/30/lessons/81301 import re def solution(s): answer = 0 num = ['zero','one','two','three','four','five' ,'six','seven','eight','nine'] # word_checker[0] = re.compile('zero') word_checker = [re.compile(x) for x in num] #num : 숫자, checker : re.co...
global dic dic = {} dic['0'] = [3,1] dic['*'] = [3,0] dic['#'] = [3,2] i = 0 j = 0 for n in range(1,10): dic[str(n)] = [i,j] j+=1 if j==3: i+=1 j=0 def solution(numbers, hand): global dic answer = '' l = [3,0] r = [3,2] for n in numbers: near = get_nearest_hand(n,...
import collections eq = input() def integrate(term): t_dic = collections.Counter(term) a=term[:len(term)-t_dic["x"]] a = int(a) if len(a) != 0 else 1 b = str(a//(t_dic["x"]+1)) result = b + "x" * (t_dic["x"]+1) if b != "1" else "x" * (t_dic["x"]+1) return result op = ["+","-"] if eq[0] i...
from collections import deque def solution(board, moves): answer = 0 q = deque() board.insert(0, [0 for i in board[0]]) for m in moves: m -= 1 y = get_top(board, m) # 들어 있으면 if y: doll = board[y][m] board[y][m] = 0 if q: ...
# https://programmers.co.kr/learn/courses/30/lessons/86051 def solution(numbers): answer = 0 num = [i for i in range(10)] for n in num: if n not in numbers: answer += n else: numbers.remove(n) return answer def solution2(numbers): return sum(n for n in r...
''' Problem 3 Description: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' LIST_OF_PRIMES = [2] LIST_OF_PRIME_FACTORS = [] def largest_prime(number): '''returns largest prime factor of 600851475143''' #Largest prime factor starts off as 1 ...
def merge(A, B): C,m,n = [],len(A),len(B) i,j = 0,0 while i+j<m+n: if i==m: C.append(B[j]) j += 1 elif j==n: C.append(A[i]) i+=1 elif A[i]<=B[j]: C.append(A[i]) i+=1 elif A[i]>B[j]: C.append(B[j]) j+=1 return C def merge_sort(X,left,right): if right - left<=1: return X[left:right...
""" 给一个m×n的矩阵,如果有一个元素为0, 则把该元素对应的行与列所有元素全部变成0 """ def zero(matrix): m = [None] * len(matrix) n = [None] * len(matrix[0]) for i in range(len(matrix)): for j in range(len(matrix[0])): if (matrix[i][j] == 0): m[i] = 1 n[j] = 1 for i in range(len(matrix))...
Name = raw_input ('Name: ') print "Hello " + Name + "! We are going to find out how long you have been alive!" Age = int(raw_input('How old are you?: ')) print "You are " + str(Age) + " years old." Months = Age * 12 # 12 is the number of months in a year Days = Age * 365 # 365 is the number of days in a year p...
# python delete_few_files_dirs.py "C:\_deletable\ex\nhentai.net" # -*- coding: utf-8 -*- import sys, os, re, shutil THRESHOLD = 10 # 指定ファイル数未満しか格納していないフォルダを、ファイルごと削除 def delete_few_files_dirs(directory): for root, dirs, files in os.walk(directory): for dir in dirs: for root2, dirs2, files2 in ...
import math class Vertex: def __init__(self, val): self.val = val self.connected = False self.visited = False #self.cost = math.inf class Graph(): def __init__(self, adjacency_matrix): """ Graph initialized with a weighted ad...
#!/usr/bin/env python3 # > greatet than # < less than # <= greater or equal # >= less or equal # == equal # != not eaual x = 42 y = 73 if x > y: print('comparison is true') else: print('comparison is false')
from tkinter import Tk, Frame, Button, Label, Entry, END, W, DISABLED class Application(Frame): '''GUI app that counts button clicks''' def __init__(self, master): '''Frame initiation''' super(Application, self).__init__(master) self.grid() self.create_widget() def create_...
#!/usr/bin/env python3 # # From python 2.5 Python includes a ternary conditional operator def bear_state(hungry): x = 'Feed the bear now' if hungry else 'Do not feed the bear' # ternary return x hungry = True print(bear_state(hungry)) # Feed the bear now hungry = False print(bear_state(hungry)) # Do not fee...
import random import time class CorrectChair: ''' A Chair on a chairlift ''' max_occupants = 4 def __init__(self, id): self.id = id self.count = 0 def load(self, number): new_val = self._check(self.count + number) self.count = new_val def unload(self, num...
#!/usr/bin/env python3 #! Special Methods # # A variety of instance methods that are reserved by Python, which affect an object’s high # level behavior and its interactions with operators. class Account: def __init__(self, name, balance = 0): self.name = name self.balance = balance prin...
from tkinter import Tk, Toplevel # create a form root = Tk() window = Toplevel(root) window.title('New Window') # to put window under main window.lower() window.lift(root) # we can control windows state window.attributes('-zoomed', True) # maximized window.state('withdrawn') # not visible window.state('iconic') # m...
#!/usr/bin/env python3 def new_decorator(some_func): def wrap_the_function(): print(f'I am doing some work before executing {some_func.__name__}') some_func() print(f'I am doing some work after executing {some_func.__name__}') return wrap_the_function def func_that_requires_decoratio...
from tkinter import Tk, Frame, Button, Label, Entry, Text, W, WORD, END class Application(Frame): '''GUI app that know secret of longevity''' def __init__(self, master): '''Frame initiation''' super(Application, self).__init__(master) self.grid() self.create_widgets() d...
from tkinter import Tk, Canvas, PhotoImage, Button root = Tk() # creating a canvas canvas = Canvas(root) canvas.pack() canvas.config(width=640, height=480) # create a line line = canvas.create_line(160, 360, 480, 120, width=5, fill='blue') # cnange line property canvas.itemconfigure(line, fill='green') # get coord...
# 1 # http://www.pythonchallenge.com/pc/def/map.html def cypher(sentence, step): alphabet = list('abcdefghijklmnopqrstuvwxyz') new_sentence = '' for letter in sentence.lower(): if letter in alphabet: letter_idx = alphabet.index(letter) + step if alphabet.index(letter) + step <= len(alph...
# sudo pip3 install seaborn # importing packages import seaborn as sns import matplotlib.pyplot as plt # loading dataset data = sns.load_dataset("iris") # draw lineplot sns.lineplot(x="sepal_length", y="sepal_width", data=data) # setting the title using Matplotlib plt.title('Title using Matplotlib Function') plt...
from tkinter import Tk, Frame, Label, Entry, Text, Radiobutton, StringVar, END, WORD, W, BooleanVar, Checkbutton, Button from random import randint class GuessNumber(Frame): '''GUI for guess number game''' def __init__(self, master): super(GuessNumber, self).__init__(master) self.grid() ...
#!/usr/bin/env python3 class NQueens: def __init__(self, n:int): self.n = n self.field = {} for i in range(self.n): self.field[i] = [0] * self.n def show(self): for i in range(self.n): print(self.field[i]) print() def ad...
#!/usr/bin/env python3 def main(): myFile = open("scores.txt", "w") # Show attributes of a file print(f"Name: {myFile.name}") print(f"Mode: {myFile.mode}") # Write to file myFile.write("GBJ : 100\n") myFile.write("NHD : 99\n") myFile.write("BBB : 89\n") myFile.close() ...
#!/usr/bin/env python3 # All of this evaluates to False # # False and None # Numeric zero values: 0, 0.0, 0j # Decimal(0), Fraction(0,x) # Empty sequences/collections: (), [], {}, '' # Empty sets and ranges: set(), range(0) # Anything else evaluates as True # Except: class myClass: def __bool__(self): re...
#!/usr/bin/env python3 def fibonacci_gen(): trailing, lead = 0, 1 while True: yield lead trailing, lead = lead, trailing + lead def main(): fib = fibonacci_gen() for _ in range(10): # to override problem use _ instead of letters print(next(fib)) if __name__ == '__main__': ...
#!/usr/bin/env python3 # Creates a new type object NewType = type("NewType", (object, ), {"attr": "it is a new type"}) New = NewType() # Print the type of object print(type(New)) #* <class '__main__.NewType'> # Print the attribute of object print(New.attr) #* it is a new type # it is same as: class NewType: ...
#!/usr/bin/env python3 def myFunction(arg1, arg2, *, supressExceptions=False): pass def main(): # try to call function w/o the keyword # myFunction(1, 2, True) # this will return error: # TypeError: myFunction() takes 2 positional arguments but 3 were give myFunction(1, 2, supressExceptions=...
#!/usr/bin/env python3 # coroutines # receive values/input (repeatedly) # process values # may not return anything # not for iteration # # Fumction vs Coroutine # It's the same function each time you call it # Persistent properties can be changed and altered # yield in coroutines: # pauses flow # captures sent value...
#!/usr/bin/env python3 def main(): # kitten(kitty = 'meow', dog = 'grrr', cat = 'purr') # # or x = dict(kitty = 'meow', dog = 'grrr', cat = 'purr') kitten(**x) def kitten(**kwargs): # keyword arguments list (dictionary) if len(kwargs): for k in kwargs: print('{} says: {}'.for...
# use a recursive algorithm to find a maximum value # declare a list of items to operate on items = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53] def find_max(items): # breaking condition: last item in list? return it if len(items) == 1: return items[0] # otherwise get the first item and call functi...
# use recursion to implement a countdown counter def countdown(x): if x == 0: print("Done!") return else: print(x, "...") countdown(x-1) print("foo") # if put something after function call this line will be executed after # "return" as much times as function was...
#!/usr/bin/env python3 import itertools def main(): # permutations # a way, especially one of several possible variations # in which a set of numbers or things can be ordered or # arranged election = {1: "John", 2: "Tom", 3: "Nathan"} for p in itertools.permutations(election): print(p...
#!/usr/bin/env python3 import zipfile def main(): # open zip = zipfile.ZipFile('archive.zip', 'r') # list print(zip.namelist()) # metadata for meta in zip.infolist(): print(meta) info = zip.getinfo("purchases.txt") print(info) # access a file in archive prin...
from tkinter import Tk from tkinter import ttk # create a form with tab notebook root = Tk() notebook = ttk.Notebook(root) notebook.pack() # by default notebook is sized 0x0 # lets add frames frame1 = ttk.Frame(notebook) frame2 = ttk.Frame(notebook) notebook.add(frame1, text='One') # index 0 notebook.add(frame2, text...
#!/usr/bin/env python3 from enum import Enum, unique, auto # @unique # class Fruit1(Enum): # APPLE = 1 # BANANA = 2 # ORANGE = 3 # TOMATO = 4 # PEAR = 1 # ValueError hear because of duplicate values class Fruit(Enum): APPLE = 1 BANANA = 2 ORANGE = 3 TOMATO = 4 PEAR = auto() ...
#!/usr/bin/env python3 def main(): # when compairing the strings # a->z 1->26 # so print("a" > "b") # will be False because 1 is not greater then 2 print("b" > "a") # will result in True 2 > 1 print("Jenny" > "Jennifer") # will result in True because "Jenn" is the same in both word...
#!/usr/bin/env python3 #! Returning functions from within functions def say_hi(name = 'Jack'): def greet(): return 'Now you are in the greet() function' def welcome(): return 'Now you are in the welcome() function' if name == 'Jack': return greet else: return welcome ...
# TC: O(n) # SC: O(1) # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: slow,fast,prev = head, head, None while f...
""" Project Euler Problem 3 ======================= The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? """ import math def prime_factorization(n): primes = [] number = n for divisor in range(2, math.floor(math.sqrt(number)) + 1): while n...
from math import sqrt a=1 b= -5 c=6 if (a==0) and (c==0): if (b==0): print 'non ci sono dati' else: if (a==0): print "L'eq. non e' di secondo grado" b=b*(-1) x=b/a print"x= ",x if(b==0): print "L'eq. e' pura" c=c*(-1) x1=c/a x2=sqrt(x1) if x2<0: print"impossibile" else: print"x1/2:+o-...
#!/usr/bin/python x=0 while True: print "current value x:",x x=x+1 if x==2563: break print "these is last number"
#!/usr/bin/env python3 count = 0 while count < 5: print("count:" , count) count+=1 else: print("count:", count, "is now not less than 5") print("Done")
#!/usr/bin/env python3 # Python 10 - Functions - Problem Set # =================== # 5. Create a new function that calculates the GC content of a DNA sequence. # - it will take a DNA sequence without spaces and no header as an argument and return the percentage of nucleotides that are a G or C. # - example `percen...
#!/usr/bin/env python3 # Python 7 - Regular Expressions - Problem Set # =================== # 3. Using pattern matching, find all the header lines in [Python_07.fasta](https://raw.githubusercontent.com/prog4biol/pfb2019/master/files/Python_07.fasta). Note that the format for a header in a fasta file is a line that st...
#!/usr/bin/env python3 # Python 6 - IO - Problem Set # =================== # 1. Write a script to do the following to [Python_06.txt](https://raw.githubusercontent.com/prog4biol/pfb2019/master/files/Python_06.txt) # - Open and read the contents. # - Uppercase each line # - Print each line to the STDOUT in...
import random def bubble_sort(_list_search): size = len(_list_search) for i in range(size): for j in range(0, size - i - 1): if _list_search[j] > _list_search[j + 1]: _list_search[j], _list_search[j + 1] = _list_search[j + 1], _list_search[j] return _list_search ...
#!/usr/bin/env python # Filename: func_return.py def maximum(x, y): if x >= y: return x else: return y print maximum(2, 3) x = int(raw_input('Enter an integer: ')) y = int(raw_input('Enter an integer: ')) z = maximum(x, y) print z
#!/usr/bin/env python def quickSort(array): mySort(array, 0, len(array)) def mySort(array, begin, end): if begin < end - 1: mid = partition(array, begin, end) mySort(array, begin, mid) mySort(array, mid+1, end) # increasing sorting def partition(array, begin, end): swap(array, beg...
#!/usr/bin/env python class Heap(object): """docstring for Heap""" def __init__(self, args=None): super(Heap, self).__init__() self.arg = [] if args != None: self.build_heap(args) def build_heap(self, arg): """start building the heap""" for item in arg: ...
#!/bin/python3 import math import os import random import re import sys def solve(s): coded_string = "" for i in range(len(s)): if i == 0 or (s[i].isalpha() and s[i-1].isspace()): coded_string += s[i].upper() else: coded_string += s[i] return coded_st...
kot = "Pixel" pies = "kora" rok = 2020 print(kot == 'pixel') print(pies == 'kora') print(kot.lower() == 'pixel') print(pies.lower() == 'pixel') print(rok > 2021) print(rok <2021) print(rok >=2021) print(rok <= 2021) print(rok == 2020 and pies == 'Pixel') print(rok == 2020 and pies == 'kora') print(rok == 2020 or pies ...
print("Stare menu:") potrawy = ('jajecznica', 'żurek', 'pizza', 'grochówka', 'bigos') for potrawa in potrawy: print(potrawa) #potrawy[2] = 'grzybowa' #nie działa i nie powinno print("\nNowe menu:") potrawy = ('jajecznica', 'rosół', 'kebab', 'grochówka', 'bigos') for potrawa in potrawy: print(potrawa)
current_users = ['admin', 'Sebastian', 'Yarek', 'Grzesiek', 'Asia'] new_users = ['Ania', 'Yarek', 'SEBASTIAN'] current_users = [current_user.lower() for current_user in current_users] for new_user in new_users: if new_user.lower() in current_users: print("Nazwa użytkownika jest zajęta!") else: print("Nazwa użyt...
cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort(reverse=True) print(cars) cars = ['bmw', 'audi', 'toyota', 'subaru'] print("Oto lista początkowa:") print(cars) print("\nOto lista posortowana:") print(sorted(cars)) print("\nOto ponownie lista po...
players =['karol', 'martyna', 'michał', 'florian', 'ela'] print("Pierwsze trzy elementy listy to:") print(players[0:3]) print("\nŚrodkowe trzy elementy listy to:") print(players[1:4]) print("\nOstatnie trzy elementy listy to:") print(players[-3:])
bicycles = ['trekingowy', 'górski', 'miejski', 'szosowy'] print(bicycles) print(bicycles[0]) print(bicycles[3]) print(bicycles[-1]) message = "Moim pierwszym rowerem był rower " + bicycles[1].title() + "." print(message)
pizzas = ['hawajska', 'pepperoni', 'wiejska'] for pizza in pizzas: print("Moja ulubiona pizza to: " + pizza.title()) print("\nNaprawdę uwielbiam pizzę!")
list = [1,2,'a'] y=[] #loop for x in list: y.append(x) print(y)
# Conversão de Dados String para Inteiro num = 1 num2: str = "1" print(f"# Conversão de Dados String para Inteiro : {num + int(num2)}") # Conversão de Dados Int para String print(f"# Conversão de Dados Int para String : {str(num) + num2}") # Atribuição de Valor print(num) num = 10 print(num) num2 = "100" prin...
from turtle import Turtle class Tags(Turtle): def __init__(self, input, x, y): super().__init__() self.hideturtle() self.color("blue") self.penup() self.goto(x, y) self.speed("fastest") self.write(input, align="center", font=("Arial", 8, "normal")...