text stringlengths 37 1.41M |
|---|
def identify():
print("What lies before us?")
lier=input()
if(lier=="a large boulder"):
print("It's time to run!")
else:
print("we will be fine")
identify() |
def box(name):
value=len(name)
print(" -"*value)
print("| " + name + " |")
print(" -"*value)
def lwr(name):
print(name.lower())
def upr(name):
print(name.upper())
def mrd(name):
print(name[::-1])
def repeat(name):
hmt=int(input("How many times do want to repeat: "))
for co... |
number=input("Write a 5 digit-number:\n")
size_number=len(number)
print("1) Display ASCII Triangle - display the number in an ascii art triangle.")
print("2) Display Left Digits Triangle - display digits of the number so that they form a triangle aligned on the left.")
print("3) Display Right Triangle – display the... |
print("selamat datang di kelas python")
print("1+1={}".format(1+1))
print("3-1={}".format(3-1))
print("4*2={}".format(4*2))
print("81/9={}".format(81//9))
print("100%3={}".format(100%3))
print("6**1200={}".format(6**1200))
print("1+1={}, dan 2+2={}".format(1+1,2+2))
|
from random import randint
num = randint(0, 100)
count = 0
while count < 8:
guess = int(input("Select a number from 0 to 100"))
count += 1
if guess in list(range(0,101)):
if guess == num:
print("You are correct!")
break
if guess < num:
print("Sorry, your ... |
weekly_event = int(raw_input()) * 2
goal_number = int(raw_input())
surplus = 0 if goal_number % weekly_event == 0 else 1
print(str(goal_number / weekly_event + surplus))
|
#exercise3 number maths
from __future__ import division
print "I will now count m hens:" # print stmnt
print "hens", 25 + 30 / 6 # expression evaluation
print "roosters", 100 -25 * 3 % 4 # expression evalution
print "now i will count eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # expression evalution
print "is it t... |
# exercise 30
people = 30
cars = 40
buses = 150
if cars > people:
print "there are no roads for people to walk!"
elif cars < people:
print "this world is growing too fast!"
else:
print "why cant we know?"
if buses > cars:
print "i love to go by buses!"
elif buses < cars:
print "what happened to all the buses"
e... |
# exercise 31
print "you are going to enter a zoo or a museum? for zoo press 1, for museum press 2"
ans = raw_input("--> ")
if ans == "1":
print "you chose zoo, a tiger is on the loose! what are you going to do?"
print "1) go find the tiger before tiger finds you"
print "2) run for your life!"
zoo = raw_input("--... |
# TCP_client_easy.py
# create_connection() 이용한 TCP 클라이언트 프로그램
import socket
# TCP 소켓 생성과 연결
sock = socket.create_connection(("localhost", 2500))
# 메시지 전송
message = "클라이언트 메시지"
print("sending {}".format(message))
sock.sendall(message.encode())
data = sock.recv(1024) #데이터 수신
print("received {}".format(data.decode())... |
import sys
filepath='C:\\Users\\himan\\Documents\\Himani-Data\\Git-Working\\practice_python\\Config\\'
def ask():
while True:
try:
x,y = map(int,raw_input("Enter two number to divide ").split())
except ValueError:
print "Incorrect value"
else:
try:
... |
# working on it
# import sys
import random
#from Config import Bk_card_value
# Used for card shuffle
# Boolean used to know if hand is in play
playing = False
chip_pool = 100 # Could also make this a raw input.
bet = 1
restart_phrase = "Press 'd' to deal the cards again, or press 'q' to quit"
# Hearts, Diamonds,Clubs... |
a = "hello"
b = "world"
c = a.upper() + " " + b.upper()
d = c + "!"
print(d)
e = d + " This {} my first type in {} when my age {} {}" #The format() method takes unlimited number of arguments, and are placed into the respective placeholders
f = "was"
g = 23
h = "python"
i = e.format(f,h,f,g)
print(i)
p = "I want to ... |
listOne = ["apple","banana","charry","orange", "kiwi", "melon", "mango"]
print(listOne)
if "melon" in listOne:
print("Yes, melon here in the list")
else:
print("No! melon don't exist here")
print(len(listOne)) #list length
|
import sqlite3
import csv
class Database():
"""This is a simple multi use case database class"""
def __init__(self, useMemory=True):
if useMemory:
self.conn = sqlite3.connect(':memory:')
else:
user_input = input("Name of db?\n")
self.conn = sqlite3.connect(f"{user_input}.db")
self.c = s... |
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import neighbors, metrics
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd
data = pd.read_csv('car_data.csv')
#print(data.head())
#We d... |
class stack(object):
def __init__(self):
self.items=[]
def is_empty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(se... |
def pal(a):
if len(a)<1:
return True
else:
if a[0]==a[-1]:
return pal(a[1:-1])
else:
return False
a=str(input("enter the string"))
if pal(a)==True:
print("palindrome")
else:
print("not a palindrome")
|
str=input("enter the string")
vowels=0
for i in str:
if (i=='a'or i=='e'or i=='i'or i=='o'or i=='u'):
vowels=vowels+1
print("no of vowels are:")
print(vowels)
|
import matplotlib.pyplot as plt
from numpy import linspace, pi, cos, sin
import matplotlib.animation as animation
#from matplotlib import style
def table2(n, mod):
"""Trace la table de mutliplication "modulaire" de n modulo mod"""
#tracé du cercle
X1 = linspace(0, 2*pi, 1000)
X = cos(X1)
Y = sin(X... |
from rnn import CharGen
from rnn.train_model import train
train_new_model = True
model_name = 'shakespeare'
if train_new_model: # Create a new neural network model and train it
char_gen = CharGen(name=model_name,
bidirectional=True, # Boolean. Train using a bidirectional LSTM or unidirect... |
"""
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
s = 0
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player... |
def is_palindrome(self, targetString: str) -> bool:
stringArray = []
for character in targetString:
if character.isalnum():
stringArray.append(character.lower())
while len(stringArray) > 1:
if stringArray.pop(0) != stringArray.pop():
return False
return True |
# Your goal for this question is to write a program that accepts
# two lines (x1,x2) and (x3,x4) on the x-axis and returns whether they overlap.
# As an example, (1,5) and (2,6) overlaps but not (1,5) and (6,8).
# Assumptions
# a <= b and a < c
# c <= d and b < d
def isOverlapping (a, b, c, d):
if a==... |
"""
Create a list called emotions that contains the first word of every line in emotion_words.txt.
"""
f = open("emotion_words.txt","r")
emotions = list()
for line in f:
emotions.append(line.split()[0]) |
"""
Using the file school_prompt.txt, if the character ‘p’ is in a word, then add the word to a list called p_words.
"""
f = open("school_prompt.txt","r")
p_words = []
for line in f:
words = line.split()
for word in words:
if "p" in word:
p_words.append(word) |
import unittest
from flexi.tree import Tree
from flexi.tree import create_sub_tree
class TestTree(unittest.TestCase):
def test_list(self):
root = Tree()
create_sub_tree(root, 'tree').list = [1, 2, 3]
self.assertListEqual(root.tree.list, [1, 2, 3])
def test_get_item(self):
ro... |
# Algorithmic efficiency - O(V + E)
from collections import deque
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
def breadth_first_search... |
# lists can contain differing datatypes
myList = ['spam', 2.0, 5, [10, 20]]
#if you read/write to an nonexistant eliment, you get an index error
'spam' in myList # returns true
# negative indicies wrap backwards to end of list
# common way to traverse a list while getting the index
for i in range(len(my... |
# Exercise 2 - Pay program which avoids errors.
while True:
try:
hours = float(input("enter hours: "))
rate = float(input("enter rate: "))
break
except:
print('please enter a number.')
pay = hours * rate
print('your pay is : ' + str(pay))
|
"""
Chapter 8, Excercise 6
Write a program which repeatedly reads numbers until the user enters “done”.
Once “done” is entered, print out the total, count, and average of the
numbers. If the user enters anything other than a number, detect their
mistakeusing try and except and print an error me... |
# -*- encoding = utf-8 -*-
def swap(arr, i ,j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def insertSort(arr):
for i in range(1, len(arr)):
j = i
while j > 0:
if (arr[j] < arr[j-1]):
swap(arr, j, j -1)
j -= 1
return arr
def insertSort2(... |
"""The symbol table stores the locations of each of the symbolic
variable names and the relative scope of those variables.
The tables contains the name of the variable, the type (int, ClassName)
and the kind (field, local)
"""
class SymbolTable:
def __init__(self, global_table=None):
self.global_table = g... |
#LO HICE MEDIANTE UNA LISTA DEBIDO A QUE ES NECESARIO POSEER UNA GRAN CAPACIDAD DE COMPUTO PARA ENCONTRAR NUMEROS PERFECTOS
numerosperfectos = [6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128]
numero = input('ingrese el numero N: ')
if numero.isdigit():
numero = int(num... |
#! /usr/bin/env python3
"""Find the largest prime factor given a number."""
def get_largest_prime_factor(n):
prime_factor = False
prime_factor_val = None
factors = []
max_factor = n
x = 2
while x < max_factor:
if n % x == 0:
max_factor = int(n / x)
factors.insert(0, x)
factors.ins... |
import pandas as pd
import matplotlib.pyplot as plt
#import matplotlib as plt (Did not work to plot)
#import csv
file = "C:\\Users\\Pedrosky\\Documents\\GitHub\\learning\\Data\\Anacondas\\Panda\\2Dcsv.csv"
df = pd.read_csv(file)
new_df = df.sort_values(["x","y"], ascending=True,)
new_df.plot.scatter(["x"],["y"])
#n... |
#!/usr/bin/env python
#
# Based on the work of Pravin Paratey (April 15, 2011)
# Joachim Hagege (June 18, 2014)
#
# Code released under BSD license
#
from __future__ import print_function
from math import inf
#DISTANCE_INDEX = 1
class PriorityQueue:
""" This class illustrates a PriorityQueue and its associated ... |
# loops
# loops are repeated actions (iterations)
# loop wiht a counter (will run a certain number of times)
# n will become whatever you give it,
# the function is expecting a value from anywhere, but only 1 value
# so could have loop_with_counter(5)
# or my_num = 23 n\ loop_with_counter(my_num)
def loop_with_counter... |
#Problem Statement:
#Given an array, rotate the array to the right by k steps, where k is non-negative.
#Example 1:
#Input: [1,2,3,4,5,6,7] and k = 3
#Output: [5,6,7,1,2,3,4]
#Explanation:
#rotate 1 steps to the right: [7,1,2,3,4,5,6]
#rotate 2 steps to the right: [6,7,1,2,3,4,5]
#rotate 3 steps to the right: [5,6,7,1,... |
#Problem Statement:
#Given a non-empty array of integers, every element appears twice except for one. Find that single one.
#Note:
#Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
#Example 1:
#Input: [2,2,1]
#Output: 1
#Example 2:
#Input: [4,1,2,1,2]
#Output: 4... |
val1 = []
agua = 0
fuego = 0
x = True
while x:
frase = input("escriba su frase: \n")
if "agua" in frase:
agua=agua+1
if "fuego" in frase:
fuego=fuego+1
if "agua" in frase or "fuego" in frase:
val1.append(frase)
print("escriba salir para salir o ")
if ... |
'''
1. Открыть страницу http://SunInJuly.github.io/execute_script.html.
2. Считать значение для переменной x.
3. Посчитать математическую функцию от x.
4. Проскроллить страницу вниз.
5. Ввести ответ в текстовое поле.
6. Выбрать checkbox "I'm the robot".
7. Переключить radiobutton "Robots rule!".
8. Нажать на кнопку "Su... |
"""
CENTRO UNIVERSITÁRIO METODISTA IZABELA HENDRIX
PROGRAMAÇÃO FUNCIONAL ORIENTADA A OBJETOS PYTHON
Aula 03
por Layla Comparin
"""
# Atributo são nome, idade, raça...
# Método são as funções em negrito.
# Self - Remete a tudo que for da classe Cachorro. (Init é um método - construtor.)
class Cachorro:
... |
################################################
# CENTRO UNIVERSITÁRIO METODISTA IZABELA HENDRIX
# PROGRAMAÇÃO FUNCIONAL ORIENTADA A OBJETOS PYTHON
# Aula 03
# por Layla Comparin
################################################
## Estruturas de Dados:
# Listas e Dicionários:
# Lista:
nomes = ['Layla', 'Ge... |
class Board:
ROW_COL_BASE = 1
def __init__(self, board, N):
"""
Builds a Board from a list of blocks and the size of the board. The list must hold N^2 blocks.
:param board: the list with the blocks.
:param N: the size of the board (length = width = N)
:return: a new B... |
def stringspliter(sentence):
holder = int(0)
sentence = str(sentence)
print(sentence)
words = sentence.split(" ")
word_amount = len(words)
print("Your sentence has " + str(word_amount) + " words")
while holder != word_amount:
print(words[holder])
holder += 1
... |
#!/usr/bin/python
import sys
import re
import json
import getopt
import io
def parse_tweet_json(tweet, list_of_keys):
parsed_tweet = json.loads(tweet)
# a filtered tweet using a dictionary
filtered_tweet = {}
for mykey in list_of_keys:
search_key = mykey
# simple keys
myvalue = parsed_twee... |
#Fibonacci Numbers
fibonacci = list()
for i in range(1,55):
if i == 1:
fibonacci.append(i)
fibonacci.append(i)
else:
fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
if fibonacci[i] >= 55:
break
print(fibonacci)
|
deque = []
n = int(input())
result = []
for i in range(0, n):
cmd = input().split()
if cmd[0] == "push_front": deque.insert(0,cmd[1])
elif cmd[0] == "push_back": deque.append(cmd[1])
elif cmd[0] == "pop_front":
if len(deque) == 0: result.append(-1)
else:
result.append(deq... |
number = 0
if (number ==0):
print(number)
else:
print("Hello")
number = 12
print(number) |
# 10. 請設計一個銀行帳號的類別,有name(姓名)及balance(帳戶餘額)兩個屬性,
# withdraw()提款、deposit()存款及check_balance()檢查餘額的三個方法。
# 產生一個銀行帳號的物件時,請列印出 [Hello Jack, 您的開戶金額是NT$100元]
# 提款時會列印
# 您提了NT$50元
# 餘額NT$50元
# 或
# 您的存款不足
# 存款時會列印出
# 您存了NT$1,000元
# 餘額NT$1,050元
class bank:
def __init__(self, name, balance=0):
self.name = name
... |
# 9. 讓使用者輸入身高、體重、腰圍及性別
# 根據身高及體重算出BMI,18.6 >= BMI < 24,或男性腰圍<90、女性腰圍<80,
# 就列印出健康,否則就列印出不健康,請使用function來完成
bf = input("請輸入性別(男OR女):")
tall = int(input("請輸入身高:"))
fat = int(input("請輸入體重:"))
heavy = int(input("請輸入腰圍:"))
bmi = fat / (tall / 100 ) ** 2
def myself():
if bf == "男" :
if bmi >=18.6 and bmi < ... |
# 4. 列出1到1000中不能被2整除也不能被3整除的數字
math = list(range(1, 1001))
print([i for i in math if i % 2 >= 1 and i % 3 >= 1])
|
# def fun(s1,s2,count):
# s = s1 + s2
# print(s * count)
# #位置參數
# fun("Hello ", "World ", 3)
# #關鍵字參數
# fun(count=2, s1="Hello ",s2="World ")
# def fun(s1, s2="World ", count=1):
# s = s1 + s2
# print(s * count)
# fun("Hello ")
# fun("Hello ", "Fiona ")
# fun("Hello ", "Steve ", 3)
# fun("Hello ",... |
list1 = [1,2,3,4,5,6,7,8,9,10]
# list2 = []
# for i in list1:
# list2.append(i**2)
# list2 = [i**2 for i in list1]
# print(list2)
# for i in list1:
# if i % 2 == 0:
# list2.append(i)
list2 = [i for i in list1 if i % 2 == 0]
print(list2)
|
# The goal of this program is to show an improvement
# to linear time from the recursive solution.
# It also shows a flaw in that it disregards stack limits.
# tracks the operations per calculation
operations = 0
# saves results of previous calculations
table = {0 : 0, 1 : 1}
# Accepts an position x as an... |
# TAKE TWO NUMBERS AS INPUT AND PERFORM ALL THE ARITHMETIC OPERATIONS IN IT
x = int(input("ENTER FIRST NUMBER : "))
y = int(input("ENTER SECOND NUMBER : "))
add = x + y
sub = x - y
mult = x * y
div = x / y
floordiv = x//y
mod = x % y
exp = x ** y
print("SUM : ",add)
print("DIFFERENCE : ",sub)
print("MULTIPLICATION : ",... |
# # Use the file name mbox-short.txt as the file name
# fname = input("Enter file name: ")
# fh = open(fname)
# number = 0.0
# count = 0
# for line in fh:
# if not line.startswith("X-DSPAM-Confidence:"): continue
# # print(line)
# count += 1
# number += float(line[line.find(':')+1:].lstrip())
#
# print(... |
# Here we are going to see the default(naive) time demo available in python
import datetime
import time
# Cerating custom time
time_ = datetime.time(20,22,44,1000)
print(time_)
print("*"*50)
# Getting the default time
time_default = time.localtime(time.time())
print(time_default) |
# In this file we are going to see the different loops available in Python
# and Operations on it
myList = list(range(11))
print(myList,end="-")
print()
# While Loop
length = len(myList)
i = 0
while(i < length):
print(myList[i],end="-")
i += 1
print()
# For Loop
for i in myList:
print(i,end="==")
print(... |
# In this tutorial, we are going to see the different operators
# available in Python
# Arithematic Operators
# Like +,-,*,/,%
a = 10
b = 5
print()
print("*"*50)
print(a+b) # addition
print(a-b) # substraction
print(a*b) # multiplication
print(a/b) # divison
print(a%b) # modulus
# Logical/Conditional Operators
# and... |
def minMoves(h, w, h1, w1):
'''
:param h: initial high
:param w: initial width
:param h1: final high
:param w1: final width
:return: min moves to fold paper from initial to final dimentions
'''
moves = 0
# high
while h - h1 >= h1:
h = h // 2 + h % 2
moves += 1
... |
# https://sites.google.com/site/dlampetest/python/vector-3d
import math
class Vec3:
''' A three dimensional vector '''
def __init__(self, v_x=0, v_y=0, v_z=0):
self.set( v_x, v_y, v_z )
def set(self, v_x=0, v_y=0, v_z=0):
if isinstance(v_x, tuple) or isinstance(v_x, list):
self.... |
"""
This file has functions for a bubble sort and a random list GeneratorExit
Using the bubble_sort() function:
bubble_sort(*put the variable name or the list you want to be sorted*)
Using the get_random_list() function:
get_random_list(*put the length of the list you want*, *put the range of the list you want from... |
def swap_case(s):
result = []
for word in s.split(' '):
temp = []
for s in word:
if ord(s) >= 65 and ord(s) <= 90:
temp.append(s.lower())
elif ord(s) >= 97 and ord(s) <= 122:
temp.append(s.upper())
else:
temp.app... |
#Link to problem https://leetcode.com/problems/palindrome-number/
class Solution:
def __init__(self): #value in x can be edited to test other solutions
x = -121 #must be of type int
result = self.isPalindrome(x) #must be of type bool
print('Answer: ', result)
def isPalindrome(self, x: ... |
class Point:
row = 30
col = 30
fruitx = None
fruity = None
def __init__(self):
self.x =0
self.y =0
def __init__(self,x,y,check =True):
if x>-1 and x<self.row and y>-1 and y<self.col :
self.x = x
self.y = y
else:... |
class Vechile:
def __init__(self, name, color):
self.name = name
self.color = color
def setname(self):
pass
class Bus(Vechile):
def __init__(self, name, color, brand):
self.brand = brand
Vechile.__init__(self, name, color)
# member function
def getname(self):
return self.name
def getcolor(se... |
class Person(object):
def __init__(self, name, age=None, phone_no=None):
self.name = name
self.age = age
self.phone = phone_no
# for python code debugging we will use interactive python debugger
#import ipdb; ipdb.set_trace()
person = Person("rahul")
print (person.name)
# class Employee:
# # member v... |
class Dog:
Info = {} #commen for all objects
# def __init__(self): #default constructor
def __init__(self,name,age,weight):
self.name=name#instance variable
self.age=age
self.weight=weight
def printDetails(self):
print(self.name)
print(self.age)
print(se... |
i=1
# while(i<10):
# print(i)
# i+=1
# else:
# print("End of the loop")
# while(i<10):
# s=10*i
# print("10 x %i = %s"%(i,s))
# i+=1
# for i in range(1,11):
# print("10 x %d = %d" % (i,i*10))
# list1=["apple","banana","orange","grapes"]
# for fruite in list1:
# print(fruite +" is a f... |
import time,threading
class User(threading.Thread):
def __init__(self, x, y, username,client):
threading.Thread.__init__(self)
self.client=client
self.x = x
self.y = y
self.username = username
self.step=0
self.Running=True
self.inputs=[0,0,0,0] #left,right,up,down
def run(self):
while self.Runni... |
#!/usr/bin/python
# could be more readable, but looks pretty :D
def isLeapYear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
return False
return True
return False
# days up to and including a month
# assumes not a leap year... |
def binarySearch( theValues, target ):
# Start with the entire sequence of elements.
low = 0
high = len(theValues) - 1
# Repeatedly subdivide the sequence in half until the target is found.
while low <= high:
mid = ( high + low ) // 2
if theValues[mid] == target:
return ... |
# Print the moves required to solve the Towers of Hanoi puzzle.
def move( n, src, dst, tmp ):
if n >= 1:
move( n-1, src, tmp, dst )
print "Move %d -> %d" % ( src, dst )
move( n-1, tmp, dst, src )
print "moving tower of hanoi starts: "
move( 1, 1, 3, 2 )
|
# ===================Bubble Sort=====================================
# Sorts a sequence in ascending order using the bubble sort algorithm.
def bubbleSort( theSeq ):
n = len( theSeq )
for i in range( n-1 ):
for j in range( n-i-1 ):
if theSeq[j] > theSeq[j+1]:
tmp = theSeq[j]... |
# Implementation of the Sparse Matrix ADT using a list.
class SparseMatrix:
# Create a sparse matrix of size numRows * numCols initialized to 0.
def __init__( self, numRows, numCols ):
self._numRows = numRows
self._numCols = numCols
self._elementList = list()
# Return the number of... |
#! python3
import requests
rs = requests.get('http://automatetheboringstuff.com/files/rj.txt')
# to check if link is ok in shell, only raise exception on error
rs.raise_for_status()
#this print the length of the downloaded link as a string.
print('The article is ' + str(len(rs.text)) + ' words long.')
#this pri... |
import random
def isPrime(x):
for i in range(2,x):
if x%i == 0:
return False
return True
def genRandPrime():
index = random.randrange(65)
for i in xrange(2,2**32):
if isPrime(i):
if(index == 0):
return i
index -= 1
def genRsaKeys():
q = p = genRandPrime()
while p == q:
q = genRandPrime()
n... |
def is_prime(x):
for i in range(2, x / 2 + 1):
if x % i == 0:
return False
return True
def find(fn):
for i in range(2,fn):
if fn % i == 0 and is_prime(i):
print(i)
if __name__ == "__main__":
find(int(input())) |
#!/usr/bin/python
def encrypt(keys, number):
return number**keys[1] % keys[0]
def decrypt(keys, number):
return number**keys[2] % keys[0]
if __name__ == '__main__':
n = int(input("Enter N: "))
t = 'a'
while t != 'E' and t != 'D':
t = raw_input("Enter Encrypt/Decrypt: ")
i = int(input("Enter key: "))
num ... |
dict = {}
n = input()
for i in range(n):
name,m1,m2,m3 = map(str,raw_input().split())
l = []
name = str(name)
l.append(float(m1))
l.append(float(m2))
l.append(float(m3))
dict[name] = l
avg = 0
find_name = raw_input()
for i in dict[find_name]:
avg = avg+i
print "%.2f" %( avg/3.0)
|
import re
n = input()
for i in range(n):
a = raw_input()
a = a.split(' ',1)
if (len(a)>1):
a = a[1]
match = re.findall(r'#[a-f A-F 0-9]{6}|#[a-f A-F 0-9]{3}',a)
for j in match:
print j
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 2 00:45:12 2018
Name: Kewen Deng
Student ID: 29330440
Last modified date: May 4 2018
Description:
In this file, I have defined a class in this task for analysing the number of occurrences for each type of English sentences from the decoded sequences.
This ... |
print('------basic------')
print ('hello world!')
myStr = 'abc'
print(myStr)
a, b, c, d, e = 1, 'b', True, 3.14, 4+3j
print(type(a),type(b),type(c),type(d),type(e))
print('\n------number------')
print('2/4:',2/4)
print('2//4:',2//4)
print('2 ** 5:', 2 ** 5)
print('\n------str------')
s = 'Yes,he\'s'
print(s,type(s),l... |
# follow.py
#
# Follow a file like tail -f.
import time
import pandas as pd
from io import StringIO
# create generator that yields line
# generators can be iterated through only once
def follow(thefile):
thefile.seek(0,2) # 0 is offset, 2 is whence (relative to file end)
while True:
line = thefile.re... |
(S, C) = ('John Doe; Peter Benjamin Parker; Mary Jane Watson-Parker; John Elvis Doe; John Evan Doe; Jane Doe; Peter Brian Parker', 'Example')
print(C.lower())
naemDict = {}
resLst = []
for name in S.split('; '):
nameType = name.split()
if len(nameType) == 2:
firstName = nameType[0].lower()
last... |
# evaluate a string
def parse_integer(s):
i = int(s)
return i
def parse_float(s):
i = float(s)
return i
def parse_string(s):
i = str(s).lower()
return i
def evaluate_string(s):
try:
st = parse_string(s)
if any(i in st for i in 'aeiou'):
retur... |
import tkinter as tk
from tkinter import ttk
def greet():
print(f'Hello, {user_name.get() or "World"}.')
root = tk.Tk()
user_name = tk.StringVar()
name_label = ttk.Label(root, text='Name: ') # Pode-se colocar espaço após a label dessa forma
name_label.pack(side='left', padx=(0, 10)) # Ou então ... |
#!/usr/bin/env python3
# Copyright 2019 Ricardo Iván Vieitez Parra
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS... |
#!/usr/bin/python
from __future__ import print_function
print("Hello World!")
1 + 1
2 ** 2 ** 2 ** 2 ** 2
x=5
type(x)
x=5.0
type(x)
y = x
x, y = 17, 42
l = [1, 2, 3]
l[0]
x = [1, 3, 7]
y = x
y
x[1] = 6
y
4 ** 62
1.0 / 2
0xBEE
hex(3054)
0b10
int('0b10',2)
bin(2)
5 % 2
5 == 6
str = "Look how easy!"
"I am %d years old, ... |
print('Módulo importado com sucesso!!!')
def encontra_indice(lista, alvo):
for i, value in enumerate(lista):
if value == alvo:
return 1
return -1
teste = 'Testado.' |
"""
7. Para resolver as questões abaixo considere o livro "Generative
Art: A Practical Guide Using Processing" por Matt Pearson.
Sugere-se que se use Python, mas admite-se a solução em qualquer
programa que não seja o "Processing" cujas soluções estão
apresentadas no livro. Todas essas questões devem ser bem
explicadas... |
# INPUT_FILE = 'test_input.txt'
INPUT_FILE = 'input.txt'
class BingoBoard():
def __init__(self, row_list):
self.board = row_list # 2d 5x5 array of ints
self.marked = [[False for _ in range(5)] for _ in range(5)]
self.marked_cols = [[False for _ in range(5)] for _ in range(5)]
self.s... |
'''
平衡树
'''
import copy
import time
def cral_time(fun):
def wrapper(*args, **kwargs):
start_time = time.time()
result = fun(*args, **kwargs)
end_time = time.time()
print("执行时间:", end_time - start_time)
return result
return wrapper
@cral_time
def num_split(n):
if ... |
from . import np
from NeuralNetworks.activations.sigmoid import sigmoid
def logistic_predict(w, b, X):
'''
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- d... |
import matplotlib.pyplot as plt
import numpy as np
from 求导 import first_derivative, second_derivative
from Functions import fun2
def fun(x):
return x**3 - 2*x + 1
def display(fun, x0=6, a=-1, b=6, h=6, delta=0.001):
# fun: 输入的函数, 二维
# x0: 初始点坐标
# a: 范围的下限
# b: 范围的上限
# delta: 步长
# retur... |
#!/usr/bin/env python3
def funcao5():
so = "so"
trabalho = " trabalho"
sem = " sem"
diversao = " diversao"
faz = " faz"
de = " de"
joao = " joao"
em = " em"
chato = " chato"
print(so+trabalho+sem+diversao+faz+de+joao+em+chato)
funcao5()
|
# digest_network.py
# written by Chris Coletta for BIOF 518
# takes as input a file containing node pairs (edges) one per line
# and calculates statistics such as diameter and clustering coefficients
import re
from copy import deepcopy
import sys
debug = 0
#===========================================================... |
def calculate_sums(numbers):
""" Calculate and return a list with the sum of
every number pair in given list of numbers """
sums = []
for i in range(len(numbers)):
for j in range(len(numbers)):
if numbers[i] == numbers[j]: # may not be equal
continue
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.