text stringlengths 37 1.41M |
|---|
import json
import re
# This functions takes .txt file as input
# and returns tweets as a list of json
def parse_tweets(tweet_files):
twt_data = []
for tweet_file in tweet_files:
tweets_file = open(tweet_file, "r")
for line in tweets_file:
try:
tweet = json.loa... |
n = 5
arr = [2,3,6,6,5]
arr1 = []
[arr1.append(x) for x in arr if x not in arr1]
arr1.sort()
print(arr1[-2]) |
from klampt import *
from klampt.math import vectorops
#attractive force constant
attractiveConstant = 100
#repulsive distance
repulsiveDistance = 0.1
# repulsive constant - alters the strength of the repulsive force
repulsiveConstant = .009;
#time step to limit the distance traveled
timeStep = 0.01
class Circle:
... |
s = "Hey there! what should this string be?"
print(s, "\n")
#Panjang harusnya 20
s = s[:20]
print(s)
print("panjang dari s = %d" % len(s), "\n")
#Huruf pertama 'a' harusnya di index no 8
s = s.replace("there", "thera")
print(s)
print("Kemunculan a pertama = %d" % s.index("a"), "\n")
#Jumlah huruf a seharusnya 2
prin... |
# Assignment 7.1 - Guilherme Ferreira
# Use words.txt as the file name
fname = raw_input("Enter file name: ")
try:
fh = open(fname)
except:
print "Error: Name of the file invalid!"
exit()
for line in fh:
print line.rstrip().upper() |
#!/usr/bin/env python3
def decode_row(data):
return binary(0, 127, 'F', 'B', data[:7])
def decode_column(data):
return binary(0, 7, 'L', 'R', data[7:])
def getID(row: int, column: int) -> int:
return 8 * row + column
# def binary_search(lth: int, hth: int, llt: str, hlt: str, data: str) -> int:
# ... |
import os
__author__ = 's.jahreiss'
def get_file_list(dir_path, file_extensions):
"""
Returns a list of all available files in the file system under the specified path with the specified file extensions.
:return: All available files in the filesystem with the specified file extensions under the s... |
import random
def computer_guess(x):
low=1
high =x
feedback=''
while feedback!='c':
guess = random.randint(low, high)
print(f"Computer guesses: {guess}")
feedback=input("h, c or l").lower()
if feedback=='h':
high =guess
elif feedback=='l':
... |
import sqlite3
conn = sqlite3.connect(':memory:')
# Clase conectar BD
class Conectar():
# Funcion crear tablas
def CrearTablas(self):
c = conn.cursor()
#Crear tabla de cines
c.execute('''CREATE TABLE CINE
(id_cine int PRIMARY KEY, nombreCine text )''... |
#1.create a function printstr(str), which takes a string as an argument, and prints it
a = "The"
b = "Marathon"
c = "continues"
d= a+ " " + b+ " "+ c
print (d)
|
#2.create a function changedata(mylist), which take a list as argument and changes the values in mylist. Display the contents of the list
myBasket = ['apples', 'oranges', 'pineapple']
def changedata(mylist):
mylist.append("cherry")
mylist.append("kiwi")
for item in mylist:
print (item)
... |
# coding=utf-8
import json
data = {
"id": "10000011",
"name": "lichang",
"age": 25,
"game": {
"id": "123456",
"type": "poke"
},
"family": [
{"role": "father", "age": 50},
{"role": "mather", "age": 49}
]
}
# 将json字符串解析成python对象
jsonParseBean = json.dumps(da... |
from buildings import Building
class City:
def __init__(self, name, mayor, year_est, all_buildings):
self.name = name
self.mayor = mayor
self.year_est = year_est
self.all_buildings = list()
def new_building(self):
self.all_buildings.append()
building_1 = Building("... |
#!/usr/bin/env python
from math import sin
from random import gauss
# Generates data from a fictional sensor, complete with measurement
# noise.
def generate_sensor_data(n=1000, noise=0.05):
return [sin(x * 0.01) + gauss(0.0, noise) for x in xrange(n)]
# Print some sensor data to a file.
def print_sensor_data(... |
#!usr/bin/python3
# -*- coding: utf-8 -*-
# author zzZ5
'''
python自带的装饰器
'''
# import time
# def time_it(func):
# # 创建一个时间装饰器, 用于计算函数运行的时间.
# def call_func():
# start_time = time.time()
# func()
# stop_time = time.time()
# print("运行时间是{}".format(stop_time-start_time))
# ... |
#!usr/bin/python3
# -*- coding: utf-8 -*-
# author zzZ5
def singleton(cls):
# 函数装饰器实现单例模式
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner
@singleton
class Test():
def __init__(self):
pass
test1 =... |
from vec import Vec
def list2vec(L):
"""Given a list L of field elements, return a Vec with domain {0...len(L)-1}
whose entry i is L[i]
"""
return Vec(set(range(len(L))), dict((k,L[k]) for k in range(len(L))))
def zero_vec(D):
"""Returns a zero vector with the given domain
"""
return Vec(D... |
#!/usr/bin/env python3
def date_fashion(you, date):
if you >= 8 and date <= 2 or you <=2 and date >= 8:
return 0
elif you >= 8 or date >= 8:
return 2
elif you <= 2 or date <= 2:
return 0
else:
return 1 |
#!/usr/bin/env python3
def lucky_sum(a, b, c):
sum = a + b + c
if a == 13:
return 0
elif b == 13:
return a
elif c == 13:
return a + b
else:
return sum |
#!/usr/bin/env python3
import math
for num in range(1999,3201):
if num %7 == 0 and num %5 != 0:
print (num, end=',')
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 17 14:52:28 2019
@author: Carlos
"""
import os
import sys
from pathlib import Path
import numpy as np
import datetime
def query_yes_no(question, default="yes"):
'''
Ask a yes/no question via raw_input() and return their answer.
:param quest... |
# Josh Lim
# Comp Sci 30 P4
# 01/09/2020
# File to run code
import map
from player import Player
import action as act
import os
def intro():
"""Function for intro sequence and accepting name"""
print("Welcome to escape room")
name = input("Name: ").title # gets the name of the player
os.system('cls')... |
#loops now
friends = ["Rolf", "Jen", "Bob", "Anne"]
for friend in range(4):
print(f"{friends} is my friend.")
#
grades = [35, 67, 98, 100, 100]
total = 0
amount = len(grades)
for grade in grades:
total += grade
print(total / amount) |
import itertools
def twoNumberSum(array, targetSum):
hash_table = {}
for xx in range(0,len(array)):
for yy in range(1,len(array)):
dt = tuple(sorted([array[xx],array[yy]]))
if dt in hash_table.keys() or array[xx]==array[yy]:
pass
else:
hash_table[dt] = array[xx]+array[yy]
dd = [k for k,v ... |
# sumPrimes.py
# Author: Joey Willhite
# Date: 10/25/2013
import math
import time
def sumPrimes(maxPrime, dispInc):
# A function to calculate the sum of all of the primes below a given number. Used to solve problem 10
suspected=3
primes=[2, suspected]
primeSum=5
print('Count:1, Prime Located:2' )
... |
num = 4
print(num)
# complex numbers:first one will be the real part
# of the complex number, while the second value
# will be the imaginary part.
#used to solve quadratic equations that = 0 or
#squareroot 0
com = complex(10, -2)
print(com)
#finding the length of a string
str = 'a string'
print(len(str))
#accessin... |
#1 первый способ list
def printMat(a, n, m):
for i in range(n):
for k in range(m):
print(a[i][k], end = "\t")
print()
a = []
n = int(input('n = '))
m = int(input('m = '))
for i in range(n):
a.append([])
for j in range(m):
a[i].append(int(input('Enter element: ')))
... |
def f(x):
if(x % 5 == 0):
return x / 5
else:
return x + 1
n = float(input("Enter value = "))
print(f(n))
|
print("Enter set1 : ")
set1 = set([int(x) for x in input().split()])
print("set1 : ",set1)
print("Enter set2 : ")
set2 = set([int(x) for x in input().split()])
print("set2 : ",set2)
res = set1.intersection(set2)
s = sum(res)
print("\nintersection : ", res, "\nSum : ",s)
|
from tkinter import *
class App:
def __init__(self):
self.master = Tk()
self.master.wm_title("Entry Name")
# Text field storing text details
self.text_field = Entry(self.master)
self.text_field.pack()
self.text_field.focus_set()
self.text_value = None
... |
import pygame
pygame.init()
screenwidth=int(input("Enter the screen size in pixels : "))
win= pygame.display.set_mode((screenwidth,screenwidth))
caption=pygame.display.set_caption("Basic Movements")
x=250
y=250
width=50
height=20
vel=10
run=True
while run:
pygame.time.delay(100)
for eve... |
#!/usr/bin/python3
matrix = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print('matrix[{}][{}] = {}'.format(i, j, matrix[i][j]))
for i, row in enumerate(matrix):
for j, col in enumerate(row):
print('matrix[{}][{}] = {}'.format(i, j, col))
|
from math import sqrt
number = 0
for i in range(10):
number = i ** 2
if i % 2 == 0:
continue # continue here
print(str(round(sqrt(number))) + ' squared is equal to ' + str(number))
|
from dataclasses import dataclass
"""
Since version 3.7, Python offers data classes. There are several advantages over regular classes or other alternatives like returning multiple values or dictionaries:
- a data class requires a minimal amount of code
- you can compare data classes because __eq__ is implemented for... |
"""
def get_secret_code(password):
if password != "bicycle":
return None
else:
return "42"
secret_code = get_secret_code("unicycle")
if secret_code is None:
print("Wrong password.")
else:
print("The secret code is {}".format(secret_code))
"""
def get_secret_code(passw... |
name = "Jeremy"
age = 25
# String formatting using concatenation
print("My name is " + name + ", and I am " + str(age) + " years old.")
# String formatting using multiple prints
print("My name is ", end="")
print(name, end="")
print(", and I am ", end="")
print(age, end="")
print(" years old.")
# String formatting u... |
original_list = [1, 2, 3, 4, 5]
def square(number):
return number ** 2
squares = map(square, original_list)
squares_list = list(squares)
print(squares)
# Returns [1, 4, 9, 16, 25]
|
from functools import cmp_to_key
import locale
my_list = ["leaf", "cherry", "fish"]
# Brute force method using bubble sort
my_list = ["leaf", "cherry", "fish"]
size = len(my_list)
for i in range(size):
for j in range(size):
if my_list[i] < my_list[j]:
temp = my_list[i]
my_list[i] = ... |
another_str = "The * operator"
# Using a list outside the unpacking
var2 = [*another_str]
print(type(var2)) # List
# Using a tuple
# Tuples ends with a comma
var3 = (*another_str,)
print(type(var3)) # Tuple
|
import os
folder = '.'
filepaths = [os.path.join(folder, f) for f in os.listdir(folder)]
print(filepaths)
# os.scandir() function (available for Python >= 3.5 or with the scandir module)
filepaths = [f.path for f in os.scandir('.') if f.is_file()]
dirpaths = [f.path for f in os.scandir('.') if f.is_dir()]
print(fil... |
l = [1, 2, 3]
magic_number = 4
for n in l:
if n == magic_number:
print("Magic number found")
break
else:
print("Magic number not found")
|
import operator
people = [
{'name': 'John', "age": 64},
{'name': 'Janet', "age": 34},
{'name': 'Ed', "age": 24},
{'name': 'Sara', "age": 64},
{'name': 'John', "age": 32},
{'name': 'Jane', "age": 34},
{'name': 'John', "age": 99},
]
people.sort(key=operator.itemgetter('age'))
people.sort(key... |
x = range(5)
print(x)
print(type(x))
l = list(range(5, 20, 3))
print(l)
for n in x:
print(n)
t = tuple(x)
print(t)
l2 = list(range(5, 20, 3))
print(l2)
print(list(range(5, 10, 1)))
print(list(range(5, 10)))
print(list(range(-5, 5)))
print(list(range(5, -5)))
print(list(range(5, -5, -1)))
|
from collections import Counter
myList = [1, 1, 2, 3, 4, 5, 3, 2, 3, 4, 2, 1, 2, 3]
print(Counter(myList))
|
def print_each_item(items):
# check whether items is an Iterable
try:
iter(items)
except TypeError as e:
raise (
TypeError(
f"'items' should be iterable but is of type: {type(items)}")
.with_traceback(e.__traceback__)
)
# if items is iter... |
class Square(object):
def __init__(self, length):
self._length = length
@property
def length(self):
return self._length
@length.setter
def length(self, value):
self._length = value
@length.deleter
def length(self):
del self._length
r = Sq... |
import numpy as np
print(np.random.rand(10)) # array
print(np.random.rand(3, 4)) # 3x4 matrix
# To generate random numbers in a normal distribution, use the randn() function from np.random:
print(np.random.randn(10))
print(np.random.randn(3, 4))
# To generate random integers between a low and high value, use th... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 8 16:52:51 2020
@author: Max
"""
import pandas as pd
def data_fill_from_df(data,fill_table,data_id):
"""like vlookup, try to fill a table with another table as a reference"""
for index, row in fill_table.iterrows():
for col in fill_table.columns[1:]:
... |
# UI TEXT STRINGS -- TODO WRITE FOR DIFFERENT LANGUAGES
# TODO - organize these so they aren't random lists / strings, and instead consolidated in some dictionaries or something
PURPOSES_OF_PACKAGE_TUTORIAL_STEP = [
"Let's talk about what we can do with this package.",
"* We can get a 'mask' of the current moo... |
# Time Complexity : O(M * N)
# Space Complexity : O(M * N)
# Did this code successfully run on Leetcode : YES
# Any problem you faced while coding this : Logic
class Solution:
def findDiagonalOrder(self, matrix):
if (matrix == [] or len(matrix) == 0):
return []
m = len(matrix)
... |
#-*- coding:utf-8 -*-
##在命令行中运行python,粘贴下面三段以导入
# import sys
# sys.path.append('/home/vetains/pywork/pycore')
# import chapter13 as c13
# class C(object):
# '''a class'''
# def __init__(self):
# pass
# def A(self):
# print 'a'
#
# c=C()
# print C.__class__
# class P(object):
# def __i... |
import sys
class tic_tac_toe(object):
def __init__(self):
self.board = [0] * 9
self.pattern = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7),
(2, 5, 8), (0, 4, 8), (2, 4, 6))
self.player = True # X moves first, 1=X, 2=O
def printboard(self, board=None):
... |
#!/usr/bin/env python
from random import *
print("Script for generating two dimensional coordinate data")
print("Data is stored in a txt file where each line has a pair of coordinates, delimited by a colon")
#print("Max distance in each dimension from previous point is 0.05")
print("Domain of each dimension is (-5.0,... |
my_list = [5, 12, -8, 3, 16, 2]
# вывести массив
print(my_list)
# list + list, list * number
another_list = ['five', 'four', 'ten']
print(my_list + another_list)
print(my_list * 2)
# разрезание
print(my_list[2:5])
my_list.sort()
print(my_list) |
#!/usr/bin/env python3
# ^3^ coding=utf-8
#
# author: superzyx
# date: 2019/09/08
# usage: the forth one of exams
# 4.请使用Python代码对[23, 14, 12, 21, 45, 99, 34, 42]排序, 请使用冒泡排序
list01 = [23, 14, 12, 21, 45, 99, 34, 42]
for i in range(len(list01)):
for j in range(len(list01) - i - 1):
if list01[j] > list01[... |
#!/usr/bin/env python3
# ^3^ coding=utf8
#
# author:superzyx
# date:2019/08/10
# usage: sort qiuckly
def sortq(list01):
if len(list01) < 2:
return list01
else:
nu = list01[0]
listr = [i for i in list01[1:] if i > nu]
listl = [r for r in list01[1:] if r < nu]
return sort... |
#!/usr/bin/env python3
# ^3^ coding=utf8
#
# author:superzyx
# date:2019/08/09
# usage: OS module learning
d = {'mike': 10, 'lucy': 2, 'ben': 30}
d = dict(sorted(d.items(), key=lambda list: list[1], reverse=True))
print(d) |
#!/usr/bin/env python3
# ^3^ coding= utf8
#
# author: superzyx
# date: 2019/08/19
# usage: random function
import random
tuple01 = (0, 1, 2, 3)
a = random.choice(tuple01)
print(a)
random.shuffle(tuple01)
print(tuple01)
# m = 1
# while m != 9:
# m = random.uniform(1,9)
# print(m) |
#!/usr/bin/env python3
# ^3^ coding=utf8
#
# author: superzyx
# date: 2019/08/15
# usage: many_inherit
# class A:
# def __init__(self, name, sex):
# self.name = name
# self.sex = sex
#
# class B(A):
# def __init__(self, name, sex, age):
# A.__init__(self,name,sex)
# # self.name... |
# equal or not
a = input("enter the first number")
b = input("enter the second number")
if (a==b):
print("numbers are equal")
else
print("numbers are not equal")
|
#python program to creat a tuple with different data types
tuplex=("tuple",3.2,1)
print(tuplex)
('tuple', 3.2, 1)
>>>
|
#python program to creat a list of empty dictionaries
n = 5
1 = [{} for _ in range(n)]
print(1)
output
{} {} {} {} {}
|
# equal or not
a = input("enter a number")
b = input("enter a number")
if (a==b):
print("numbers are equal")
else:
print("numbers are not equal")
|
import sys
import string
import random
snakes = {
8: 4,
18: 1,
26: 10,
54: 36,
60: 23,
90: 48,
92: 25,
97: 87,
99: 63
}
# ladder takes you up from 'key' to 'value'
ladders = {
3: 20,
6: 14,
11: 28,
15: 34,
17: 74,
22: 37,
38: 59,
49: 67,
57: 76,
... |
n = float(input("Informe um Numero: "))
div = 0
if (n%2 == 0):
m = n
while m != 0:
div = n / m
if div == 0:
print("O Numero Nao eh Primo")
break
else:
print("O Numero Eh Primo")
m -= 1
|
soma = 0
x = 0
numero = 0
while True:
numero = float(input("Informe um Numero ou 0 para sair: "))
if numero == 0:
break
soma += numero
x += 1
print ("A Soma e = %3.2f e a Media = %3.2f "%(soma,(soma/x)))
|
PD = 0
QT = 0
total = 0
while True:
PD = int(input("Informe Codigo do Produto ou 0 para Sair: "))
if PD == 0:
break
QT = float(input("Informe Quantidade desejada: "))
if PD == 1:
total += (0.50 * QT)
elif PD == 2:
total += (1.00 * QT)
elif PD == 3:
total += (4.00 * QT)
elif PD == 5:
total += (7.00 * ... |
#IST 440
# Drive Train (Team 02)
# Author: Ghansyam Patel, Rahul Manoharan, and Klaus
# Date: 10/03/2016
#Unit-Testing
#GoPiGo Robot for DriveTrain
#Unit tests added by Klaus Herchenroder
from gopigo import *
import sys
#Import Unit Test
import unittest
#Returns Value True
def IsTrue():
return True... |
# Section06
# 파이썬 함수식 및 람다(lambda)
# 함수 정의 방법
# def 함수명(parameter):
# code
# 함수 호출
# 함수명(parameter)
# 함수 선언 위치 중요
# 예제1
def hello(world):
print("Hello", world)
hello("Python!")
hello(7777)
# 예제2
def hello_return(world):
val = "Hello " + str(world)
return val
strr = hello_return("Python!!!!!")
p... |
from re import sub
from string import punctuation
def count_words(sentence):
word_count = {}
sentence = sub(f"[{punctuation}]".replace("'", ""), " ", sentence.lower())
sentence = [word.strip("'") for word in sentence.split()]
for word in sentence:
word_count[word] = sum(1 for w in sentence if... |
def leap_year(year):
check1 = is_divisible(year, 4) and not is_divisible(year, 100)
check2 = is_divisible(year, 400)
return check1 or check2
def is_divisible(a: int, b: int) -> bool:
return (a % b) == 0
|
def response(hey_bob):
phrase = hey_bob.strip()
response = "Whatever."
if phrase.isupper() and phrase.endswith("?"):
response = "Calm down, I know what I'm doing!"
elif phrase.isupper():
response = "Whoa, chill out!"
elif phrase.endswith("?"):
response = "Sure."
... |
# Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечным.
# ... |
#!/usr/bin/env python3
""" Module provides a Van class, a subtype of Vehicle class. """
from vehicle import Vehicle
class Van(Vehicle):
"""
Subtype of the Vehicle class.
Contains additional attributes of make and model, num of passengers.
Supports polymorphic behaviour of method get_description.
... |
class SystemInterface :
'''Provides all the methods that any user interface would need for interacting with the system (API)'''
def __init__(self) :
pass
def create (self) :
# returns
pass
def num_avail_vehicles (self, vehicle_type) :
# returns
pass
def get_vehicle (self, vin) :
# returns
pass
de... |
fruits=['apple','pear',5]
#outputs all
print(fruits)
#outputs fruit at index number 0
print(fruits[0])
#to append towards the end of the list
fruits.append('Grapes')
#to remove from list
fruits.remove(5)
#to change item in list
fruits[2]="Guava"
|
## Finds the largest palindrome number obtained after multiplying two three digit numbers
def is_palindrome(str):
if str== reversed(str): return True
return False
def reverse_int(n):
return int(str(n)[::-1])
n=10201
for i in range(999, 100, -1):
for j in range(i,100, -1):
num=i*j
... |
# coding: utf-8
# In[164]:
import numpy as np
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
# Load the data set
data = np.loadtxt('C:/Users/Mina Alpu/Desktop/polynome.data')
# Separate the input from the output
X = data [:, 0]
Y = data [:, 1]
N = len(X)
def visualize(w, X, Y):
... |
# Python program to add two binary numbers.
# Driver code
# Declaring the variables
a = "1101"
b = "100"
# Calculating binary value using function
sum = bin(int(a, 2) + int(b, 2))
# Printing result
print(sum[2:])
|
alphabets=" abcdefghijklmnopqrstuvwxyz"
num=int(input("Enter the number of alphabet you want:"))
alphai=input("Enter the alphabet:")
num_ans=alphabets[num]
alphai_ans = alphabets.index(alphai)
suffix="0"
if num == 1:
suffix="st"
elif num == 21:
suffix="st"
elif num == 2:
suffix="nd"
elif num == 22:
suf... |
"""
An example usage of the python 'requests' module, which will permit
us to retrieve data from wikipedia pages.
"""
import requests
API_URL = 'https://en.wikipedia.org/w/api.php'
PARAMS = {
# "opensearch" is the method we are using
"action" : "opensearch",
"namespace": "0",
# "search" is the search... |
# import from rubikMoves and import random
""" Contains functions that produce a randomly scrambled Rubik's Cube"""
from rubikMoves import *
import random
def scrambleAlgorithm():
# returns a scramble algorithm for the cube
numMoves = 25
moveList = ["R", "R'", "R2", "L", "L'", "L2", "U", "U'", "U2", "D",... |
import sys
def fizzBuzz(fizz, buzz, num):
if num % fizz == 0 and num % buzz == 0:
print("FizzBuzz")
elif num % fizz == 0:
print("Fizz")
elif num % buzz == 0:
print ("Buzz")
else:
print(num)
def main():
for i in range(1,101):
fizzBuzz(3, 5, i)
if __name__=="__main__":
main()
|
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_prime(x):
y=sigmoid(x)
return y(1-y)
class Network():
def __init__(self, num_layers,num_neurons_each_layer,first_neurons_input):
# input:
# num_layers = int
# num_neurons_each_layer = [] each num represents... |
array=[];
# input
print ("Enter any 6 Numbers for Unsorted Array : ");
for i in range(0, 6):
n=input();
array.append(int(n));
# Sorting
print("")
for i in range(1, 6):
temp=array[i]
j=i-1;
while(j>=0 and temp<array[j]):
array[j+1]=array[j];
j-=1;
array[j+1]=temp;
# Output
for i in range(0,6):
print(array[... |
# You might know some pretty large perfect squares. But what about the NEXT one?
# Complete the findNextSquare method that finds the next integral perfect square
# after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.
# If the parameter is i... |
from Classes import ComplexNumbers as cn
while True:
print("Complex calculator")
print("Enter first real part and then complex part")
fr = int(input())
fi = int(input())
print("Enter an operation: +, -, *, /, mag, conj")
option = input()
operation = None
first = cn.CN(... |
print("Enter first name, last name and birthyear")
data = input()
name, lastName, birthYear = data.split(" ")
print("First name: " + name , ", Last name: " + lastName + ", Year of birth: " + birthYear) |
def read_file():
"""
open and read file given for assignment two
and return an array of a list of integers in the file
"""
thefile = open('C:/Documents and Settings/steven/repos/Python-Codes/Algo_One_Stanford/assignment_2_QuickSort.txt'
, 'r')
# initializing the array to be returned
... |
import json
import requests
def pretty_print(data, indent=4):
"""
prints a python dictionary in more readable indented format.
The default indent levels is set at four.
"""
if type(data) == dict:
return json.dumps(data, indent=indent, sort_keys=True)
else:
print data
def api_ge... |
# Problem Set 1 [Paying off Credit Card Debt] from MIT Intro to CS 6.00
# Name:Vivian D
# Time Spent: 45 mins
#Problem 1, Paying the Minimum
"""
Use raw_input() to ask for the following three floating point numbers:
1.
the outstanding balance on the credit card
2.
annual interest rate
3.
minimum monthly payment rate
... |
n = 0
for n in range(10):
print ("Perulangan for Python ke - ", (n))
n+=1
n = 0
while(n<=10):
print ("Perulangan for Python ke - ", (n))
n+=1
n = 0
while(n<=10):
print ("Perulangan for Python ke - ", (n))
n+=1
if n==1:
break |
import pandas as pd
import math
import csv
# print 했을 때 다보이는 방법
pd.set_option("display.max_rows", 10000)
path = "C:/workspaces/python-project/yong-in/data/"
year = 2011
start = 4344
end = 6535
csv_path = path+str(year)+".csv"
# 한글이 있어 오류가 생기므로 engine='python' 을 코드에 넣어줌
df = pd.read_csv(csv_path,h... |
'''
For linked list 1->2->3->2->1, the code below first makes the list to be 1->2->3->2<-1 and the second 2->None, then make 3->None, for even number linked list: 1->2->2->1, make first 1->2->2<-1 and then the second 2->None, and lastly do not forget to make the first 2->None
(If forget it still works while the idea b... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 6 01:20:14 2020
@author: Oshi
"""
class dummybank_API:
def __init__(self): #assunimg 5 digit bank accoount number
self.my_dict = {12345:1234, 22222:2345} #hardcoding the dictionary for testing
self.account_number = None
self.... |
from random import *
class Bag():
def __init__(self):
self.data = []
print('Creating bag...')
def add(self,item):
self.data.append(item)
print('Added an item to the bag')
def removeItem(self,item):
if item in self.data:
self.data.remove(item)
print('Removed an item from the bag')
... |
# print the replacment fields in the order I want, otherwise it would replace
# {} in the order of 0, 1, 2, 3, 4 , ...,
#V this way flops it backwards
#formatter ="{3} {2} {1} {0}"
#V this way is standard
formatter = "{} {} {} {}"
# print the
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two"... |
# This line prints a string
print("I will now count my chickens:")
# This line prints a string and computation
print("Hens", float(25 + 30 / 6))
# This line prints a string and computation
print("Roosters", float(100 - 25 * 3 % 4))
# This line prints a string
print("Now I will count the eggs:")
# This line does comp... |
"""
Utility used by the Network class to actually train.
Based on:
https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py
"""
from keras.datasets import mnist, cifar10
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.utils.np_utils import to_categorical
from kera... |
from matplotlib import pyplot as matplot
from matplotlib import animation as matani
def plotfun(z1,z2,maxy):
fig = matplot.figure()
axes = matplot.axes(xlim=(0,len(z1)), ylim = (0,maxy))
line, = axes.plot([],[], lw=2)
def init():
line.set_data([], [])
return line,
def animate(j):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.