text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 25 22:05:19 2016
Neural network for digit classification (MNIST) Kaggle competition
conv/conv/pool/dense/readout
Backend is Tensorflow
@author: dario
"""
# import the packages
from keras.models import Sequential, load_model
from keras.layers import... |
import tkinter as tk
from tkinter import messagebox
from math import pi
main_window = tk.Tk()
main_window.title("Checkout System")
CONTAINERS = ['Cube', 'Cuboid', 'Cylinder']
COLOURS = [
'purple',
'DarkSlateGray4',
'deep sky blue',
'light sea green',
'VioletRed2',
'gold'
]
CHEAP = 0.4
EXPE... |
def integer_number():
num_list = []
for i in range(1, 51):
if i % 2 == 0:
num_list.append(i)
else:
False
# return num
return num_list
print(integer_number()) |
import random
from tkinter import *
import tkinter
import math
running = False
sizeOfWindowX = 1000
sizeOfWindowY = 1000
linesEachSide = 600
firstCube = []
lastCube = []
currentCount = 0
lastMovedCubes = []
grid = []
walls = []
noSol = False
foundIt = False
pathPlaces = []
window = Tk()
window.title("Graph Generat... |
import math
import os
import random
import re
import sys
def main(n):
if n == 3:
print('Weird')
elif n == 5:
print('Weird')
elif n > 1 and n < 6:
print('Not Weird')
elif n >= 6 and n <= 20:
print('Weird')
elif n > 20 and n <= 28:
print('Not Weird')
elif ... |
"""
This module implements a simple function which discretizes point
locations into images
"""
__author__="Igor Volobouev (i.volobouev@ttu.edu)"
__version__="0.2"
__date__ ="Feb 25 2016"
from numpy import zeros
def imageArray2d(xSequence, ySequence, nx, xmin, xmax, ny, ymin, ymax):
"""
This function fills e... |
"""
This module provides a reasonably complete vector class for 3-d calculations.
"""
__author__="Igor Volobouev (i.volobouev@ttu.edu)"
__version__="0.5"
__date__ ="Jan 29 2018"
import math
class V3:
"Basic 3-d vector class."
def __init__(self, x=0.0, y=0.0, z=0.0):
# Use floats for internal represen... |
#!/usr/bin/env python3
# Created by: Jacob Bonner
# Created on: September 2021
# This program draws a circle with a radius of 75 pixels
import pygame # Importing the pygame library
def main():
# This function will create a circle with a radius of 75 pixels
# Initializing a surface object for the shape... |
class ListNode:
def __init__(self, data=None, next=None, prev=None):
"""
A node in a doubly-linked list.
"""
self.data = data
self.next = next
self.prev = prev
def __repr__(self): # 'toString' Impl
return repr(self.data)
class DoublyLinkedList:
def... |
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __repr__(self):
return str(self.value)
class Queue:
def __init__(self):
self.first = None
self.last = None
self.length = 0
def __repr__(self):
curr... |
from collections import deque
from itertools import chain
import numpy as np
def windowed(seq, n, fillvalue=None, step=1):
"""Return a sliding window of width *n* over the given iterable.
>>> all_windows = windowed([1, 2, 3, 4, 5], 3)
>>> list(all_windows)
[(1, 2, 3), (2, 3, 4), (3, 4, 5)]... |
# Name:Javier Villalba
# Date:9/26/19
# Period:
# Lab: PythonLogic.py
# Description: Write the 4 functions described below in comments
#
# Style - Code format, whitespace and PEP-8 style is followed making code easy to read.
# Comments - Blocks of code are well commented, every function has a descriptive... |
import numpy
import os
import random
import movement
def check_row(board):
for row in board:
size = len(row)
for j in range(0,size-1):
if row[j] == row[j+1]:
return True
return False
def check_col(board):
size = len(board[0])
for j in range(0,size-1):
col = board[:,j]
for k in range(0,size-1):
... |
"""
para un juego que va a tener 20.000 planetas necesitamos formar nombres
para cada uno de los planetas.Cres una lista con todos los posibles nombres de 3 silavas
que se pueden formar con 10 consonantes y 5 vocales, de tal forma que cada letra sea seguida
de una vocal y no se repita ninguna letra en cada uno de los n... |
import time
inicio = time.time()
for i in range(11):
for j in range(10):
for f in range(10):
print("{} {} {} ".format(i,j,f))
final = time.time()
print("el adgoritmo tardo: ",final-inicio) |
amigos = [["clara", 25], [ "sebastian", 19],["sergio", 32],["juan",27]]
amigos.append(["sonia"])
amigos[4].append(1)
for amigo in amigos:
print("{} edad: {}".format(amigo[0],amigo[1]))
print(amigos) |
"""
Cinco amigos van a hacer una carrera:
Tomas, Maria, Laura, Miguel, Carlos
Muestra todos los posibles resultados que se pueden dar
en la carrera"""
amigos = ["Tomas","Maria","Laura","Miguel","Carlos"]
Contador = 0
for i in amigos:
for j in amigos:
for k in amigos:
for m in amigos:
... |
import urllib.parse
import json
import urllib.request
#Consumer Key ZsamDKpuQn6SSr0BwKH4LkuTAKJfpCe2
#Consumer Secret Tdqlc6zcha6shcW1
def build_map_quest_url(list_of_locations: list)-> str:
'''this function takes in the locations inputed in lets_begin
and returns a URL the can be used in the... |
def exchange(x, y):
y = x
x = y
return x, y
a = 2
b = 3
a, b = exchange(a, b)
print a, b
|
from gturtle import *
def square(sidelength):
repeat(4):
forward(sidelength)
right(90)
makeTurtle()
s = inputInt("Enter the side length")
square(s)
|
from math import sin
def sinc(x):
y = sin(x) / x
return y
print sinc("python")
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(input())
for i in range(t):
try:
a,b = map(int, input().split())
print(a//b)
except Exception as e:
print("Error Code:", e)
|
def count_substring(string, sub_string):
num = 0
check = True
starting_index =0
while check:
x = string.find(sub_string, starting_index)
if x== -1:
check = False
else:
num+=1
starting_index =x+1
return num
if __name__ == '__main__':
s... |
import re
x = input()
vowels = 'aeiouAEIOU'
consonants = 'qwrtypsdfghjklzxcvbnmQWRTYPSDFGHJKLZXCVBNM '
ans = re.findall(r'(?<=[%s])([%s]{2,})[%s]'%(consonants,vowels,consonants),x)
print('\n'.join(ans or ['-1']))
|
from searcher import Searcher
from grid import Grid
from math import sqrt
class OrderedQueue():
def __init__(self, reverse : bool = False):
self.reverse = reverse
self._values = []
def __len__(self):
return len(self._values)
def append(self, item, value):
try:
... |
# class student:
# def check_pass(self):
# if self.marks>=40:
# print("Passed")
# elif self.marks<40:
# print("Failed")
# student1 = student()
# student1.name="Hari"
# student1.marks=80
# did_pass =student1.check_pass()
# print(did_pass)
# student2 = stud... |
from sys import argv
script, user_name = argv
#Notice though that we make a variable prompt that is set to the prompt we want, and we give
#that to raw_input instead of typing it over and over.
prompt = '$'
print "HI I am %s, I'm the %s." % (user_name, script)
print "I'd like to ask you afew questions."
print "Do yo... |
def is_leap(year):
if year % 4 == 0 and (year % 400 == 0 or year % 100 != 0):
return True
else:
return False
def run():
leap_year = int(input('Ingrese un año: '))
if is_leap(leap_year):
print('Año Bisciesto')
else:
print('Año no Bisciesto')
if __name__ ... |
def run():
numero = int(input('Ingrese el limite del conteo: '))
for i in range(numero,0,-1):
print(i)
if __name__ == "__main__":
run() |
def run():
numero = int(input('Ingrese el tamano del cuadrado: '))
for i in range(numero):
for j in range(numero):
print('#', end="")
print()
if __name__ == "__main__":
run() |
def run():
numero = int(input('Ingrese el tamano del trinagulo: '))
for i in range(numero):
print('#'*i)
for i in range(numero,0,-1):
print('#'*i)
if __name__ == "__main__":
run() |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: 模块1
# Purpose:
#
# Author: Panywa
#
# Created: 29/12/2016
# Copyright: (c) Panywa 2016
# Licence: <your licence>
#-----------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: 模块1
# Purpose:
#
# Author: 潘先生
#
# Created: 26/12/2016
# Copyright: (c) 潘先生 2016
# Licence: <your licence>
#-----------------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: 模块1
# Purpose:
#
# Author: 潘先生
#
# Created: 26/12/2016
# Copyright: (c) 潘先生 2016
# Licence: <your licence>
#-----------------------------------------------------------------------------... |
'''
======================
User inputs in Python
======================
We will use this file to write a simple program that
let's user feed data to program
'''
# print("Hello user,")
# name = input("What can I call you?\n")
# age = int(input("How old are you?\n"))
# print("Hi %s, you are going to be %s next year" % ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 29 21:57:46 2018
#inspirado em: https://dev.to/mxl/dijkstras-algorithm-in-python-algorithms-for-beginners-dkc
Referências: Caderno
A first Look at Graphs Theory
Python para Zumbis
https://docs.python.org/3/tutorial/datastructu... |
# -*- coding: utf-8 -*-
# exemplo de uma função bastante simples
def soma(a, b):
return a + b;
# exemplo de uma função um pouco mais complexa
def fib(n):
"""
Descrição
---------
Algoritmo iterativo para a sequência de Fibonacci.
Entradas
--------
n : um número inteiro positiv... |
class Animal:
#constructor
def __init__(self, tipo):
self.tipo = tipo
def __setSangue__(self, s):
self.sangue = s #quente ou frio
def getSangue(self):
print(self.sangue)
def getTipo(self):
print(self.tipo)
class Pet(Animal):
#constructor
def __init__(self, nome, qtdPatas, somEleEmite):
Ani... |
x = 6
#bad practice
def example3():
global x
x += 1
print(x)
print(example3())
def example():
z = 5
print(z)
print(example())
#best practice
def example2():
z = 7
print(z)
y = x + 1
print(y)
print(example2())
x = example2()
print(x) |
from proof_stuff.source.data import cases
from proof_stuff.source.proof_loops import prove_target_set, prove_1_to_1
for case in cases:
case['upper'].substitute(n=case['n'], inplace=True)
case['lower'].substitute(n=case['n'], inplace=True)
big_sep = "\n" + 79*"#" + "\n"
small_sep = 49*"*"
print(big_sep)
prin... |
'''
-find how many digits are in a given number
-find a digit
--raise number to the power
-Find some of the powered digits
-Compare final number to input number
'''
def is_armstrong(number):
print(number)
strnumber = str(number)
numberofdigits = len(strnumber)
sum = 0
for strdigit in strnumber:
digit = int(str... |
students=["Engel","Slosar","Boas","Spice" ]
students.append(input("enter student"))
print(students)
students.append(input("enter student"))
print(students)
gpas = [4,5.4,5.4,4.5,4.7]
print (gpas[3])
message = "The Quick Brown Fox Jumped Over The Fence"
print(message)
words = message.split()
print(words)
lines = "-... |
import random
number = input("Enter Number:")
number = int(number)
answer = random.randint(0,25)
while(number > answer):
print("Too High")
number = input("enter a number:")
number = int(number)
if(number > answer):
print("Too High")
elif(number < answer):
print("Too Low")
else:
print("You got it")
if(n... |
import sys
import urllib.request
import os
#First Exercise 1
argList = sys.stdin.readline()
print(argList)
count = 1
def download(url, counter):
print ("\n")
print ("Downloading Item Number: ", (counter))
urlSplit = os.path.basename(url)
urlSplit = urlSplit[:-1]
print ("File will be named: ",urlSplit)
print("Dow... |
#!/bin/python3
S = input()
for x in ['isalnum', 'isalpha', 'isdigit', 'islower', 'isupper']: print(any(getattr(y,x)() for y in S))
|
#!/usr/local/bin/python3
import xml.etree.ElementTree as etree
n = int(input())
lis = ''
count = 0
for i in range(n):
lis += input()
tree = etree.fromstring(lis)
for i in tree.iter():
count += len(i.attrib)
print(count)
|
#!/bin/usr/python3
import datetime
testcase = int(input())
for i in range(testcase):
time1 = input().strip()
time2 = input().strip()
timeformat = "%a %d %b %Y %H:%M:%S %z"
t1 = datetime.datetime.strptime(time1, timeformat)
t2 = datetime.datetime.strptime(time2, timeformat)
print(int(abs(t1 - t2)... |
#!/usr/bin/python
a = int(input())
b = int(input())
c = int(input())
d = int(input())
result = 0
power1 = 1
power2 = 1
for i in range(0,b):
power1 = long(power1 * a)
for i in range(0,d):
power2 = long(power2 * c)
result = long(power1 + power2)
print (result)
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
from math import sqrt, acos, degrees
AB = int(raw_input())
BC = int(raw_input())
AC = sqrt((AB * AB) + (BC * BC))
AM = AC / 2.0
print str(int(round(degrees(acos((BC/2.0)/AM))))) + "°"
|
class Car:
def __init__(self, make, model, year, color):
self.make = make
self.model = model
self.year = year
self.color = color
def carFacts(self):
facts = "\nMake: {}\nModel: {}\nColor: {}\nYear: {}\n".format(self.make,self.model,self.color,self.year)
return f... |
"""
Simple genetic algorithm class in Python
TODO:
- INSTRUCTIONS (note that genemax is INCLUSIVE)
- Multithread fitness evaluation
- Errors shouldn't call exit - use exceptions
- Parameterise everything (max age, individuals to keep on reset)
- Variable length chromosomes
- More crossover,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
for i in range(1, 101):
result = ""
if i % 3 == 0:
result += "Fizz"
if i % 5 == 0:
result += "Buzz"
print(result or i)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 1 11:53:43 2017
@author: Robert
"""
import random
count= 0
checklist = ['heads','heads','heads','heads','heads','heads','heads','heads','heads','heads']
result = []
def addtolist(dict):
dict.append(random.choice(['heads','tails']))
global count
count += 1
... |
inventory = {'rope': 1, 'torch': 4, 'gold coin': 9, 'dagger': 2, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin' 'ruby']
print('Inventory:')
def addToInventory():
for k, v in inventory.items():
for i in range(len(dragonLoot)):
# findCount = 0
#i = dragonLoo... |
# lettercount.py
# A Python script that counts every letter in a given text.
# http://www.meganspeir.com
#
# Copyright (C) 2013 Megan Speir. All rights reserved.
#
# Licensed under The BSD 3-Clause License. You may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http... |
stack = 5*[float("inf")]
n = int(input('Введите число N: '))
lst = list(map(int, input('Введите N чисел: ').split()))
for i in range(len(lst)):
#adding elements
if max(stack) > lst[i]:
stack += [lst[i]]
stack.sort()
if len(stack) > 5:
stack.pop()
#print
for j in range(len(stack)-1, -1, -1):
if stack[j] !... |
def euclides_mdc(dividendo, divisor): #maximo divisor comum pelo metodo de euclides
while divisor != 0:
temp = divisor
divisor = dividendo % divisor
dividendo = temp
return dividendo
def euclides_recursivo_mdc(dividendo, divisor):
if divisor == 0:
return dividendo
... |
import os
import csv
budget_csv = os.path.join('Resources', 'budget_data.csv')
#budget_csv = os.path.join('..', '..', '..', '..', 'columbia', 'myWork', 'homework', '03-Python', 'Instructions', 'PyBank', 'Resources', 'budget_data.csv')
with open(budget_csv, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimi... |
words = "It's Thanksgiving day. It's my birthday, too!"
print words.find("day")
print words.replace("day", "month")
x = [2, 54, -2, 7, 12, 98]
max = 0;
min = 0;
for n in range(0, len(x)):
if max < x[n]:
max = x[n]
if min > x[n]:
min = x[n]
print "max: ", max
print "min: ", min
y = ["hello"... |
import datetime as d
# classes
class Business:
def __init__(self, name, franchises):
self.name = name
self.franchises = franchises
class Franchise:
def __init__(self, address, menus):
self.address = address
self.menus = menus
def __repr__(self):
return "The address of the re... |
# Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Shortest Job First(SJF), which today you will be implementing.
#
# SJF works... |
# Your task is to create a function that will take an integer and return the result of the look-and-say function on that integer. This should be a general function that takes as input any positive integer, and returns an integer; inputs are not limited to the sequence which starts with "1".
#
# Conway's Look-and-say se... |
import random
import time
def getRandomNumber(low, high):
return random.randrange(low, high)
def getUserInput(message, expectedInput = ['Y', 'N']):
user_input = input(message+ ' \n')
if user_input.upper() in expectedInput:
return user_input.upper()
else:
print('That was not expected, ... |
array = ["Sara" , "Ghada", "Afnan","Ghalia", "Abeer"]
for x in array:
if x == "Afnan" :
continue
elif x=="Ghalia":
break
print(x)
for x in range(10):
if x % 2 == 0:
continue
print(x) |
#be om en mening och gör om till lista
valdmening = (input("Skriv din mening: "))
#kons = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "W", "x", "z"]
konssmall="bcdfghjklmnpqrstywxz"
konsbig = konssmall.capitalize()
kons = konssmall + konsbig
nymening = ""
for i in range(len... |
score = 0 #Set score to zero
print("''**Welcome To The Magical Game!**''") #printing gamename
name = input("Please insert your magical name: ")
ans = int(input("What is 2*3? ")) #question 1
if ans == 6:
print("Good job! you got one point!")
score = score+1 ... |
list = [2, 6, 3, 0, 4, 13]
nylista = []
lenghtlist = len(list)
for i in range(len(list)):
minsta = min(list)
list.remove(minsta)
nylista.append(minsta)
print(nylista) |
# Be om siffror
numbers = (input("insert your numbers: "))
# gör om numbers till lista
num = []
for x in range(len(numbers)):
num.append(int(numbers[x]))
#lägg till första siffran igen på slutet
num.append(num[0])
print(num)
#gör ny lista
nynum=[]
for i in range(len(num) -1):
if num[i] == num[i +1]:
... |
from eldar import Query
import pandas as pd
# build dataframe
df = pd.DataFrame([
"Gandalf is a fictional character in Tolkien's The Lord of the Rings",
"Frodo is the main character in The Lord of the Rings",
"Ian McKellen interpreted Gandalf in Peter Jackson's movies",
"Elijah Wood was cast as Frodo ... |
list_1 = [1, 2, 3, 4, 5]
# O(1) - Constant
def constant(n: list):
return n[0]
# O(N) - Linear
def linear(n: list):
for i in range(len(n)):
print(i)
# O(N^c) - Exponential
def exponential(n: list):
for i in range(len(n)):
for j in range(len(n)):
print(i, j)
# Combination -... |
from List import List
from copy import deepcopy
class LinkedList(List):
def __init__(self):
self.head = None
self.tail = None
def set_head(self, h):
self.head = h
def set_tail(self, t):
self.tail = t
def is_empty(self):
return self.head is... |
class Test:
def __init__(self, a):
self.a = a
def seta(self, b):
self.a = b
def f(self, b):
#self = Test(b)
self.seta(b)
t = Test(1)
t.f(2)
print(t.a)
|
class Solution:
def isBalanced(self, root): #recursive
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
def depth(node):
if not node:
return 0 # leaves has no length
left=depth(node.left)
... |
import functools
x=[1, -2, 3, -50, 40, -90]
result = filter(lambda x: x>0, x)
# возвести все положительные элементы последовательности в квадрат
def positive_in_square(el):
if el>0:
return el**2
else:
return el
print(list(map(positive_in_square, x)))
# map принимает 2 параметра: func и *it... |
"""
Algorithm Design and Applications: An Example of Pseudo-Code
"""
# Algorithm arrayMax(A, n):
# Input: An array A storing n >= 1 integers.
# Output: The maximum element in A.
# currentMax <- A[0] ............2
# for i <- 1 to n - 1 do.........1 + n - 1
# if currentMax < A[i] then....4(n - 1)
# currentMax ... |
def fibonacci_series_r(present_term, next_term, term_count): # Using Recursion
if term_count > 0:
print(present_term, " ", end="")
fibonacci_series_r(next_term, (present_term + next_term), (term_count - 1))
else:
print("")
def fibonacci_series(term_count):
present_term = ... |
def is_armstrong(num):
temp, s = num, 0
while temp > 0:
s += (temp % 10) ** 3
temp = temp // 10
if s == num:
return True
else:
return False
n = int(input("Enter number: "))
if is_armstrong(n):
print("Armstrong!!")
else:
print("Not Armstrong")
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#check whether user input is num
import re
import time
number_str = input("請輸入一個數字,將列出可整除這個數字的integer:")
num_pattern = r'^[0-9]+$'
match = re.match(num_pattern, number_str.strip())
number_int = int(number_str)
"""first failure debug long time finding num%number_int -> nu... |
willing_tocontinue = input(" Would you like to start the game type 'y' if you would like to or 'n' if you want to exit: ")
if willing_tocontinue == "y":
print ("great let's get started")
else:
exit(print("well thank you for stopping by see you next time"))
user_name = input(" Ok now it's time to get to know yo... |
import requests, sys
base_url = 'https://api.trello.com/1/{}'
"""
Enter Key and ID of your Trello account.
Then create or choose the board on the Trello and copy the board ID.
"""
board_id = 'Write the board id here'
auth_params = {
'key': 'Write your Trello key here',
'token': 'Write your Trello i... |
import unittest
from lexer import LexicalAnalyzer
from parser import RegExParser
class MyTestCase(unittest.TestCase):
def test_primitive_parser(self):
re = "a"
l = LexicalAnalyzer()
l.run(re)
parser = RegExParser(l)
tree = parser.regex()
print(tree)
... |
import datetime
""" Person class with name attribute.
Real life anaglous: Library customers """
class Person():
'''Initialize person '''
def __init__(self,name,timeobj):#,userlist):
self.name = name
self.timeobj = timeobj
def PrintName(self):
return ("Customer name : %s "% self._name)
def SetTime(self,... |
"""
list_node.py
Contains a simple ListNode class,
which simply has 'val' and 'next' fields.
"""
class ListNode:
""" Models a single node in a singly-linked list.
Has no methods, other
than the constructor.
"""
def __init__(self, val):
""" Constructs the object; calle... |
'''
File: letter_swaps.py
Author: Kevin Falconett
Purpose: swaps every possible
character in a string
'''
def swap(i1,i2,string):
'''
Swaps the letters at string[i1]
and string[i2]
Parameters:
i1 (int): first index
i2 (int): second index
... |
"""
File: puzzle_match
Author: Kevin Falconett
Purpose: check if puzzle pieces
can be joined left to right
or top to bottom
"""
def puzzle_match_LR(left, right):
"""
Checks to see if the right
side of left can be matched
to the left side of right
... |
"""
File: classify.py
Author: Kevin Falconett
Function: determines whether the first letter of a word
is a vowel, consonant, or neither
"""
if __name__ == "__main__":
string = input("input: ") # retrieve input
vowels = ["A", "E", "I", "O", "U"] # list of vowels
consonants = [
... |
"""
File: swap.py
Author: Kevin Falconett
Function: If string input is even, swap first and second halves of string.
if the length of the string is odd, then the first part of the string will be the portion of the string from
the beginning to to the middle, but not including the middle chara... |
class YuChen:
'yuchen的测试类'
def __int__(self):
pass
def test_list(self):
'列表函数'
list1 = ['go','to','school','by','bus'];
list2 = ['1','2','3','4','5','6'];
print(list1[0]);
del list1[0]; #删除列表元素 remove()方法
print(list1[0]);
list2[0]= 99; #更新列表元... |
'''
Tetris Project
Creators:
Paul Vetter, Seth Webb, Sarah Rosinbaum, & Anna Woodruff
Engr 102 final project
The game will consist of 4 different files:
JTetris - present the GUI for tetris in a window and do animation
Piece class within
Brain - simple heuristic logic that knows how to play the te... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 模块字符串
'''
学习使用seaborn中的分布图distribution plot及其参数
'''
# 模块导入
# 第三方模块导入
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# seaborn的全局配置
sns.set(style="white", palette="muted", color_codes=True)
# 伪随机数生成器
rs = np.random.RandomState(10)
# Set up t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 模块字符串
'''
学习使用seaborn分组盒图Group boxplots。
'''
# 模块导入
# 标准库导入
import ssl
# 第三方库导入
import seaborn as sns
import matplotlib.pyplot as plt
# seaborn global configuration
sns.set(style="ticks", palette="pastel")
# urllib's ssl cert configuratioon
ssl._create_default_https_co... |
tabela = [' '] * 10
rodada = 1
n1 = 0
n2 = 0
# função para imprimir a tabela a cada movimento;
def imprimeTabela():
print(tabela[1], '|', tabela[2], '|', tabela[3])
print("----------")
print(tabela[4], '|', tabela[5], '|', tabela[6])
print("----------")
print(tabela[7], '|', tabela[8... |
print("PLAYER 1 IS ASSIGNED X and PLAYER 2 IS ASSIGNED O BY DEFAULT")
main = [] #list
for x in range(0, 9, 1):
main.append(str(x + 1)) # assigning values in the matrix
playerOneTurn = True # initialization
winner = False # initialization
def printBoard():
for i in range(7,0,-3) : # got right ... |
x = float(input("Enter a number: "))
n = int(input("Enter the degree of accuracy: "))
def fact(i):
if(i==1):
return 1
else:
x = i*fact(i-1)
return x
ex = 1
print(fact(n))
for i in range(1,n):
ex = ex + ((x**i)/fact(i))
print(ex)
|
banyak_data = int(input("Masukkan jumlah data: "))
a = []
jumlah = 0
for i in range(0 ,banyak_data):
nilai = int(input("Masukkan data ke-%d: " % (i + 1)))
a.append(nilai)
jumlah = jumlah + nilai
rata_rata = jumlah/banyak_data
print("Rata rata: ", format(rata_rata, '.2f'))
|
"""
Q3.Write a menu driven program that shows the working of a library. The menu option should be
--ADD BOOK INFORMATION
--DISPLAY BOOK INFORMATION
--LIST ALL BOOKS OF GIVEN AUTHOR
--LIST THE COUNT OF BOOKS IN THE LIBRARY
--EXIT
"""
database = {}
z=True
while(z):
class Library:
print("-... |
#Q6.Write a program to accept 5 names from user and store these names into an array sort these array element in alphabetical order.
list1=[]
z=True
while(z):
n=input("Enter a name:\n")
list1.append(n)
a=input("do want to enter a name(y/n):\n")
if a!="y":
z=False
print("your list is:\n... |
"""
Write a program to accept three sides of a triangle as input and print whether the Trangle is valid or Not.
(The trangle is valid, if sum of each of the two sides is greater then the third side.)
"""
class Triangle:
def check(self,a,b,c):
if (a+b>c):
print("triangle is valid")
... |
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input())
arr=[]
for N_itr in range(N):
firstNameEmailID = input().split()
firstName = firstNameEmailID[0]
emailID = firstNameEmailID[1]
if re.sear... |
class NextSequence:
# operation = ["*", "+","-","/","^"]
sequence = []
2, 4, 6, 8
def __init__(self):
print("Start")
def ask_sequence(self):
temp = input("Input your sequence, make sure your numbers are split by ',' with no spaces\n")
self.sequence = temp.split(",")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.