text stringlengths 37 1.41M |
|---|
list=["a","b","c","d","e","f"]
#insert method
list.append(5)# insert at last if we have to insert into agiven position then we have to use insert method "a.insert(len(a),x)" is equal to a.append
print list
a = [66.25, 333, 333, 1, 1234.5]
a = [66.25, 333, 333, 1, 1234.5]
print a.count(66.25),a.count(333)
a.append(999... |
class parentclass:
var1="i am var1"
var2="i am var2"
class childclass(parentclass):
pass
parentobject=parentclass
childobject=childclass
print parentobject.var1
print childobject.var1
print "here we show that childobject access the parentobject property"
|
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self)... |
import json
from difflib import get_close_matches
#load dictionary data into variable called 'data'
data = json.load(open("data.json"))
#create function
def translation(w):
#whenever words get passed into this function, it will convert all characters to lower case
w = w.lower()
#conditional if word passe... |
import pygame
from config import PLAYLIST, BACK, JUMP, KEY, FORWARD, DIE
class AudioService:
"""A class to represent audio service which handles the audio of the game.
"""
def __init__(self):
"""Loads audio files for the audio service.
Audio filepaths are obtained from the config -file.... |
class NewGameView:
"""A class to represent new game view of UI.
Attributes:
renderer: Renderer object.
"""
def __init__(self, renderer):
"""Constructs all the necessary attributes for finish view.
Args:
renderer (Renderer): Renderer object which renders the display... |
class MenuView:
"""A class to represent menu view of UI.
Attributes:
renderer: Renderer object.
"""
def __init__(self, renderer):
"""Constructs all the necessary attributes for finish view.
Args:
renderer (Renderer): Renderer object which renders the display.
... |
import sys
def testWhileElse():
count = 0
while count < 5:
print(count)
count += 1
else:
print(count, 'false')
def testForElse():
#else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况
#下执行,while … else 也是一样
for num in range(10,20): # 迭代 10 到 20 之间的数字
for i in range(2,nu... |
"""
All Rules relevant to contexts that work with strings.
It may be subject, object, etc.
"""
import re
import logging
from ..rules.base import Rule
log = logging.getLogger(__name__)
class StringEqualRule(Rule):
"""Rule that is satisfied if the string value equals the specified property of this rule"""
... |
# 이진트리 순회(깊이우선탐색)
# 아래 그림과 같은 이진트리를 전위순회와 후위순회를 연습해보세요.
# 1
# 2 3
# 4 5 6 7
# 전위순회 출력 : 1 2 4 5 3 6 7 중위순회 출력 : 4 2 5 1 6 3 7 후위순회 출력 : 4 5 2 6 7 3 1
import sys
import math
from collections import deque
# heapq를 사용할 수 있도록 추가
import heapq as hq
#sys.stdin = open("in1.txt", "rt")
# 전위순회
def f_DFS(v):
if v <= 7:
... |
# coding=utf-8
'''
Created on 30/01/2016
@author: jmonterrubio
Address parsing tests
'''
import unittest
from map_parser.map import address
ONE_GOOD_CITY = 'City'
UNKNOWN_ADDRESS_FIELD = 'address:'
BAD_ADDRESS_FIELD = 'addr:city:info'
class TestsParseAddress(unittest.TestCase):
# Parse correctly a well d... |
import numpy as np
list1=[90,32,89,21]
print(list1[-2:])
print(np.argmin(list1)) # least element(21) present in 3rd index position
list2=[[12,31,23,67],[89,45,21,34],[56,25,78,96]]
print(*np.argmin(list2,axis=1)) # Row-wise
print(*np.argmin(list2,axis=0)) # Column-wise |
#В матрице a(n, m) поменять местами столбцы с минимальным и максимальным
# количествами четных элементов. Матрица — список списков.
def change(a):
n = len(a)
m = len(a[0])
for j in range(m):
b = []
count = 0
for i in range(n):
if a[i][j] % 2 == 0:
count... |
# Введенную с клавиатуры строку вывести на экран наоборот (использовать цикл)(0,5 балла)
def revers(s):
string = ''
# Вызываем функцию, ей в качестве аргумента точку
s = s.split('.')
for i in range(0, len(s)):
string += s[i][::-1].strip() + '. '
print(string)
strl = input()
revers(strl) |
# नितीन पटले
# 𝓑𝓣𝟣𝟪𝓒𝓢𝓔𝟢𝟢𝟦
import sys
# prime number is in the form
# 6n ± 5
def product_of_primes(a):
if a <= 1: return []
l = []
i = 2
count = 0
while (a%i == 0):
a = a//i
count += 1
if(count > 0):
l.append([i, count])
i = 3... |
# नितीन पटले
# 𝓑𝓣𝟣𝟪𝓒𝓢𝓔𝟢𝟢𝟦
import sys
def gcd(a, b):
if(b == 0):
return a
return gcd(b, a%b)
def extended_euclidean(a, b):
if(b == 0):
return [1, 0]
[x1, y1] = extended_euclidean(b, a%b)
x = y1
y = x1 - (a//b)*y1
return [x, y]
def multiplicative_in... |
print('my name is')
for i in range(3):
print('Jimmy Five Time (' + str(i) + ')')
|
def is_multiple(n, m):
if n % m == 0:
return True
else:
return False
print(is_multiple(20, 5))
print(is_multiple(13, 5)) |
def remove(word):
punc = ['.', ',', '!', '?', ':', ';', '-']
new_word = ''
for i in word:
if i not in punc: new_word += i
return new_word
print(remove('apple?'))
print(remove('hd,a:sie,w-n,fe;dw!!!'))
|
import random
import string
from words import Words
class Hangman:
guesses = 8
lettersGuessed = []
__guessed = ''
def __init__(self, words):
self.__words = words
def start(self):
print 'Welcome to the game, Hangam!'
print 'I am thinking of a word that is', len(self... |
import csv
def entry2csv(listdata):
# enters list data to csv file
with open("student_data.csv", 'a', newline = '') as datafile:
entry = csv.writer(datafile)
if datafile.tell() == 0:
entry.writerow(['Name', 'Age', 'Ph No.', 'Email ID'])
entry.writerow(listdata)
def lwrcase... |
"""Doubly-linked list class definition.
Defines a general purpose doubly-linked list data structure with a nested class to define the nodes of the list.
.. _React Library:
https://github.com/hivebattery/gui/blob/master/driver/react/data_structures/doubly_linked_list.py
"""
class DoublyLinkedList(object):
"... |
n=int(input('n='))
if (n==28) or (n==29):
print('februarie')
if n==30:
print('aprilie','iunie','septembrie','noiembrie')
if n==31:
print('ianuarie','martie','mai','iule','august','octombrie','decembrie')
if (n<28) or (n>31):
print('numar de zile invalid')
|
# -*-encoding=utf-8-*-
"""
全面复习各种奇怪的排序
"""
"""
直接插入排序
"""
def insert_sort(nums):
for i in range(1, len(nums)):
tmp = nums[i]
j = i - 1
while j >= 0 and tmp < nums[j]:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = tmp
return nums
"""
归并排序
"""
def merge_sort(nums... |
import numpy
def u(ary1, ub):
print(ary1)
print(ary1.__len__())
std = numpy.std(ary1)
average = numpy.average(ary1)
ua = std/numpy.sqrt(ary1.__len__())
U = numpy.sqrt(float(ua)**2+float(ub)**2)
return {
'平均数': f'{average}',
'标准差': f'{std}',
'Ua': f'{ua}',
'U... |
class minHeap:
def __init__(self):
self.heapList = [0]
self.size = 0
def percUp(self, i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self... |
import turtle
import random
myTurtle = turtle.Turtle()
myWin = myTurtle.screen
def draw_spiral(myTurtle, linelen):
if linelen > 0:
myTurtle.forward(linelen)
myTurtle.right(90)
draw_spiral(myTurtle, linelen - 5)
# draw_spiral(myTurtle, 150)
# myWin.exitonclick()
def tree(branchLen, t):... |
def insertion_sort(arr):
for k in range(1, len(arr)):
value = arr[k]
position = k
while position > 0 and arr[position - 1] > value:
arr[position] = arr[position - 1]
position -= 1
arr[position] = value
return arr
test_arr = [11, 5, 2, 7, 48, 12, 443, 0... |
#descrip_stat.py功能: 以自訂函數寫法計算敍述統計並回傳
import math
def depsta(sample):
#depsta功能: 計算樣本的敍述統計
maxv=max(sample)
minv=min(sample)
meanv=sum(sample)/len(sample)
sumi=0
for i in range(0, len(sample)):
sumi=sumi+((sample[i]-meanv)**2)
varv=sumi/(len(sample)-1)
stdv=math.sqrt(varv)
... |
#RC_6_4 功能: 終值
def fvfix(pv, i, n):
#fvfix: 計算終值公式
result=pv*(1+i)**n
return(result)
pv=100
i=0.03
n=int(input('計算終值的年數 = '))
print('%d年後的終值 = %6.2f' %(n, fvfix(pv, i, n))) |
#E_7_13: 檔案更名與檔案刪除
import os
import os.path
PATH1='./file/WangWei_poetry_1.txt'
PATH2='./file/WangWei_poetry_2.txt'
if os.path.isfile(PATH1) and os.access(PATH1, os.R_OK):
os.rename('./file/WangWei_poetry_1.txt', '辛夷塢王維.txt')
print('%s檔案已更名%s' %('WangWei_poetry_1.txt','辛夷塢王維.txt'))
else:
print('WangWei_p... |
#E_5_1 功能: 輸入一個數值,判斷若小於50則開根號乘以10
import math
num=int(input('請輸入任一數'))
Tt=num
if num<50:
Tt=math.sqrt(num)*10
print(num,Tt)
|
#E_6_8.py 功能: 預設參數的使用範例
import math
def defaultscore(score=40):
#defaultscore: 判斷若小於50則開根號乘以10
if score<50:
return math.sqrt(score)*10
else:
return score
name='Jack'
ss=[16,'',36,55,'']
for ii in ss:
if type(ii) is int:
result=defaultscore(ii)
else:
result=defaultscore(... |
import abc
class Leifeng:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def wash(self):
""""wash"""
@abc.abstractmethod
def sweep(self):
"""sweep"""
@abc.abstractmethod
def buy_rice(self):
"""buy rice"""
class Undergraduate(Leifeng):
def wash(self):
... |
#E_5_3 功能: 成績分等級
score=int(input('輸入成績0-100分: '))
grade='輸入'
if score<60: #條件1
grade='戊等'
elif score <70: #條件2
grade='丁等'
elif score<80: #條件3
grade='丙等'
elif score<90: #條件4
grade='乙等'
elif score<=100: #條件5
grade='甲等'
else: #條件6
grade='輸入錯誤'
print (score,grade) |
#RC_6_8 功能: 年金給付金額
def annuity(pv, i, n):
#annuity: 計算年金公式
up=i*((1+i)**n)
down=((1+i)**n)-1
result=pv*(up/down)
return(result)
i=0.03
n=int(input('輸入貸款年數 = '))
pv=1000000
print('每年應付貸款金額 = %10.2f' %(annuity(pv, i,n))) |
#E_5_8 功能: 計算1-(1/n)的函數。
n=int(input('Please input n : '))
result=0
for i in range(2,n+1,1):
result=result+(1-(1/i))
print('%s %.2f' %('The result is ', result)) |
#!/usr/bin/env python
"""
This is an example for python docstring, including modules,
functions, classes, methods, etc.
"""
import math
print math.__doc__ # standard modules' docstring.
print str.__doc__ # standard function docstring.
print '#' * 65
def foo():
"""It's just a foo() function."... |
#sumn_def.py功能: 主程式呼叫1層自訂函數
def sumnfunc(n):
#A_func功能: 計算累加
sumn=0
for i in range(n+1):
sumn=sumn+i
return(sumn)
num=int(input('輸入一個正整數n = '))
result=sumnfunc(num)
print('1累加到n的結果 = ', result)
|
# Coding Challenge Level 2 - Find the max and min of a Python Set
#
# Print the max and min numbers of this set
# set([15, 11, 8, 15, 32, 20])
# For example 8 and 32
example_set = ([15, 11, 8, 15, 32, 20])
# Approach 1 - Using the built-in functions:
print("\nBuilt-in functions:")
print("The maximum number in the ... |
import numpy as np
class Net():
"""
Implements a neural network with a user-determined number and size of hidden layers.
Except for the final hidden layer, each hidden layer is followed
by a non-linear function f(x) = x when x >= 0, x/100 when x < 0.
Predicts by selecting the index of the maximum outp... |
from collections import deque
from typing import Optional, Set, Text
LIMIT = 3
class Manager:
def __init__(self, limit: Optional[int] = LIMIT) -> None:
self.queue = deque() # 待抓取的网页
self.visited = dict() # 已抓取的网页
self.limit = limit # 进入待爬取队列重试上限
if self.limit is None:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The tests."""
from unittest import TestCase
from fzbz import FizzBuzz
class FzBzTest(TestCase):
"""Fizz Buzz Test."""
def setUp(self):
"""Setup."""
self.obj = FizzBuzz()
def test_num(self):
"""The return value should be based of F... |
rival = -999999
contador = 0
while True:
jugador = int(input("Dame tu mejor numero: "))
if jugador == -1:
break
contador = 1
if jugador > rival:
rival = jugador
if contador != 0:
print("el nuevo rival es: ",rival)
# Otro código
while True:
palabra = input('Rompe el hechizo: '... |
# Si el ingreso del ciudadano no era superior a 85,528 pesos, el impuesto era igual al 18% del ingreso menos 556 pesos y 2 centavos
# (esta fue la llamada exención fiscal ).
# Si el ingreso era superior a esta cantidad, el impuesto era igual a 14,839 pesos y 2 centavos, más el 32% del excedente sobre 85,528 pesos.
# No... |
def validate(n):
n_list = [int(x) for x in str(n)]
doubled_list = list()
# Even
if len(n_list) % 2 == 0:
doubled_list = [x*2 if index % 2 != 0 else x for index, x in enumerate(n_list, 1)]
# Odd
else:
doubled_list = [x*2 if index % 2 == 0 else x for index, x in enumerate(n_list, 1)]
cleaned_list = [int(str(x... |
items = []
num_items = int(input("How many items have you got? : "))
for i in range(0, num_items):
item = [input("\nLabel: "), int(input("Size: "))]
items.append(item)
print("Your items are: "+str(items))
bin_size = int(input("What is the size of your bins/containers? : "))
bins = [["bin1", bin_size, []]] ... |
#!/usr/bin/env python
'''
search a fasta file for a specific sequence
Usage:
python find_sequence.py --target ATAAT < sequence.fa
'''
import argparse
import collections
import logging
import sys
def reverse_complement(sequence):
'''
return the reverse complement of the input sequence
TODO: YOU NEED... |
import argparse
def synthesize_text(speech):
"""Synthesizes speech from the input string of text."""
from google.cloud import texttospeech
client = texttospeech.TextToSpeechClient()
input_text = texttospeech.types.SynthesisInput(text=speech)
# Note: the voice can also be specified by name.
... |
num=input()
num=num.split()
num1=int(num[0])
num2=int(num[1])
val=input()
val=val.split()
list1=[]
sum1=0
for i in range(num1):
list1.append(int(val[i]))
for j in range(num2):
sum1=sum1+list1[j]
print(sum1)
|
num=int(input())
val=1
for i in range(1,num+1):
val=val*i
print(val)
|
from pprint import pprint
class Animals():
type_animals = "Живое существо"
name = "Без имени"
weight = 0
fill = 0
state = "Отдыхает"
sound = "......."
def __init__(self, name, weight):
"""
Определяем имя и вес
"""
self.name = name
self.weight = weigh... |
import random
def choose():
#List of the words that are used.Can be changed according to you.
words=["umbrella","america","programming","debugging","festival","holidays","randomly","permutation","combination","outstanding","wonders","chocolate","cricket","football","volleyball","smartphone","smartwatch","face... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''游戏逻辑类-总类'''
import random
import copy
# session暂时存储:
# row,col,array(暂时使用一维数组即可)
# 测试专用方法
# 行数,列数,种类数
def test(row_s, col_s, type_s):
row = 5
col = 5
type = 1
if row_s != '':
try:
row = int(row_s)
except:
... |
counts = dict()
line = input(' ')
words = line.split()
for word in words :
counts[word] = counts.get(word,0) + 1
print(counts) |
numero_filas=5
numero_columnas= 14
meses = ["","En","Feb","Mar","Ab","May","Jun","Jul","Agos","Sep","Oct","Nov","Diciem","Total "]
materias = ["","Español ","Matematicas","Geografia ","Total "]
def llenar(matriz,num_filas,num_columnas,mensaje):
print(mensaje)
res1 = 0
res2 = 0
res3 = 0
res4... |
class Persona:
def __init__(self,nom, ed, indj):
self.nombre = nom
self.edad = ed
self.ind = indj
def mostrar(self):
print("Nombre: {} \nEdad: {}\nIND: {}".format(self.nombre, self.edad, self.ind))
def mayor(self):
if (self.edad >= 18):
print ("E... |
#13.1. Pide al usuario el nombre de un fichero. Si el fichero existe, muestra su contenido
#(pero no como lista, sino las líneas una a una) y si no existe, escribe un mensaje de error adecuado
try:
frase = input("Dime el nombre de un fichero: ")
fichero = open(frase, "r")
except:
print("No se ha podido... |
numero = int(input("Dígame cuántas palabras tiene la lista: "))
if numero < 1:
print("¡Imposible!")
else:
lista = []
i = 0
while(i < numero):
print("Ingresa la palabra",str(i+1)+ ": ", end="")
palabra = input()
lista += [palabra]
i=i+1
print("La lista creada es:",... |
'''
EJERCICIO 1:
Escribir un programa que almacene una cadena de caracteres de contraseña en una variable,
ingresada por el usuario, pregunte al usuario por la contraseña e imprima por pantalla si
la contraseña introducida por el usuario coincide con la guardada en la variable sin tener
en cuenta mayúsculas y ... |
# TODO Create an empty list to maintain the player names
# TODO Ask the user if they'd like to add players to the list.
# If the user answers "Yes", let them type in a name and add it to the list.
# If the user answers "No", print out the team 'roster'
# TODO print the number of players on the team
# TODO Print t... |
def solution(A):
#print(A)
if len(A) == 0:
return -1
sort_a = sorted(A)
#print(sort_a)
l = len(A) // 2
#print("median:",l)
domi_candidate = sort_a[l]
B=[]
#print(A.count(domi_candidate))
if A.count(domi_candidate) > l:
for i in range(len(A)):
if A[i] =... |
CLOSING = {
']': '[',
')': '(',
'}': '{',
}
def solution(S):
stack = []
for ch in S:
if ch in CLOSING:
if not stack:
# encountered closing bracket but stack is already empty!
return 0
last = stack.pop()
if last != CLOSING[c... |
def array_count9(nums):
print (nums)
count = 0
for i in range (len(nums)):
if nums[i] == 9:
count = count + 1
print (count)
return count
array_count9([1, 2, 9, 9, 9]) |
# This program is to simulate the result of state meet by using the hypothesized distribution of win rate
# The result will be used to do the chi-square test to check if the events are independent
import multiprocess as mp
import pandas as pd
import numpy as np
import sys
import random
def test(repeat, desired, p, m... |
from bs4 import BeautifulSoup
print ("starting to scrape")
#Use code below when file to import is on web server :
response = urllib2.urlopen("http://www.goheels.com/SportSelect.dbml?DB_OEM_ID=3350&SPID=12960&SPSID=668154&SITE=UNC&DB_OEM_ID=3350")
html = response.read()
#end server version
#Use this code w... |
#!/usr/bin/python3
#
# czz78 made this script for OSCP preparation
#
from concurrent.futures import ThreadPoolExecutor
import argparse
duplicates = []
def read_words(inputfile):
with open(inputfile, 'r') as f:
while True:
buf = f.read(10240)
if not buf:
break
... |
# Name:
# Date:
# proj01: A Simple Program
# This program asks the user for his/her name and age.
# Then, it prints a sentence that says when the user will turn 100.
# If you complete extensions, describe your extensions here!
name = raw_input("Enter your name: ")
age = int(raw_input("Enter your age: "))
if age>100... |
def solution(dic):
max_value = 0
min_value = 0
list1 = sorted(dict1.iteritems())
max_value = max(list1, key=lambda list1:list1[1])
min_value = min(list1, key=lambda list1:list1[1])
#print max_value
#print min_value
tuple_numbers = max_value[1], min_value[1]
return tuple_numbers
dict... |
# Ask the user for a sentence. Sort the sentence and then
# return the sentence backwards.
# use a lambda function in this process
# Get our sentence and split on the words
our_sent = input("Please enter a sentence to reverse: ").split()
# Print the words sorted reverse by the last letter of the word
print(sorted(our_... |
person_list = {
'first_name': 'Clair',
'last_name':'Hommes',
'age':'38',
'city':'New York, NY',
'hair_color':'blonde',
'eyes': 'green'
}
for freaky in person_list.values():
print(freaky) |
# Simple earnings application
# Ask for their name, hourly wage, how many hours were worked.
# Calculate the money made.
# NOTE: Added looping with while and try statements to correct information entered.
def earnings_info():
while True:
name = input("What is your name: ")
hourly_wage = input("Wha... |
# def costOfDisneyFor(number_of_adults, number_of_children, number_of_days):
#1. How many parameters did we use to define this function?
#2 What datatype will we use as arguments when we call the function?
#3 What datatype will the return value be?
#4 How many internal lines of code are there in this fun... |
"""
NumPy functionality to compute distance-related functions on large matrices.
"""
import numpy as np
import sklearn.metrics
def NearestAB_N_NeighbourIdx_IgnoreNans(A, B, N):
"""
Find the indices of the N nearest neighbours in A for every point in B
Result is a 2D array of observation indices for A, of s... |
import view
from computerboard import ComputerBoard
import sys
NUMSHIPS = 3
view.welcome()
def run():
if len(sys.argv) > 1 and sys.argv[1] == "--cheat":
cheat = True
else:
cheat = False
# generate computer's board
size = view.ask_boardsize()
board = ComputerBoard(size, size)
... |
'''
@Description:
@Version: 2.0
@Author: yunruowu
@Date: 2020-01-02 10:12:30
@LastEditors : yunruowu
@LastEditTime : 2020-01-02 10:48:25
'''
#
# @lc app=leetcode.cn id=70 lang=python3
#
# [70] 爬楼梯
#
# https://leetcode-cn.com/problems/climbing-stairs/description/
#
# algorithms
# Easy (47.46%)
# Likes: 767
# Dislik... |
'''
@Description:
@Version: 2.0
@author: yunruowu
@Date: 2020-01-01 18:46:05
@LastEditors : yunruowu
@LastEditTime : 2020-01-01 18:58:51
'''
#
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] x 的平方根
#
# https://leetcode-cn.com/problems/sqrtx/description/
#
# algorithms
# Easy (37.30%)
# Likes: 276
# Dislikes: 0
#... |
number = input("Enter any positive number: ")
number = int(number)
if number % 2 == 0:
print("This is Even number")
else:
print("This is Odd number") |
def semordnilap(str1, str2):
if len(str1) != len(str2):
return False
elif len(str1) == len(str2) == 1:
return str1 == str2
elif str1[0] == str2[-1]:
return semordnilap(str1[1:], str2[:-1])
else:
return False
str1 = raw_input("first string: ")
str2 = raw_input("second string: ")
print semordnila... |
def monthlyCalculation (bal, inter, pay):
unpaid = bal - pay
return {
'remain': unpaid + unpaid*inter/12.0,
'pay_min': pay
}
def annualCalculation(bal, inter, pay):
remaining = bal
totalPaid = 0
for i in range(12):
monthly = monthlyCalculation(remaining, interest, pay)
remaining = m... |
# initializing the number of vertices
nV = 8
# initializing the infinity as an extremely large number
INF = 999
# function which implements the Floyd algorithm
def floyd_algorithm(source_graph):
# initialisation of the minimal distances matrix
distance = list(map(lambda i: list(map(lambda j: j, i)), source_gr... |
import graphics as g
import random
import sched, time
enemycounter = 5
score = 0
class board:
def __init__(self,w):
self.w = w
self.create()
self.instructions()
self.scorecounters()
self.deathline()
def create(self):
self.area = g.Rectangle(g.Po... |
'''fitnes function
creating individual
creating gen
selection from population
new gens(N-Best/M-random)
creating child
creating children
mutating word
mutating population
'''
#password==password que tentamos saber
#individual== a palavra escolhida
import random
import operator
#impor... |
def reverse(array): #reverse array
print(array[::-1])
def middle(array): #select elements in the middle of the array
print(array[1:-1])
def edges(array): #select only first and last
print(max(array),min(array))
def totalsum(array): # sum of all elements (countable)
print(sum(array))
def nlist(n,... |
import turtle
def star(dim):
rot = 144
x = 0
for i in range(15):
turtle.forward(dim)
turtle.right(144)
dim+= 5
turtle.exitonclick()
if __name__ == '__main__':
star(100)
|
import turtle
import math
def ball(pencil,color,radius):
y = 0
x = 0
#des
pencil.right(90)
for i in range(5):
pencil.pensize(5)
if i%2==0:
if i==0:
color = "blue"
elif i==2:
color = "black"
elif i==4:
... |
import random
#Retrieves the sum of Even and Odd numbers in a list
def evenOdd(array):
even = 0
odd = 0
for value in array:
if value%2 == 0:
even+= value
else:
odd+= value
print(array,even,odd)
#Ex: Insert 1º element of l1 and then 1º elem l2 and th... |
#####################################################
##Curso em Vídeo
##Aula 013 - Reajuste Salarial
##https://youtu.be/cTkivN8XcJ0
#####################################################
print('Calculando o reajuste salarial de um funcionário')
salario_atual = float(input('Qual é o salário do funcionário? R$ '))
aument... |
#####################################################
##Curso em Vídeo
##Aula 016 - Quebrando um número
##https://youtu.be/-iSbDpl5Jhw
#####################################################
print('Qual a porção inteira de um número?')
n = float(input('Digite um valor: '))
#print('O valor digitado foi {} e a sua porção i... |
#####################################################
##Curso em Vídeo
##Aula 011 - Pintando Parede
##https://youtu.be/mzSJpn9ldt4
#####################################################
print('Qual a metragem quadrada da parede?')
largura = float(input('Informe a largura da parede: '))
altura = float(input('Informe a al... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#时间结构体
class time_convert():
def __init__(self):
self.time = 0
self.year = 0
self.month = 0
self.day = 0
self.hour = 0
self.min = 0
self.second = 0
def input(self):
# time = input("pls input time")
... |
# -*- coding: utf-8 -*-
"""
@author: Trajan
"""
# Use Hungary Algorithm to get transformed matrix
def hungary(matrix_ori):
matrix = matrix_ori.copy()
# step 1
for i in range(len(matrix)):
matrix[i] = [k-min(matrix[i]) for k in matrix[i]]
# step 2
for i in range(len(matrix)):
... |
from win_keybindings import Keybinding
class TextInterpreter:
def __init__(self, transcription):
self.transcription = transcription
self.trigger = "Zelda"
self.keyboard = Keybinding()
self.commands = {
0: "turn off microphone",
1: "turn on microphone",
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
if head is None:
return head
last = None
while True:
tmp = head.next
head.next = last... |
import sys
def happy_ladybugs(bugs):
mappings = {}
free_cell = False
happy = True
for i, bug in enumerate(bugs):
if i == 0 and i + 1 < len(bugs):
happy = bug == bugs[i + 1]
elif i == len(bugs) - 1:
happy = bugs[i - 1] == bug and happy
else:
... |
l12,l22=input().split()
if l12[:len(l12)-1]==l22[:len(l22)-1]:
print("yes")
else:
print("no")
|
a = {"name": "Chetan", "age": 27}
print a # {"name": "Chetan", "age": 27}
b = dict({"name": "Vivek"})
print b # {"name":"Vivek"}
b = dict([("name","Vivek"), ("age",27)])
print b # {'age': 27, 'name': 'Vivek'}
# Accessable by key
print b['name'] # Vivek
# Update the value
# dict.update() does the same
# U... |
# ----------------------------------------------------------------------------------------
# Tuples are immutable - cannot change
# Mutable objects within a tuple are mutable
# Tuples are faster than lists
# ----------------------------------------------------------------------------------------
a = (1, 2, {"name": "C... |
# Dictionaries have a .get() method to search for a value instead of the my_dict[key] notation we have been using.
# If the key you are trying to .get() does not exist, it will return None by default:
# Delete a Key
available_items = {"health potion": 10, "cake of the cure": 5, "green elixir": 20, "strength sandwich... |
import sys # Module to modify error message
try:
x = int(input("x= "))
y = int(input("y= "))
except ValueError:
print("no puedes dividir entre palabras gafo")
sys.exit(1) # algo salio mal
try:
result = x / y
except ZeroDivisionError: # si algo sale mal entonces...
print("No puedes dividir entre 0 gafo")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.