text stringlengths 37 1.41M |
|---|
import sys
# 한번만 정렬하는 알고리즘
def insertionSort1_Best(n, arr):
target = arr[-1]
idx = n-2
while (target < arr[idx]) and (idx >= 0):
print(target, arr[idx], idx)
arr[idx+1] = arr[idx]
print(' '.join(map(str, arr)))
idx -= 1
arr[idx+1] = target
print(' '.joi... |
#!/bin/python3
# https://www.hackerrank.com/challenges/jumping-on-the-clouds
import math
import os
import random
import re
import sys
# Complete the jumpingOnClouds function below.
# 문제가 제대로 이해 안되어서 시간이 오래걸림. 인덱스 0과 1인 지점에 모두 0이 있으면 1부터 시작해도 되지만,
# 마지막 스텝에 0이 있으면 무조건 밟고 지나가야함! 중요한 조건인데 왜 안적혀있지?
def jumpingOnClouds(c... |
def print_twod(arr):
print('-------')
for row in arr:
print(row)
print('-------')
while True:
col, row = map(int, input().split())
if col is 0 or row is 0:
break
soil = []
for _ in range(col):
soil.append(list(input()))
mark = [[0]*row for _ in range(col)]
g... |
'''
Place green-stained images inside some directory and run with python 3
NOTE: ensure that there are only images of interest in selected directory. Other files will crash the program
Then select output format when promted:
1. a CSV file can be generatre
2. the file and print out the data in the command line
Input i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# game_functions.py
#
import sys
import pygame
from bullet import Bullet
def check_keydown_events(event, ai_settings, screen, ship, bullets):
"""响应按键"""
if event.key == pygame.K_UP:
ship.moving_up = True
elif event.key == pygame.K_DOWN:
ship.moving_down = True... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# homework2_favnumber.py
def get_stored_favnum():
"""如果存储了喜欢的数字,就获取它"""
filename = 'favnumber.txt'
try:
with open(filename) as f_obj:
favnum = json.load(f_obj)
except FileNotFoundError:
return None
else:
... |
import math
def func(x):
return pow(x,2)-2
a = float(input('input a : '))
b = float(input('input b : '))
e = pow(10,-7)
c = 0
count = 0
if (func(a)*func(b) < 0) :
while(abs(func(c))) >= e:
c = (a+b)/2
if(func(a)*func(c) > 0):
a = c
else :
b = c
count = ... |
'''
def d(n):
array = []
i = 1
while i < n:
if n % i == 0:
# print i
array.append(i)
i += 1
return array
def isPrime(n):
i = 2
while (i < round(n /2)):
if (n % i == 0):
return False
i += 1
return True
exceed = []
i = 2
while i <= 28123:
if isPr... |
from tkinter import *
root=Tk()
wenben=Text(root)
wenben.insert(INSERT,"woshiyiduanwenben hhhhhh")
wenben.insert(INSERT,"_______________________")
wenben.insert(END,"BYEBYE~")
wenben.insert(INSERT,"_______________________")
wenben.pack()
root.mainloop() |
#!/usr/bin/python
s="snoopy"
print "input is:" + s
x = len(s);
print "String length:" + str(x)
for j in range(x):
substr = s[:j+1]
print substr
|
import xlsxwriter
workbook = xlsxwriter.Workbook('Example3.xlsx')
worksheet = workbook.add_worksheet("My sheet")
for row in range(1,3):
print("Enter Name, USN, marks in 3 subjects of student "+str(row))
for col in range(5):
ele=input()
worksheet.write(row,col,ele) |
import requests
import json
from decimal import *
def get_exchange_rate(date):
""" gets the GBP/ILS exchange rate for a specified date """
response = requests.get(
'https://api.exchangeratesapi.io/' + date + '?symbols=GBP,ILS')
binary = response.content
output = json.loads(str(binary, 'utf-8')... |
import numpy as np
import math
vetor = []
for i in range (10):
if (i % 2 == 0 ):
valor = 3**i+7*(math.factorial(i))
else:
valor = 2**i+4*(math.log(i))
vetor.append(valor)
print("A posição do maior elemento é",np.argmax(vetor))
print("A média dos elementos é",np.mean(vetor))
|
"""The Rules and Setup for Chess."""
# Starting board for new game
starting_board = [
["R", "N", "B", "Q", "K", "B", "N", "R"],
["P", "P", "P", "P", "P", "P", "P", "P"],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", ""... |
money = int(input())
coin_values = [500, 100, 50, 10]
print('money to exchange: %d won' % money)
for val in coin_values:
print('coin of %d won: %d' % (val, money // val))
money %= val
print('change left: %d won' % money)
|
class point:
def __init__(self,stroka="0,0"):
self.x = float(stroka[:stroka.index(",")])
self.y = float(stroka[stroka.index(",")+1:])
def __add__(self,other):
return(str(self.x + other.x) + ','+str(self.y + other.y))
def __str__(self):
return('(' + str(self.x) + ',' + str(sel... |
from singleLinkedList import Node, LinkedList
def mergedLists(firstlist, secondlist, mergedList):
currentFirst = firstlist.head
currentSecond = secondlist.head
while 1:
if currentFirst is None:
mergedList.insertLast(currentSecond)
break
if currentSecond is None:
... |
arr = [1,2,3,1,3]
def findDuplicate(arr):
mydict = {}
for i in range(len(arr)):
if(arr[i] not in mydict):
mydict[arr[i]] = 1
else:
mydict[arr[i]] = mydict[arr[i]] + 1
#else saglanirsa duplicate vardir.
#print(mydict)
if(mydict[arr[i]] > 1):
print("Duplicate olan sayi", arr[i])... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self,new_data):
new_data = Node(new_data)
if self.head == None:
self.head = new_data
return
else... |
"""A palindrome is a word or a sequence that is the same from the front as from the back."""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self,new_data):
new_data = Node(new_data)
... |
class Animal():
# Parent Class Attribute
def __init__(self):
print("insde the constructor of Animal")
def show( self ):
print('Hello From Animal')
class Dog(Animal):
# CLASS OBJECT ATTRIBUTE
species = 'mammal'
def __init__( self, breed, name ):
self.breed = breed
... |
checkA = [1,2,3,4]
listA = [1,2,3,4,33,4,4,55]
#this function checks wether the listA consists the number sequence in list checkA and accordingly return the boolean result
def checkPresent( check ):
if( len(check) <= len(listA) ):
for i in range(0, len(listA) - len(check)+1 ):
if( check == lis... |
#Casandra Villagran
#2/20/2020
#Use random.choice to select a day of the week from a list and print that day.
import random
DaysList= ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
print ("Random day of the week: ", random.choice(DaysList))
|
students = {"Alice":["ID0001",26,"A"],
"Bob":["ID0002",27,"B"],
"Clair":["ID0003",17, "C"],
"Dan":["ID0004",21,"D"],
"Emma":["ID0005",22,"E"],
}
print(students)
print(students["Clair"])
print(students["Clair"][0])
print(students["Dan"][1:])
#in order to make... |
# open function
file1 = open("C:/Nima/Data_science course/Course 04/Example1.txt","w")
print(file1.name)
print(file1.mode)
file1.close()
#with open is better to open the file because it automatically closes the file
with open("Example1.txt") as file1:
file_stuff = file1.read()
print(file_stuff)
print(file1.c... |
class Account:
def __init__(self, name, balance, min_balance):
self.name = name
self.balance = balance
self.min_balance = min_balance
def deposit(self, amount):
self.balance = self.balance + amount
def withdraw(self, amount):
if self.balance - amount >= self.min_bal... |
#Creating a SET
set1 = {"A", "AB", "A"}
#There are no duplicate values in a set
print(set1)
#Change a list to a set
list = ["Nima", "Afshar", "Nima", 1984]
set = set(list)
print(set)
#Add item to the set
set1.add("C")
print(set1)
#remove an item from the set
set1.remove("C")
print(set1)
#check if the item is in the... |
import pandas as pd
csv_path = 'C:/Users/nafs080/work/codes/python_packages/python_tutorial/Python for Data Science/file1.csv'
df = pd.read_csv(csv_path)
df.head()
songs = {"Album":["Thriller","Back in Black"],"Released":["1982","1980"]}
songs_frame = pd.DataFrame(songs)
print(songs_frame)
x = songs_frame[['Releas... |
#local scope can only be seen in an specific local scope but global scope can be see anywhere in the code, only function can make a local scope
# a is now defined in a global scope but if we move that into the function f1() then it is not going to work for f(2)
a = 100
def f1():
print(a)
def f2():
print(a)
f... |
my_int = 4
my_float = 2.34
print(my_float)
print(type(my_int))
result = my_int + my_float
print(result)
result = my_int - my_float
print(result)
result = my_int * my_float
print(result)
result = my_int / my_float
print(result)
result = my_int // my_float
print(result)
#exponents and powers
result = 3 ** 2
print(result)... |
import string
import operator
class Question1_Solver:
def __init__(self, cpt):
self.cpt = cpt;
return;
#####################################
# ADD YOUR CODE HERE
# Pr(x|y) = self.cpt.conditional_prob(x, y);
# A word begins with "`" and ends with "`".
# For example, the probabil... |
import sys
class Question3_Solver:
def __init__(self):
return;
# Add your code here.
# Return the centroids of clusters.
# You must use [(30, 30), (150, 30), (90, 130)] as initial centroids
def solve(self, points):
centroids=[(30, 30), (150, 30), (90, 130)]
# centroids = [(30... |
################################################################################
# File: hw1_written2.py
# HW 1, CS5785
# Neil Lakin
#
# Purpose: Draw some plots for homework 1, written exercise 2.
#
################################################################################
import numpy as np
from matplo... |
def Longest_Repeated_Subsequence(n,string):
LR=[[0 for i in range(n+1)] for j in range(n+1)]
for i in range(1,n+1):
for j in range(1,n+1):
if string[i-1]==string[j-1] and i!=j:
LR[i][j]=1+LR[i-1][j-1]
else:
LR[i][j]=max(LR[i][j-1],LR[i-1][j])
i... |
# p1.py - find the maximum clique in a graph
# by K. Brett Mulligan
# 27 Aug 2014
# CSU CS440
# Dr. Asa Ben-Hur
##############################################
import itertools, copy, re
DO_TESTING = False
DO_VERBOSE_PARSING = False
prohibited_chars = ['{', '}', '/']
class Graph:
name = "" # id of... |
from Node import Node
class Edge:
def __init__(self, n1: Node, n2: Node, w: int):
"""Initialize the edge with the two nodes and the weight"""
self.node1 = n1
self.node2 = n2
self.weight = w
def get_weight(self):
return self.weight
def get_nodes(self):
return self.node1, self.node2
|
class Animals:
fullness = 'hungry'
location = 'at home'
cleanliness = 'dirty'
voice = ''
def __init__(self, name, weight):
self.name = name
self.weight = weight
def feed(self):
self.fullness = 'full'
return print('onomnomnom')
def walking(se... |
from typing import Iterable
from .data import parse_zip_codes
from .zip_code import ZIPCode
def create_map_url(zip_codes: Iterable[ZIPCode], title: str) -> str:
zips = ",".join(str(z) for z in zip_codes)
return f"https://www.randymajors.com/p/customgmap.html?zips={zips}&title={title}"
def main(body: str, t... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 04:52:16 2019
@author: dina
list of dictionary objects not good because:
- place for key name that is same for all dictionaries
- can change values that is not right
so use collections library to get immutable data structure and put the data
in a tuple ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 08:55:38 2019
Keras API save img() function to save an image to file.
The function takes the path to save the image and the image data in NumPy
array format.
The file format is inferred from the filename but can also be specified via the
file format argument.
Th... |
import sqlite3
import os
conn = sqlite3.connect(os.path.dirname(os.path.realpath(__file__)) + '\\test.db')
print ("Opened database successfully");
cursor = conn.execute('SELECT max(id) FROM test')
# print(cursor.fetchall())
#for row in cursor:
# print(row)
while True:
word = input ('Bitte gib ... |
summe = 0
anzahl = 0
while summe <= 50:
try:
user_input = int(input("Bitte eine Zahl eingeben:"))
anzahl += 1
summe += user_input
except:
break
if anzahl > 0:
print ("Summe: ", summe, "Anzahl: ", anzahl)
print ("Durchschnitt = ", summe / anzahl) |
try:
user_input = int(input("Bitte eine Zahl eingeben: "))
except:
exit("eine Zahl du x#%&§@!")
if user_input > 10:
print ("user_input > 10")
elif user_input == 10:
print("user_input == 10")
else:
print("user_input < 10")
print("fertig") |
# PROBLEM: Code a Program which will help the user in Printing a Star Pattern according to their wish of style.
print("Select the Pattern from the Two Options given below. \n")
print("Here's Option 1:-")
R = 5
while R >= 1:
print(R * "*")
R = R - 1
print()
print("Option 2 on your Screen:-")
... |
def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1))
numbers=[]
for key in str(factorial(100)):
numbers.append(int(key))
print sum(numbers)
|
# coding: utf-8
# # Slicing Ends verse min/max
#
# If you have an order list of numbers how best to return the min and max values.
# In[ ]:
list min max
list []
np min max
np []
# In[ ]:
# Slicing the first and last elements is faster than np.min(), np.max() if you know that the list is ordered
#min_dwl = wl2[... |
import random
import statistics as stats
n = 10
lst = [random.random() for x in range(n)]
def carloloop(nums):
if nums <= 0.05:
## print("nine")
nine.append(1)
result = 9
elif 0.05 < nums <= .15:
## print('ten')
ten.append(1)
result = 10
... |
def multiply_string(n):
n = n + 1
return n
if __name__ == '__main__':
try:
n = int(input("Enter the number"))
except ValueError as err:
print("ValueError found!!")
else:
print("Python!" * n)
# age = 5
# print(multiply_string(age))
# print(age) |
# =============================================================================
# Exercise-11 with Solution
# Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations.
#
# Sample data:
# /*
# X = [10, 2... |
# =============================================================================
# 6. Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers. Go to the editor
# Sample data : 3, 5, 7, 23
# Output :
# List : ['3', ' 5', ' 7', ' 23']
# T... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 13 21:11:01 2017
@author: Wizard
"""
import sqlite3
queries = {
"a": "SELECT * FROM nodes_tags WHERE key='city' and value LIKE '%, WA%'"}
# query the database and return results as rows
def ask_question(query):
db = sqlite3.connect("openmaps.d... |
import sys
from task import Task
from task_search import tasks_search
MAIN_MENU_PROMPT = "WORK_LOG\nWhat would you like to do?\na) add new entry\n" \
"b) Search in existing entries\nc) Quit program\n"
def app_menu():
"""Application menu"""
while True:
prompt_res = input(MAIN_MENU_PR... |
# Class representing a population of individuals
# Author Fan Zhang
import random
from Individual import Individual
class Population:
# Actual standard ctor.
# param map The map.
# param initialSize The initial size of the population.
def __init__(self, map, initialSize):
self.vector = []
... |
"""
Increase the output of a single neuron
Taken from http://karpathy.github.io/neuralnets/ and refactored a bit
Pending questions:
- How can this be generalized to vectors?
Should every element in every vector be considered as a variable?
- How is the gradient calculated for dot and matrix products?
"""
import math
... |
def solution(S):
parentheses = 0
for element in S:
if element == "(":
parentheses += 1
else:
parentheses -= 1
if parentheses < 0:
return 0
if parentheses == 0:
return 1
else:
return 0 |
def solution(T):
if T.l == None and T.r == None:
# Has no subtree
return 0
elif T.l == None:
# Only has right subtree
return 1 + solution(T.r)
elif T.r == None:
# Only has left subtree
return 1 + solution(T.l)
else:
# Have two subtrees
... |
class Train:
def __init__(self, name , fare, seats):
self.name = name
self.fare = fare
self.seats = seats
def getStatus(self):
print('************************')
print(f"The Name Of Train is {self.name}")
print(f"The Seats In Train is:{self.seats}")
def fareInf... |
name = input("Enter your Name:\n")
marks = int(input("Enter your marks:\n"))
phone = input("Enter your phone:\n")
template = "The name of student is {}, his marks are {} and phone number is {}"
output = template.format(name,marks,phone)
print(output) |
class Employee:
company = "Google"
def getSalary(self):
print(f"Salary for this employee working in {self.company} is {self.salary}")
ayush = Employee()
ayush.salary = 1000000
ayush.getSalary() #---> automatically convert into below code the self (function)
# Employee.getSalary(ayush) |
class Person:
country = 'India'
def takeBreath(self):
print("I am breathing....")
class Employee(Person):
company = "Honda"
def getSalary(self):
print(f"Salary is {self.salary}")
def takeBreath(self):
print("I am employee and luckily breathing...")
class Programmer(Emplo... |
L1 = [1,5,22,4,122,42,55,1111]
print(L1)
# L1.sort() ---> Sorts The List
# L1.reverse() --->Reverse The List
# L1.append(45) --->Appends The List add 45 at end of list
# L1.insert(1,544) --->Inserts 544 at index 1
# L1.pop(2) --->Pops Out (Remove) Index 2 from lists
# L1.remove(55) ---> Removes 55 from list
print(L1) |
cont = True
i = 1
with open('/home/cyberboyayush/Documents/Python/Practise/Chapter 9/log.txt') as f:
while cont:
i+=1
cont= f.readline().lower() # reads full file as lower so that our program can detect it
print(cont)
if 'python' in cont:
print(cont)
print('... |
b = set()
print(type(b))
# Addding values to empty set
b.add(4)
b.add(5)
b.add(6)
b.add(5) #Adding a value repeatidly does not change a set
# Note : We Cannot add list or dict in sets
#Accessing Elements
print(b)
#Find Length
print(len(b))
#Removing Element
b.remove(5) #Removes 5 from set b
# b.remove(15) #Throws a... |
#!/usr/bin/env python3
"""Um exemplo mais claro, observe que a ordem dos paramentros nao eh obedecida"""
def printinfo(name, age):
"This prints a passed info into this function."
print("Name: ",name)
print("Age: ",age)
return
# Chamando a funcao printinfo
printinfo(age=43, name="Fabio") |
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.title())
"""The title() method returns a copy of the string in which first characters of all the words
are capitalized."""
#s.title(), retorna a primeira letra de cada palavre em maiusculo.
# print('the sun also rises'.title())
# print()
|
#!/usr/bin/env python3
from tkinter import *
root = Tk()
B1 = Button(root, text='circle', relief=RAISED, cursor='circle')
B2 = Button(root, text='plus', relief=RAISED, cursor='plus')
B1.pack()
B2.pack()
root.mainloop() |
import os
import time
"""The files and directories to be backed up are specified in a list
Example on Windows OS: source = ['"C:\\My Documents"', 'C:\\Code']
Example on Unix: source = ['/Users/nome/Documents']
"""
source = '/home/fabio/Pictures'
"""The backup must be stored in a main backup directory
Example Wi... |
#!/usr/bin/env python3
"""O método asctime () converte uma tupla ou struct_time representando uma hora
como retornada por gmtime () ou localtime () para uma cadeia de 24 caracteres da
seguinte forma: 'Ter 17 de fev 23:21:05 2009 '.
Sintaxe: time.asctime([t]))
"""
import time
t = time.localtime()
print("asctime: ", ... |
#!/usr/bin/python3
"""The islower() method checks whether all the case-based characters (letters) of the string
are lowercase.
"""
str = "THIS is string example....wow!!!"
print(str.islower())
str = "this is string example....wow!!!"
print(str.islower())
print()
print('abcdef'.islower())
print('abcde$f'.islower())... |
#!/usr/bin/env python3
a = ['foo', 'bar', 'baz', 'qux', 'quux', 'courge']
a.insert(3, 3.14159) # 3 = indice, 3.14159 = valor
print(a) |
#!/usr/bin/python3
"""Description
The count() method returns the number of occurrences of substring sub in the range
[start, end]. Optional arguments start and end are interpreted as in slice notation.
Syntax
str.count(sub, start= 0,end=len(string))
"""
str="this is string example....wow!!!"
sub='i'
print ("str.cou... |
"""cria um generator"""
def main():
for i in inclusive_range(0,25):
print(i, end=" ")
print()
def inclusive_range(*args):
"Cria um range incluindo o ultimo numero."
numargs = len(args)
start=0
step=1
if numargs < 1:
raise TypeError("Esperado ao menos 1 argumento, recebid... |
from tkinter import *
janela = Tk()
# W x H + L + T
janela.geometry("400x300+200+200")
def bt_click():
print('bt_click clicado')
lb['text'] = 'E ganhe Super Poderes'
bt = Button(janela, width=20, text="ok", command=bt_click)
bt.place(x=100, y=100)
lb = Label(janela, text='Aprenda Python')
lb.place(x=150... |
#!/usr/bin/env python3
"""A rolodex of friends"""
rolodex = {
'Aaron':5556069,
'Bill':5559824,
'Dad':5552603,
'David':5558381,
'Dillon':5553538,
'Jim':5555547,
'Mom':5552603,
'Olivia':5556397,
'Verne':5555309
}
#
# print(rolodex["Verne"])
# print(hash('Verne'))
# Adding new person
... |
#!/usr/bin/python3
"""Equivale a invocar lstrip() e rstrip() sucessivamente.
Sintaxe: str.strip([chars]);
"""
str = "*****this is string example....wow!!!*****"
print(str.strip( '*' ))
print()
s = ' foo bar baz\t\t\t'
print(s.lstrip().rstrip())
print('www.realpython.com'.strip('w.com'))
|
#!/usr/bin/python3
str = "this2016"
print (str.isdecimal())
str = "23443434"
print (str.isdecimal())
"""The isdecimal() method checks whether the string consists of only decimal characters.
This method are present only on unicode objects.""" |
#!/usr/bin/env python3
ages = [12, 19, 39, 87, 7,2]
for age in ages:
isAdult = age > 17
if isAdult:
print('Being: ' + str(age) + " make you an adult")
if not isAdult:
print("Being: " + str(age) + " does not make you an adult.")
|
#!/usr/bin/env python3
#Exemplos utilizando operadores booleanos (and, or, not, in, not in, is , is not).
a = True
b = False
x = ('bear', 'bunny', 'tree', 'sky','rain')
y = 'bear'
if y in x: # y (bear) in x (bear ...)
print('Expression is true')
else:
print('Expression is false')
|
#!usr/bin/python3
import sys
lista = [1,2,3,4]
it = iter(lista) # this builds an iterator object
print(next(it)) #prints next available element in iterator
#Iterator object can be traversed using regular for statement
#
for x in it:
print (x, end=" ")
#or using next() function
# while True:
# try:
# ... |
#!/usr/bin/env python3
# Trocando os valores de duas variaveis , SWAP
a = 'foo'
b = 'bar'
#print(a,b)
# Primeira maneira, utilizando um variavel temporaria
# temp = a
# a = b
# b = temp
# print('Valor de a: "{}" e valor de b: "{}".'.format(a, b))
# De maneira mais Pythonica
a, b = b, a
print('Valor de a: "{}" e val... |
#!/usr/bin/env python3
"""O método sleep () suspende a execução pelo número de segundos especificado. O
argumento pode ser um número de ponto flutuante para indicar um tempo de sleep
mais preciso.
Sintaxe:time.sleep(t)
"""
import time
print("Start: %s" % time.ctime())
time.sleep(3)
print("End: %s" % time.ctime()... |
from tkinter import *
root = Tk()
var = IntVar()
var.set(0) # inicializando com a opção Python marcada
languages = [
"Python",
"Perl",
"Java",
"C++",
"C",
]
def ShowChoice():
print(var.get()) # captura o valor da opção escolhida
l1 = Label(root,
text="""Escolha sua linguagem... |
#!/usr/bin/env python3
print('Listas_________')
minhaLista = ['ABCD', 2.33, 'efgh', 'bola', 'copo']
print(minhaLista[0])
print(minhaLista[1])
print(minhaLista[2])
print(minhaLista[-1])
#Adicionando um elemento no final da lista utilizamos append
minhaLista.append('Fogo')
print(minhaLista)
# Para adicionar e escolher... |
#!/usr/bin/env python3
import tkinter
window = tkinter.Tk()
window.title("Mouse click events")
# definindo 3 diferente funções para eventos
def left_click(event):
tkinter.Label(window, text="Left Click").pack()
def middle_click(event):
tkinter.Label(window, text="Middle click").pack()
def right_click(e... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c = a - b
print("Line 2 - Value of c is ", c )
c = a * b
print("Line 3 - Value of c is ", c)
c = a / b
print("Line 4 - Value of c is ", c )
c = a % b
print("Line 5 - Value of c is ", c)
a = 2
b = 3
c = a**b... |
nome = 'Fabio'
idade = 42
peso = 72
altura = 1.70
code = 'Python'
versao = 2.7
ano = 2018
# place holder
""""% python 2.7, place holder %s (strings) , %d(inteiros) %f(floats)"""
print('Meu nome eh %s meu codigo eh %s, versao: %d'%(nome, code, versao))
#formato Python versao 3.0
#print('Vamos programar em {} versao... |
#!/usr/bin/python3
"""The rjust() method returns the string right justified in a string of length width. Padding
is done using the specified fillchar (default is a space). The original string is returned if
width is less than len(s).
"""
str = "this is string example....wow!!!"
print (str.rjust(50, '*'))
print()
p... |
'''A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
The main difference between the tuples and the lists is that the tuples cannot be changed
unlike lists. Tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separat... |
#!/usr/bin/env python3
a = ['foo', 'bar', 'baz', 'qux', 'quux', 'courge']
a.pop() # a.pop() simply removes the last item in the list
print(a)
print(a.pop(1)) # 'bar' |
#!/usr/bin/env python3
# multiplos diretorios e arquivos
import os
for dirpath, dirnames, files in os.walk('.'):
print('-' * 70)
print(f'Diretorios e arquivos encontrados: {dirpath}')
for file_name in files:
print(file_name)
|
#!/usr/bin/env python3
import tkinter
window = tkinter.Tk()
window.title("Label")
# definindo 3 labels simples contendo texto simples
# sufficient width
tkinter.Label(window, text = "Sufficient width", fg="white", bg="purple").pack()
# width of x
tkinter.Label(window, text="Width of x", fg="white", bg="green").p... |
#!/usr/bin/env python3
"""Criando um dicionario a partir de duas listas usando a função zip"""
questions = ['name', 'questions', 'favourite color']
answer = ['Lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answer):
print("What's yours {}? It's {}".format(q, a)) |
#!/usr/bin/env python3
fo = open('foo3.txt', 'r') # modo leitura r/read
print("Nome do arquivo: ", fo.name)
for index in range(5):
line = next(fo)
print(f'Line No {index} - {line}')
fo.close() |
#!/usr/bin/python3
str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))
"""The len() method returns the length of the string.
Syntax
len( str )""" |
#!/usr/bin/env python3
"""Sempre que usamos a palavra reservada yield , estamos criando uma funcao
geradora. A funcao geradora gera um valor toda vez em que e “chamada”, e aqui,
usamos aspas, pois não e uma chamada comum. Por padrão, as funções geradoras
podem ser iteradas no comando for"""
def get_generator():
... |
from tkinter import *
root = Tk()
var = IntVar()
l1 = Label(root,
text="Escolha uma linguagem de programação:",
justify=LEFT,
padx=20).pack()
r1 = Radiobutton(root,
text="Python",
padx=20,
variable=var,
value=1).pac... |
from tkinter import *
def write_slogan():
print("Tkinter is use to learn!!!!")
root = Tk()
frame = Frame(root)
frame.pack()
button = Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=LEFT)
slogan = Button(frame,
text="Hello",
... |
from player import Player
class Human(Player):
def __init__(self):
super().__init__()
def choose_gesture(self):
self.chosen_gesture = input("Pick a gesture: rock, paper, scissors, lizard, spock ")
if (self.chosen_gesture == "rock" or self.chosen_gesture == "paper" or self.chosen_gestu... |
from turtle import Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)
scoreboard = Scoreboard()
screen.listen()
paddle1 = Paddle(1)
paddle2 = Paddle(... |
from src.algorithms.node import Node
# Given a list of integers as the leafs of a binary tree, create a balanced binary tree, in which
# the sum of a node's children will equal the node's value.
# Return the root of the binary tree.
#
# Print the binary tree as the following:
# For example, given the list [1, 2, 3, 3... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.