text stringlengths 37 1.41M |
|---|
a=input("enter test1:")
b=input("enter test2:")
c=input("enter test3:")
print ((a+b+c)-min(a,b,c))/2.0
|
fname=raw_input("enter a file name:")
fd=open(fname)
count=0
for line in fd:
if line.startswith('From:'):
line=line.split()
print line[1]
count+=1
print "number of lines starts with From: are=",count
|
values=[]
while True:
num=raw_input("enter a value/enter done to finish::")
if num=='done':
print 'max=',max(values)
print 'min=',min(values)
print 'sum=',sum(values)
print 'len=',len(values)
print 'avg=',sum(values)/len(values)
break
else:
temp=f... |
#!/usr/bin/env python
"""
Defines Huffman Encoding Algorithm
"""
import numpy as np
argmin = lambda x: min(x, key=x.get)
class ProbabilityMap(object):
def __init__(self, probs):
total_weights = sum(probs.values())
self.probs = { key : probs[key] / total_weights for key in probs }
@propert... |
# allowed papers: 100, 50, 10, 5, and rest of request
money = 500
request = 277
def atm_give(request):
# defining needed variables
allowed_papers = [100,50,10,5,1]
switch = 0
repeat = 0
give = []
# checking the amount availability
if request <= money:
# a loop for processing the request
while re... |
# Sort the files in a given directory by filename
import os, fnmatch
class FileSorter:
def sort():
listOfPyFiles = []
pattern = "*.py"
for root, dirs, files in os.walk("."):
for filename in files:
if fnmatch.fnmatch(filename, pattern):
listOfP... |
class Date:
month = 0
day = 0
year = 0
def __init__ (self, m, d, y):
self.month = m
self.day = d
self.year = y
def compareTo(self, date):
if self.year < date.year:
return -1
if self.year > date.year:
return +1
if self.month < ... |
import unittest
class TestEvaluate(unittest.TestCase):
def test_evaluate(self):
expression = '( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )'
evaluate = Evaluate(expression)
self.assertEqual(evaluate.result, 101)
class StackResizingArray(object):
N = 0
s = []
def __init__(self):
se... |
# The below code explains loops
# it is self explanatory
for number in range(3):
print("Attempt", number + 1, (number + 1) * ".")
# for ranges
for number in range(1, 4):
print("Attempt", number + 1, (number + 1) * ".")
# for steps: first parameter is initial value of range, second parameter is the
... |
# Ternary operator can be used instead of if statement
age = 22
if age >= 18:
message = "Eligible"
else:
message = "Not Eligible"
print(message)
# Instead of above code the following code can be written which is cleaner
message = "Eligible" if age >= 18 else "Not Eligible"
print(message)
|
number = 100
# below are while loops
# syntax:
# while condition:
# statement
# update
while number > 0:
print(number)
number //= 2
# another example (below functions like do while in c++)
command = ""
while command != "quit" and command != "QUIT":
command = input(">")
print("Echo", c... |
list1 = [1, 2, 3]
list2 = [10, 20, 20]
# If we want to convert the above 2 lists to -> [(1, 10), (2, 20), (3, 30)] we use
# zip function
print(list(zip(list1, list2)))
# Zip function gives a list object which is iterable and can also be converted to
# list.
# Zip function can also take strings as parameters as s... |
try:
age = int(input("Age: "))
except ValueError as ex:
print("You didn't add valid age.")
print(ex)
print(type(ex))
else:
print("No exceptions encountered")
# If the ValueError is encountered by program, instead of crashing it will print the
# message in except. Due to the "as ex" it will ... |
# 3 logical operators in python are and, or and not
# The below code is self explanatory and has different instances of how logical
# operators can be used
high_income = True
good_credit = False
student = True
if high_income and good_credit:
print("Eligible")
else:
print("Not Eligible")
if high_... |
# We can also extend built in data types. for example we can create a class "Text"
# and have it inherit from class string(str). So Text will get all methods of class
# string and we can also add additional methods.
class Text(str):
def duplicate(self):
return self + self
text = Text("Python")... |
letters = ["a", "b", "c"]
# To add elements at the end of the list we use the append method
letters.append("d")
print(letters)
# To add elements at a specific position in the list we insert
letters.insert(0, "#")
print(letters)
# To remove item from end of list
letters.pop()
print(letters)
# To remove item at... |
from sys import getsizeof
values = [x*2 for x in range(10)]
for x in values:
print(x)
# If there is a large number of data or infinite stream of data, we should not store
# it in memory since it is very memory inefficient. In situations like this it is
# more efficient to use generator object. They are it... |
class Point:
def __init__(self, x, y): # Constructor
self.x = x
self.y = y
point = Point(1, 2)
other = Point(1, 2)
print(point == other)
# In the above statement we get false because by default the == operator compares
# the memory address of the 2 objects and they are stored at diffe... |
def celciusToFheraniteConverter(c):
f=(9/5)*int(c)+32
print("Temperature in Fharenite is: "+str(f))
def hourToMinuteCoverter(m,s=0):
h=int(m)*60+ int(s)*3600
print("Time in Minutes is: "+str(h))
celcius=int(input("Enter temperature in celcius: "))
min=int(input("Enter Hours: "))
celciusToFheraniteConv... |
#windown part 1
#hear part 2
#food part 3
#snake body grow
#Border Collisions
#body collisions
#Scoring
import turtle
import time
import random
delay = 0.1
#Score
score = 0
high_score = 0
# Set up the screen
wn = turtle.Screen()
wn.title("Snake Game by @TokyoEdtech")
wn.bgcolor("green")
wn.setup(width=600,height... |
a=int(input("enter first number "))
b=int(input("enter second number "))
s=a+b
print("sum is",s)
input()
|
from sys import argv
from cs50 import get_string
k = int(argv[1])
plaintext=get_string("plaintext: ")
print("ciphertext: ",end="")
ch=""
for i in range(0,len(plaintext)):
if ord(plaintext[i]) >= 65 and ord(plaintext[i]) <= 90:
print(chr((ord(plaintext[i])-65+k)%26+65),end="")
elif ord(plaintext[i]... |
# Floating-point arithmetic
from cs50 import get_float
# Prompt user for x
x = get_float("x: ")
# Prompt user for y
y = get_float("y: ")
# Perform division
print(f"x / y = {(x / y):.50f}")
|
from customer import Customer
def main():
print("Welcome to Wake-Mart. Please register.")
name = input("Enter your name: ")
obj = Customer(name)
obj.inputCardInfo()
print("Registration completed.Rick")
total_items_ordered = scanPrices()
total_coupons = scanCoupons()
amount_due = total_... |
import random
def rps(user, computer):
if user == computer:
return 'Draw!'
elif (user == 'Scissors' and computer == 'Rock') or (user == 'Paper' and computer == 'Scissors') or (user == 'Rock' and computer == 'Paper') :
return 'Computer wins!'
else :
return 'You win, queen!'
user_cho... |
# -*- coding: utf-8 -*-
"""
Functions to sort a list using mergesort, and count number of inversions.
"""
def _countAndMerge(left, right, _cmp):
merged = []
(lLength, rLength) = (len(left), len(right))
(lIdx, rIdx) = (0, 0)
count = 0
while True:
if(lIdx == lLength):
merged.ex... |
# 키보드에서 5개의 정수를 입력 받아 리스트에 저장하고 평균을 구하는 프로그램을 작성하시오
lst = []
result = 0
for i in range(5):
a = int(input())
lst.append(a)
for index in lst:
result += index
print("평균 :",result/len(lst))
|
# 키보드로 정수 수치를 입력 받아 짝수인지 홀수 인지 판별하는 코드를 작성하세요.
a = int(input("수를 입력하세요: "))
if(a%2==0):
print("짝수")
elif(a%2!=0):
print("홀수")
else:
print("수가 아닙니다") |
#!/usr/bin/env python
# encoding: utf-8
# @author: Mrliu
# @file: demo.py
# @time: 2020/5/13 23:09
# @desc: 生产者与消费者模式
import threading
import queue
import time
def produce():
for i in range(10):
time.sleep(0.5)
print('生产++++++面包{} {}'.format(threading.current_thread().name,i))
q.put('{}{... |
#!/usr/bin/env python
# encoding: utf-8
# @author: Mrliu
# @file: demo.py
# @time: 2020/5/13 23:09
# @desc: 迭代器与生成器
list=[1,2,3,4]
it = iter(list)
print(next(it))
for i in it:
print(next(it))
|
name = raw_input("What is your name? ")
print "Hello world"
print "line 2!"
print name
fib = lambda n:reduce(lambda x,n:[x[1],x[0]+x[1]], range(n),[0,1])[0]
fib_val = raw_input("What Fibonacci number would you like to compute? ")
print fib(int(fib_val))
|
# import socket programming library
import socket
# import thread module
from _thread import *
import threading
import pickle
print_lock = threading.Lock()
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": "1964"
}
# thread fuction
def threaded(c):
while True:
# data received... |
"""
LINE STYLES
By default, Matplotlib makes solid lines. Manually, this can be set using
'linestyle' or 'ls' and one the options listed below.
linestyle description
'-' solid
'--' dashed, use 'dashes = (on, off)' to change the gaps
'-.' dash_dot
':' dotted
'None' draw nothing
' ' draw... |
"""
SHARE AN AXIS BETWEEN TWO SUBPLOTS
If you want to share an axes between two subplots, simply use 'sharex' or
'sharey' when creating the subplot.
"""
import numpy
import matplotlib
import matplotlib.pyplot as plt
ax = [0] * 2
fig = plt.figure()
ax[0] = fig.add_subplot(121)
ax[1] = fig.add_subplot(122, share... |
"""
CONTOUR PLOTS
There are two functions of interest: contour and contourf. The first plots
contour lines, the second filled contours. Their behavior is very similar.
contour(Z): plot data Z
contour(X,Y,Z): plot data Z and axes X and Y
contour(X,Y,Z, contours = N): as before, use N levels
contour(X,Y,Z, levels = V)... |
"""
COLORMAPS
A colormap is a dictionary for the RGB values. For each color, a list of tupples
gives the different segments. Each segment is a point along the z-axis, ranging
from 0 to 1. The colors for the levels is interpolated from these segments.
segment z-axis end start
i z[i] v0[i] v1[i]
i+1... |
class SignalGenerator:
""" Signal generator class
It creates different signals depending on the events it's given.
Examplee of an events list:
[
{
"start": {
"value": 10
}
},
{
"step": {
"cycle": 100,
... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import csv
class AbstractRecord:
def __init__(self, name):
self.name = name
class StockStatRecord(AbstractRecord):
def __init__(self, name, company_name, exchange_country, price, exchange_rate, shares_outstanding, net_income, market_value_usd, pe_ratio):
... |
import pygame # install in terminal with: pip install pygame
import sys
import random
# RobotArm class ################################################
#
# An object of this class...
#
# lets you load and display a yard with stacks of colored boxes
# you can load a predefined level at the creation
# lets you p... |
def fibonach(x):
if x <= 1:
return 1
else:
return fibonach(x-1)+fibonach(x-2)
for i in range(0,10):
print fibonach(i)
|
"""sorting algorithms"""
def merge_sort(given_list: list) -> list:
'''merge sort'''
if len(given_list) > 1:
mid = len(given_list)//2 # Finding the mid of the array
L = given_list[:mid] # Dividing the array elements
R = given_list[mid:] # into 2 halves
merge_sort(L) # Sorti... |
#number = input("enter a non-negative integer to take the factorial of: ")
#product = 1
#for i in range(number):
#product = product * (i+1)
#print(product)
range(10) |
from Intersection import Intersection
__author__="stuart"
__date__ ="$08 Jan 2014 9:06:32 PM$"
class Graph:
Intersections = []
def __init__(self):
self.Intersections = []
return
def addLink(self, intersectionA, intersectionB):
intersectionA.addNeighbour(intersectionB)
... |
from sqlalchemy import *
# http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html
db = create_engine('sqlite:///tutorial.db')
db.echo = False # Try changing this to True and see what happens
# Before creating our Table definitions, we need to create the object that will manage them.
# Table definitions (what the c... |
# Coding for usual stuff Bitcoin mining, hmmm that's typical
# how hashing looks like, bbay steps!!
from hashlib import sha256
# display sha256 for a string
# print(sha256("ABC".encode("ascii")).hexdigest())
#at later stage defining a max number for nonce iteration based on compute powr of the system
# so here we go
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[i... |
# Function that lists "how_many" images in subdirectories of a given "path" for a specific "camera" starting from "from_hour" and ending at "to_hour"
import fnmatch
import os
def list_images(path, camera, from_hour, to_hour, how_many):
image_list = []
count = 0
for root, dirnames, filenames in os.walk(path):
for... |
def add1(x, y):
return x + y
class Adder:
value = 10
def __call__(self, x, y):
return x + y
@classmethod
def my_method(cls):
print('Hello', cls.value)
add2 = Adder()
print(add2.value)
add3 = Adder()
Adder.value = 55
print(add2.value)
# print(add1(10, 20))
# print(add2(10, 20))
|
"""
PTHW Exercise 3 numbers
1/4/2018
"""
print("How about some more")
#print statement and boolean answers
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
|
"""
Loops and lists
"""
the_count = range(1,5)
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#This is the first kind of for-llooop goes through a list
for number in the_count:
print(f"This is count {number}")
# Same as above
for fruit in fruits:
pr... |
"""
Making Decisions
with if , else and elif you can start making scripts that decide things
"""
print("""You enter a dark room with two doors
Do you go through door #1, door #2 or door #3?""")
door = input("> ")
if door == "1":
print("There is a giant bear here eating a cheese cake.")
p... |
print("************")
print("Contoh list ")
print("************")
a, b, c = 7, 8, 9
d = [a, b, c]
print(f'a={a}, b={b}, c={c}')
print(f'd={d}') |
"""
Functions to analyze the time complexity
"""
# TODO
# Given a function below, how many times exec `print`.
# Analyze it's time complexity in terms of f(n). SO that f(n) = n^2
# And what is it's order?
def ex_1(n):
for i in range(n):
for j in range(i):
print(j)
# TODO
# Given a function ... |
# time module works with times in two distinct ways:
# 1. it stores time in seconds from the epoch
# 2. it stores time in time.struct_time object (class) - this is the only class in time module
# there are several methods to convert between two store types
# advantage of struct_time is accessing the various parts of ti... |
# tempfile module holds functions which operate on temp files/directories securely
import tempfile, pathlib
with tempfile.TemporaryFile() as temp: # context manager automatically deletes temp file on file close
print('temp:')
print(' {!r}'.format(temp))
print('temp.name:')
print(' {!r}'.format(t... |
from itertools import count # count is a infinite version of builtin range function
enumerate = lambda x, start=0: zip(count(start),x) # overloading enumerate function with count(start,step) - there is no end parameter like in range!
print(list(enumerate('dejanstojcevski',3)))
print(list(zip(count(3),'dejanstojce... |
import re
'''
This module shows how to substitute strings with regular expressions
'''
bold = re.compile(r'\*{2}(.*?)\*{2}')
text = r'Make this **bold**. This **too**.'
print('Text:', text)
print('Bold:', bold.sub(r'<b>\1</b>', text)) # use sub method from re.Match class to substitute
# use named groups instead of \1... |
from dataclasses import dataclass
@dataclass
class CountrySummary(object):
"""Dataclass Object representing a country summary"""
name: str = None
new_confirmed: int = 0
total_confirmed: int = 0
new_recovered: int = 0
total_recovered: int = 0
new_deaths: int = 0
total_deaths: int = 0
... |
from abc import ABC, abstractmethod
class AbstractFilter(ABC):
"""Abstract class for filtering"""
@abstractmethod
def apply_to(self, data):
"""
Filters data based on concrete behavior
Parameters
----------
data: The data to filter
Returns
-------
... |
command = input ("Введите команду: ")
num1 = int (input ("Введите число 1: "))
num2 = int (input ("Введите число 2: "))
if command == "+" :
print (num1 + num2)
elif command == "*" :
print (num1 * num2)
elif command == "/" :
print (num1 / num2)
if command == "-" :
print (num1 - num2)
if command == "more... |
#!/usr/bin/env python3
# -- coding: utf-8 --
"""
Created on Sat Jul 18 10:39:54 2020
@author: smith barbose & manan dodia
"""
# first importing librarys
import wikipedia
import random
#creating multiple responses for greating user
bot_response=["Hello Stay Safe ","How may I hepl you???","Hey Wanna play???","Why ... |
import sys
from Bio import SeqIO
def sequence_cleaner(fasta_file):
# Create our hash table to add the sequences
sequences={}
# Using the Biopython fasta parse we can read our fasta input
for seq_record in SeqIO.parse(fasta_file, "fastq"):
# Take the current sequence
sequence = str(seq_... |
# Given a list of points as [x,y] pairs; a vertex in [x,y] form; and an integer k, return the kth closest points in terms of euclidean distance
from random import random, randint
from collections import namedtuple
from math import sqrt
Point = namedtuple('Point', ['x', 'y'])
def rand(max):
return round(random()... |
#!/usr/bin/env python3
# ศิลาลักษณ์ แก้วจันทร์เพชร
# 610510670
# Lab 13
# Problem 3
# 204111 Sec 001
import string
def word_count(text):
char_ = ((text.strip(string.punctuation)).lower()).split()
x = {}
alp_ = string.punctuation
for i in char_:
word_ = i.strip(alp_)
if word_ in x... |
#!/usr/bin/env python3
# ศิลาลักษณ์ แก้วจันทร์เพชร
# 610510670
# Lab 04
# Problem 1
# 204111 Sec 001
def love6(first, second):
if(first == 6) or (second == 6):
return True
elif(first + second) == 6:
return True
elif(first - second) == 6 or (second - first) == 6:
r... |
#!/usr/bin/env python3
# ศิลาลักษณ์ แก้วจันทร์เพชร
# 610510670
# Lab 07
# Problem 4
# 204111 Sec 001
def reverse_digits(x):
for i in range(x==0):
o = x%10
o = o*(10**i)
rev = reverse_digits(x//10)
return rev
def main():
#รับค่าจำนวนเต็มบวก
x = int(input("input numbers: ... |
#!/usr/bin/env python3
# ศิลาลักษณ์ แก้วจันทร์เพชร
# 610510670
# Lab 04
# Problem 1
# 204113 Sec 001
import math
class Circle(object):
def __init__(self, r):
self.radius = r
def perimeter(self):
return 2 * math.pi * self.radius
def area(self):
return math.pi * (self.radius**2)
... |
#!/usr/bin/env python3
# ศิลาลักษณ์ แก้วจันทร์เพชร
# 610510670
# Lab 02
# Problem 3
# 204111 Sec 001
print("First Equation")
m1 = float(input("Input m1: ")) #รับค่าความชันที่ 1
b1 = float(input("Input b1: ")) #รับค่าb1
print("Second Equ... |
#!/usr/bin/env python3
# ศิลาลักษณ์ แก้วจันทร์เพชร
# 610510670
# Lab 02
# Problem 2
# 204111 Sec 001
H = float(input("Input height (m): ")) #รับข้อมูลความสูง มีหน่วยเป็น เมตรยกกำลังสอง
W = float(input("Input weight (kg): ")) #รับข้อมูลน้ำหนัก มีหน่วยเป็น กิโลกรัม
BMI = W/(H*H) ... |
#!/usr/bin/env python3
# ศิลาลักษณ์ แก้วจันทร์เพชร
# 610510670
# Lab 11
# Problem 4
# 204111 Sec 001
import copy
def sum_nested_list(list_a):
list_x = copy.deepcopy(list_a)
sum_ = []
for i in list_x:
if isinstance(i,list) == True:
list_x.extend(i)
else:
sum_.appen... |
#!/usr/bin/python
class Node:
def __init__(self, val):
self.l = None
self.r = None
self.v = val
class BST:
def __init__(self):
self.root = None
def add(self, val):
if self.root is None:
self.root = val
if val < self.root:
self.ro... |
#!/usr/bin/env python3
# ศิลาลักษณ์ แก้วจันทร์เพชร
# 610510670
# Lab 13
# Problem 4
# 204111 Sec 001
def square_matrix(list_x):
mtrx_ = []
for i in list_x:
mtrx_.append(len(i))
col_ = max(mtrx_)
row_ = len(list_x)
x = max(col_, row_)
zero_ = [[0] * x for j in range(x)]
a = 0
... |
import math
from sympy.utilities.lambdify import lambdify
from sympy import symbols
point = []
print("Enter a starting point")
for i in range(2):
point.append(int(input()))
def gradient_of_function():
"""Find a gradient of function"""
x1 = symbols('x1')
x2 = symbols('x2')
func = 5 * (x1 - 3) ** ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: fabre
"""
from node import Node
class ChainedList:
'''
This class sets up methods to perform actions on chained lists
formed from nodes of the node class.
'''
def __init__(self, list_n):
''''
This function initialize the f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 15:02:20 2021
@author: fabre
"""
from tree_node import TreeNode
class Tree:
'''
This class sets up methods to perform actions on tree
formed from nodes of the TreeNodes class.
'''
def __init__(self, root_node):
'''
... |
# https://www.hackerrank.com/challenges/the-minion-game
# # Copied from:
# # https://stackoverflow.com/a/12945063
# def consecutive_groups(iterable):
# s = tuple(iterable)
# for size in range(1, len(s)+1):
# for index in range(len(s)+1-size):
# yield iterable[index:index+size]
def minion_g... |
# https://www.hackerrank.com/challenges/symmetric-difference
def simetric_difference(m, n):
sm = set(m)
sn = set(n)
sd = sorted(list((sm.union(sn)).difference(sm.intersection(sn))))
for i in range(len(sd)):
print(sd[i])
if __name__ == '__main__':
msize = int(input())
m = list(map(int, input().split()))... |
# https://www.hackerrank.com/challenges/find-angle
import math
AB = int(input())
BC = int(input())
AC = math.sqrt(AB**2 + BC**2)
print(str(round(math.degrees(math.asin(AB/AC)))) + "°")
|
# https://www.hackerrank.com/challenges/itertools-combinations-with-replacement
from itertools import combinations_with_replacement
[word, n] = input().split()
res = []
for i in sorted(list(combinations_with_replacement(word, int(n)))):
res.append(''.join(str(x) for x in sorted(list(i))))
for i in sorted(res):
... |
# python-functions-cw_2
# Problem 1:
#
# Create a function that will ask the user for a number. Use the function to get two numbers from the user, then pass the two numbers to a function. Add, subtract, multiple, and divide the numbers.
# !! : "Create a function that will ask the user for a number". This is not a fun... |
def my_function(num,num2,num3):
# b=[]
# if num not in b:
# b.append(num)
# if num2 not in b:
# b.append(num2)
# if num3 not in b:
# b.append(num3)
# print(b)
# i=0
# sum=0
# while i<len(b):
# sum=sum+b[i]
# i=i+1
sum=num+num2+num3
aver... |
def function(limit):
i=0
sum=0
while i<=limit:
if i%3==0 or i%5==0:
sum=sum+i
# print(sum)
i=i+1
print(sum,i)
function(15) |
from enum import Enum
class Color(Enum):
RED = 0,
BLACK = 1
class Node:
def __init__(self, val):
self.val = val
self.color = Color.RED
self.left = None
self.right = None
self.parent = None
class RedBlackTree:
"""
X's GrandFather
... |
import random
import pygame
pygame.init()
def print_summary(all_names, all_foods):
print()
print("PLAYER CHOICES: ")
print_favs(all_names, all_foods)
print()
print("FOOD SCORES: ")
print_scores(all_foods)
print()
print("MOST POPULAR FOOD: ")
print_winner(all_foods)
de... |
import pygame
import tsk
pygame.init()
window = pygame.display.set_mode([1018, 573])
cat = tsk.Sprite("Cat.png", 400,200)
cat.scale = 2
drawing = True
while drawing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
drawing = False
# Draw colors and shapes here
window.fill... |
import random
import pygame
pygame.init()
words = []
word = ""
sentence = ""
count = 0
while word != "done":
word = input("Enter a word (Type \"done\" to quit): ")
if word != "done":
words.append(word)
print()
print("Here are your words")
print("-------------------")
for i in range(len(words)):
pri... |
numbers = [5, 11, 9, 22]
rotatedLeft = []
for i in range(1,len(numbers)):
rotatedLeft.append(numbers[i])
rotatedLeft.append(numbers[0])
print(rotatedLeft)
|
import pygame
import random
pygame.init()
window = pygame.display.set_mode([500, 500])
height = 400
size = 100
circles = []
for i in range(8):
num = random.randint(0, 500)
circles.append(num)
drawing = True
while drawing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
... |
import random
numbers = []
while len(numbers) < 8:
number = random.randint(-100, 100)
numbers.append(number)
print("Here are some numbers: " + str(numbers))
print("These are the positive ones:")
for number in numbers:
if number > 0:
print(number)
|
same = False
a = [1,2,3]
b = [1,3]
if a[0] == b[0] or a[len(a)-1] == b[len(b)-1]:
same = True
if same:
print(same)
|
animals = []
animal = ""
while animal != "done":
animal = input("Enter an animal (enter 'done' to exit)")
if animal != "done":
animals.append(animal)
cage = "+===============+"
index = 0
print("ZOO MAP:")
print(cage)
while index < len(animals):
row = "| " + animals[index]
spaces = 14 - len(a... |
# Importing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Importing dataset
data = pd.read_excel('ANZ synthesised transaction dataset.xlsx')
X = data.iloc[:,12:14].values # Gender and age
y = data.iloc[:,10:11].values # Salary
# Encoding Categorical(String) data
from sk... |
class Course:
def __init__(self, name, course_data):
"""
:param name:
:type name: str
:param course_data:
:type course_data: dict of str
"""
self.name = name
self.obstacles = []
for obstacle_index in range(int(course_data["amount_of... |
import socket
resp = 'S'
while(resp == 'S'):
url = input('Digite uma url: ')
ip = socket.gethostbyname(url)
print('O IP para essa url é: ', ip)
resp = input('Digite S para continuar: ').upper() |
import csv
from collections import defaultdict
def csv2py(filename):
l = list()
with open('../resources/' + filename, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
l.append(row)
return l
class VenezuelaSchema:
def __i... |
from galois import *
#We will compute over GF(3^m), choose m :
m=2
#Please do NOT modify these 2 lines!
gf = generate_GF(m,3)
r_GF = rev_dic(gf)
#Choose the elements you want to add/multiply together:
#Highest order comes first, i.e. [2,1,0,1] = 2a^3 + 1a^2 + 0a + 1
a = [1,1,-1,1,1]
b = [1,2,1,2]
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Yandong
# Time :2019/10/25 3:03
# VRP with backhauling, first delivery all goods to customer and then pickup the goods to return the depot
# data: Solomon hard vrptw
import import_Solomon
import vrptw_ga
import matplotlib.pyplot as plt
import time
def pop_info(p... |
#! /usr/bin/python
def randomIntList(size, seed=1, maxInt=2000000000):
'''
Return a list of random numbers
Arguments:
size - size of list to return
seed - random seed - using default gives repeatable results
maxInt - max int value to return (default is 2,000,000,000)
Returns:
... |
from matplotlib import pyplot as plt
#-----------------------------------------------------------------------------
def showResult(result, city_coordination, city_num):
color = ['red', 'yellow', 'blue', 'green','orange']
style = ['o', 'p', 's', '*', '^']
x_coordination = []
y_coordination = []
x_coo... |
# if_elif_else.py
# if - else if - else 结构
a = 1
if (a > 1):
print('a > 1')
elif (a > 0):
print('a > 0')
else:
print('a <= 0')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.