text stringlengths 37 1.41M |
|---|
'''
Write a script that "flattens" a list. For example:
starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
f_list = []
for el in starting_list:
for i in el:
f_list.append(i)
print(f_list) |
ordered_lists = [[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
print('\n')
print("Determine the smallest range of integers that is common to all lists:")
print("Ordered lists of positive integers:")
print(ordered_lists)
print('\n')
list_of_items=[]
shortest_interval = []
i = 0
while True:
for element in ordered_lis... |
import pygame
import sys
from pygame.locals import QUIT
from time import sleep
class Gui ():
"""The Gui class contains all code regarding the Graphical User Interface.
Attributes:
width (Int) The width of the screen.
height (Int) The height of the screen.
... |
# Description: The aim of this file is to translate keyboard buttons into dots
#
def inverse_value(key_presses, key):
"""Inverses the value assigned to the key: 0 -> 1, 1 -> 0
Parameters:
key_presses (Dict) Dictionary which counts amount of times keys pressed.
key (String) ... |
from src.learning.learning_tool import LearningTool
import time
class SpellingGame(LearningTool):
"""This class provides objects acting as fun spelling games"""
def __init__(self, interaction_object, spelling_word, time_until_hint=20, simulations=None, max_timeout=None):
super().__init__(interaction... |
# Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
while True:
usr_input = input("Введите число\n")
if usr_input.isdigit():
result = int(usr_input) + int(usr_input * 2) +int(usr_input * 3)
break
else:
... |
# Implementation using built-in queue module
from queue import Queue
# initializing a queue with maximum size
myQueue = Queue(maxsize=5)
# Adding elements - Enqueue operation
myQueue.put(1)
myQueue.put(2)
myQueue.put(3)
myQueue.put(4)
print("Added 4 elements into the queue")
# Checking whether the queue is full
print... |
import numpy as np
class Caja:
"""
Clase que representa a la caja
"""
def __init__(self, horas, empleado, ocupacion):
self.disponible = True
self.horas = horas
self.empleado = empleado
self.ocupacion = ocupacion
def estoy_libre(self):
return self.dispon... |
"""Describe file"""
import sqlite3
conn = sqlite3.connect('NAME_OF_DATABASE')
#put your variables, etc.
def make_db():
"""Describe this function here!!"""
curs = conn.cursor()
#execute your queries related to creating database and inserting stuff
curs.close()
conn.commit()
def run_queries():
... |
import sqlite3
import pandas as pd
import psycopg2
# convert csv file into a table and create a database for that table.
# #df = pd.read_csv('https://raw.githubusercontent.com/EvidenceN/DS-Unit-3-Sprint-2-SQL-and-Databases/master/module2-sql-for-analysis/titanic.csv')
# #sl_conn = sqlite3.connect('database name')
#... |
class Pet:
# implement __init__( name , type , tricks ):
def __init__(self, name, type, tricks):
self.name = name
self.type = type
self.tricks = tricks
self.health = 0
self.energy = 0
# implement the following methods:
# sleep() - increases the pets energy by 25
def slee... |
import numpy as np
def confusion_matrix(actual, predictions):
"""
Given predictions (an N-length numpy vector) and actual labels (an N-length
numpy vector), compute the confusion matrix. The confusion
matrix for a binary classifier would be a 2x2 matrix as follows:
[
[true_negatives, fal... |
import math
import csv
from operator import itemgetter
from pprint import pprint
def csv_to_list_of_dicts(csv_file_to_convert):
list_of_dicts = []
with open(csv_file_to_convert) as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
list... |
import pandas as pd
df = pd.read_csv("data_raw.csv")
all_features = df.columns
# Let's drop some features
names = [feat for feat in all_features if "net_name" in feat] # excluded for privacy reasons
useless = ["info_gew","info_resul","interviewtime","id","date"] # features that we expect are uninformative
d... |
mysring = "ThiS is String with Upper and lower case Letters"
alphabet = ["a","c","d","e","g","h","i","l","n","o","p","r","s","t","u","w"]
def count (mystring,f_letter):
count=0
for letter in alphabet:
if (letter.lower()== f_letter.lower()):
count+=1
return count
for letter in alphabet:
... |
def keep_ints(cond,n):
""" Print out all integers 1..i..n where cond(i) is true"""
curr = 0
def
while curr <= n:
if cond(curr) == True:
print(curr)
curr += 1 |
import argparse
from pathlib import Path
lines = []
def parse_args():
"""
return args from command prompt
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-r",
help="reverse sort"
)
parser.add_argument(
'-f',
help="ignore case",
action="... |
#Create a function that will do the following:
#accum("abcd") # "A-Bb-Ccc-Dddd"
#accum("RqaEzty") # "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
#accum("cwAt") # "C-Ww-Aaa-Tttt"
def accum(s):
count = 1
l = []
for letter in s:
l.append((str(letter) * count).capitalize())
count = c... |
# -*- coding: utf-8 -*-
a = eval(input())
b = eval(input())
c = a*a
d = b*b
if c>d:
print(c-d)
else:
print(d-c) |
#-*-coding:utf-8-*-
def mkstr(astr,bstr, num):
fstr = ""
for i in range(1, num+1):
if i%2 > 0 :
fstr += astr
elif i%2 == 0:
fstr += bstr
fstr += " "
flist = fstr.split()
flist.reverse()
return flist[0]
def main():
n = eval(input())
a = input(... |
def knock_knock():
print("Knock knock")
response1 = input('type here: ')
if response1 == "who's there":
print("Europe")
response2 = input('type here: ')
response2 = response2.lower()
if response2 == 'europe who' or 'europe who?':
print("I'm not a poo, you're a poo... |
'''
In this project, you will visualize the feelings and language used in a set of
Tweets. This starter code loads the appropriate libraries and the Twitter data you'll
need!
'''
import json
from textblob import TextBlob
import matplotlib.pyplot as plt
#Get the JSON data
tweetFile = open("tweets_small.json", "r")
twe... |
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:r... |
#-------------------------------------------------------------------------------
# Name: module5
# Purpose:
#
# Author: RGCET
#
# Created: 10/03/2018
# Copyright: (c) RGCET 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
d... |
# --------------------------------------------------------------
# Ülesanne 1:
#
# Luba kasutajale sisestada aeg kujul tunnid.minutid (näiteks 3.23 tähendab, et tegu on 3 tunniga ja 23 minutiga, aga väärtus on sisestatud nagu komaga arv 3.23)
#
# Programm peab arvutama, mitu tundi ja mitu minutid on sisestatud ja ... |
#!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
length_Tuple_a = len(tuple_a)
length_Tuple_b = len(tuple_b)
if not length_Tuple_a:
first_tuple = (0, 0)
elif length_Tuple_a == 1:
first_tuple = (tuple_a[0], 0)
else:
first_tuple = tuple_a
if not length_Tuple_b:... |
#!/usr/bin/python3
def max_in_dict(a_dict={}):
maxVal = 0
maxKey = 0
for key, val in a_dict.items():
if maxVal < val:
maxVal = val
maxKey = key
return maxKey
def best_score(a_dictionary):
if a_dictionary is None or len(a_dictionary) == 0:
return None
e... |
#!/usr/bin/python3
"""
5-text_indentation:
Functions:
text_indentation
"""
def text_indentation(text):
"""
text_indentation: print text with indentation
Args:
@text: text to print
"""
if type(text) != str:
raise TypeError("text must be a string")
... |
#!/usr/bin/python3
def multiply_by_2(a_dictionary):
dictionary = a_dictionary.copy()
for key in dictionary.keys():
dictionary[key] *= 2
return dictionary
|
#!/usr/bin/python3
"""unit tests"""
import unittest
from models.rectangle import Rectangle
class test_rectangle(unittest.TestCase):
"""class that inherits from TestCase"""
def test_cases(self):
"""function test"""
rect = Rectangle(5, 4)
self.assertEqual(rect.width, 5)
self.asse... |
#!/usr/bin/python3
"""0-read_file
functions:
read_file
"""
def read_file(filename=""):
"""read_file: read a given file"""
with open(filename, "r") as my_file:
content = my_file.read()
print(content, end="")
|
"""
Lines of Action Move class
Starbuck Beagley
"""
ERR_MESS = 6
class Move:
def __init__(self, b, p1, p2):
"""
Constructor
:param b: board
:param p1: player 1
:param p2: player 2
"""
self.board = b
self.player1 = p1
self.pla... |
"""
Lines of Action Board class
Starbuck Beagley
"""
class Board:
def __init__(self, r, c, p1, p2):
"""
Constructor
:param r: total rows
:param c: total columns
:param p1: player 1's piece
:param p2: player 2's piece
"""
self.rows = r
... |
n1 = int(input("Enter Number n1: "))
n2 = int(input("Enter Number n2: "))
temp = n1
n1 = n2
n2 = temp
print("After swapping")
print("n1 = ", n1, "\nn2 = ", n2) |
#!/usr/bin/env python
from random import randint
class Rectangle:
"""This is a Rectangle class which has two different members"""
def __init__(self, width, height):
self.width = width
self.height = height
def calcArea(self):
'''
Function : calculate the area of the Rectan... |
a=int(input("Enter first number:"))
b=int(input("Enter second number"))
c=a+b
print("addition of two number is:",c3) |
class MarkSheet:
outofmarks=100
def __init__(self,first_name,last_name,roll_num,eng_marks,maths_marks,sci_marks):
self.f_name=first_name
self.l_name=last_name
self.roll=roll_num
self.eng=int(eng_marks)
self.maths=int(maths_marks)
self.sci=int(sci_marks)
self.engper=(self.eng*int(self.outof... |
#PRogram to use Write and Read method for the file object
file_obj=open("demofile.txt","r+")
file_obj.write("My Name is Rateesh \nI am your Instructor!")
file_obj.close()
file_obj2=open("demofile.txt","r")
file_str=file_obj2.read()
print(file_str) |
#Program to identify whether individual is Kid, Teenager, Adult or old
while True:
age_input=int(input("Please Enter your Age: "))
if age_input<=12 and age_input>=0:
print("You are a Kid!")
elif age_input>=13 and age_input<=18:
print("You are a Teenager!")
elif age_input>=18 and age_input<=50:
p... |
# Conjunto de importações
# Implementação do Código para Captura dos Dados no Twitter e gravação em arquivo do tipo Json..
# Autor: Ricardo Roberto de Lima. - Data: 01/08/2017
import json
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from collections import... |
"""
Calculating with Fractions
--------------------------
Problem:
--------
You have entered a time machine and suddenly find yourself working on
elementary level homewrok problems involving fractions. Or perhaps you're
writing code to make calculations involving measurements made in your woo... |
"""
Stripping Unwanted Characters from Strings
------------------------------------------
Problem:
--------
You want to strip unwanted characters, such as whitespace, from the
beginning , end, or middle of a text string.
Solution:
---------
The strip() method can be used to strip charact... |
"""
Manually Consuming an Iterator
------------------------------
Problem:
--------
You need to process items in an iterable, but for whatever reason, you can't
or don't want to use a loop.
Solution:
---------
To manually consume an iterable, use the next() function and write your code
t... |
"""
Problem:
--------
You want to sort objects of the same class, but they don't natively support
comparison operations.
Solution:
---------
The built-in sorted() function takes a key argument that can pass a callable
that will return some value in the object that sorted will use to compare the
objects.
"""
cla... |
"""
Problem:
--------
You have a sequence of items, and you'd like to determine the most frequently
occuring items in the sequence.
Solution:
---------
The collections.Counter class is designed for just such a problem. It even
comes with a handy most_common() method that will give you the answer.
To illustrat... |
"""
Converting Days to Seconds, and Other Basic Time Conversions
------------------------------------------------------------
Problem:
--------
You have code that needs to perform simple time converstions, like
days to seconds, hours to minutes, and so on.
Solution:
---------
To Perform conversi... |
"""
Mapping Names to Sequence Elements
Problem:
--------
You have code that accesses a list or tuple by position, but this makes the
code somewhat difficult to read at times. You'd also like to be less dependent
on position in the structure, by accessing the elements by name.
Solution:
----... |
"""
Creating New Iteration Patterns with Generators
-----------------------------------------------
Problem:
--------
You want to implement a custom iteration pattern that's different than
usual built-in functions (e.g., range(), reverse(), etc).
Solution:
---------
If you want to implem... |
class Solution:
# @param A : tuple of integers
# @return a list of integers
# Time Complexity : O(n)
# Space Complexity : O(1)
def repeatedNumber(self, A):
n = len(A)
total_arr = sum(A)
total_n = (n*(n+1))//2
total_arr_sq = sum([i*i for i in A])
total_n_sq = ... |
class contacto:
def __init__(self, nombre_nuevo, apellido_nuevo, telefono_nuevo, mail_nuevo):
self.mail = mail_nuevo
self.apellido = apellido_nuevo
self.nombre = nombre_nuevo
self.telefono = telefono_nuevo
self.siguiente = None
class lista:
def __init__(self):
s... |
def print_students(values):
for obj in values:
print obj['first_name'] + " " + obj['last_name']
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_na... |
# Multiples
for i in range(1, 1001):
print i
for i in range(5, 1000001, 5):
print i
# Sum
def sum(x):
sum = 0
for i in x:
sum += i
return sum
a = [1, 2, 5, 10, 255, 3]
print sum(a)
# Average
def avg(x):
return sum(x)/len(x)
print avg(a) |
class Product(object):
def __init__(self, price, name, weight, brand):
self.price = price
self.name = name
self.weight = weight
self.brand = brand
self.status = "for sale"
def sell(self):
self.status = "sold"
return self
def add_tax(self, tax... |
def type_list(l):
hasInt = False
hasFloat = False
hasString = False
total = 0
string = ""
for i in l:
if isinstance(i, int):
hasInt = True
total += i
elif isinstance(i, float):
hasFloat = True
total += i
elif isinstanc... |
"""Function for accessing the current session."""
# stdlib
from typing import Optional
from typing import Union
from uuid import UUID
import sympc.session
from .session import Session
def get_session(uuid: Union[str, UUID]) -> Optional[Session]:
"""Gets the current session for a party as defined in the global s... |
a,b=raw_input().split(" ")
a=int(a)
b=int(b)
for i in range(a+1,b+1):
if (i%2!=0):
print(i),
|
a=int(raw_input())
b=a%10
e=a/10
c=e%10
d=e/10
x=b**3+c**3+d**3
if(x==a):
print("yes")
else:
print("no")
|
#! /usr/bin/env python
import sys
import numpy as np
# import our Random class from python/Random.py file
sys.path.append(".")
from python.Random import Random
#################
# MySort class
#################
# class to sort lists of objects in different ways
class MySort:
"""A crappy sorting class"""
# i... |
x=int(input("enter your age\n"))
y=18
if x>y and x<100:
print("eligible for driving\n")
elif x==y:
print("cannot decide\n")
elif x>100 or x<7:
print("enter a valid age")
else:
print("not eligible for driving\n") |
import math
sum = 0
with open('input.txt', 'r') as f:
for line in f:
mass = int(line.strip('\n'))
fuel = math.floor(mass / 3) - 2
sum += fuel
print(sum)
|
def min_v2(x):
current_min = x[0]
for element in x:
if element < current_min:
current_min = element
return current_min
def test_min_returns_min_value_of_length_1_array():
x = [0]
assert min_v2(x) == 0
def test_min_returns_min_value_of_presorted_array():
x = [1, 5]
as... |
import random
import string
def concatenate(list):
string = ''
for i in range(len(list)):
string = string + list[i]
return string
guess_list = ('python', 'java', 'kotlin', 'javascript')
guess = guess_list[random.randint(0, len(guess_list) - 1)]
guessed = list(len(guess) * '-')
typed_letters = ''
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 18 10:33:17 2019
@author: lenovo
"""
import numpy as np
a=input("enter the number").split()
a=[int(i) for i in a]
x=np.array(a)
print(type(x))
x=x.reshape(3,3)
print(x)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 20:17:08 2019
@author: lenovo
"""
import collections
d = collections.OrderedDict()
orders = [["34587", "Learning Python, Mark Lutz", 4, 40.95],
["98762", "Programming Python, Mark Lutz", 5, 56.80],
["77226", "Head First Python, Paul B... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 18:10:08 2019
@author: lenovo
"""
def reverse_fun(greeting):
return 'welcome {}'.format(greeting)
greeting="I am kuldeep"
print(reverse_fun(greeting))
greeting[::-1] |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 11:23:32 2019
@author: lenovo
"""
names = ['Mary', 'Isla', 'Sam']
#for i in range(len(names)):
s= map(hash,names)
#print (names)
print(list(s)) |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 14:02:29 2019
@author: lenovo
"""
inc=input("Enter the bricks")
inc1=input("Enter the bricks")
inc2=input("Enter the bricks")
if int(inc2)%5>int(inc1):
print(False)
else:
red = 5*int(inc2)+1*int(inc1)
if red>int(inc):
print(True)
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 10:20:02 2019
@author: lenovo
"""
n=input("Enter the number>").split()
list_1=[True if (i==i[::-1]) and (int(i)>0) else False for i in n]
print(all(list_1))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 8 12:03:43 2019
@author: lenovo
"""
#you are given two list of numbers and you need to find total of each of the list
#this is the function tpic
total1=[2100,3400,3500]
total2=[3499,3288,5443]
def calculate(exp):
total=0
for item in exp:
total=total+ite... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 18:30:01 2019
@author: lenovo
"""
#def palindrome_number(list_a):
# c=0
n=input("Enter the number").split(" ")
#these are the t
for i in n:
if i == i[::-1]:
print(i)
t=n
rev=0
#this is define the rewverse
rem = i % 10
#it used as the remainder
rev=rev*10... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 22:36:16 2019
@author: lenovo
"""
my_list = []
orders = [ ["34587", "Learning Python, Mark Lutz", 4, 40.95],
["98762", "Programming Python, Mark Lutz", 5, 56.80],
["77226", "Head First Python, Paul Barry", 3,32.95],
["88112", "Einfüh... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 12:31:55 2019
@author: lenovo
"""
assignment1=(100*10)/100
assignment2=(100*10)/100
assignment3=(100*10)/100
#these are the assignment of 3 subjects
assignment=assignment1+assignment2+assignment3
#this is the total of 3 assignment
print(assignment)
exam1=(100*35)/100
... |
import stdio
import math
stdio.writeln("Calculating Plants and Soil needed")
stdio.writeln("Inputs needed")
lg = float( input("Enter length of garden (feet):"))
sbp = float( input("How much spacing do you want between plants (feet):"))
dog = float( input("What depth you want to dig (feet):"))
dof = float( input("How... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
#Filename: print_index.py
colors = [ 'red', 'green', 'blue', 'yellow' ]
for i in range(len(colors)):
print (i, '->', colors[i])
# >>> 0 -> red
# 1 -> green
# 2 -> blue
# 3 -> yellow
# >>>
for i, color in enumerate(colors):
print (i, '->', color)
|
"""
Created on 23 Aug, 2021
@author : Sai Vikhyath
"""
# Always try avoiding *
# This affects performance as it imports all the modules and functions
from math import *
import cmath
"""
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise ope... |
"""
Created on 24 Aug, 2021
@author: Sai Vikhyath
"""
# Create a simple class
class BasicClass: # Class Name
# Class Variables Go here
a = 0 # Variable assignment
var1: int # Variable declaration
# Class Method Go here
def func(self, aStr="Hello Word"):
a = "hello"
# Var... |
"""
Created on 25 Aug, 2021
@author : Sai Vikhyath
"""
"""
Illustration of decorators in Python
"""
def methodOneDecorator(fnToDecorate):
def wrapperToMethodOne(): # Wrapper method
print("Before the function runs") # Code to setup and base
fnToDecorate()
print("After the function runs"... |
'''
Read in the first number from 'integers.txt' and perform a calculation
with it.
Make sure to catch at least two possible Exceptions (FileNotFoundError and ValueError)
with specific except statements, and continue to do the calculation
only if neither of them applies.
To test, try running it on:
- 'integers.txt' (s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Knight(object):
def __init__(self, life, speed, attack_power, attack_range, weapon):
self.unit_type = "Knight"
self.life = life
self.speed = speed
self.attack_power = attack_power
self.attack_range = attack_range
se... |
# -*- coding: utf-8 -*-
from datetime import datetime
from threading import Timer
import time
'''
每个 10 秒打印当前时间。
'''
def timedTask():
'''
第一个参数: 延迟多长时间执行任务(单位: 秒)
第二个参数: 要执行的任务, 即函数
第三个参数: 调用函数的参数(tuple)
'''
Timer(5, task, ()).start()
# 定时任务
def task():
print(datetime.now().strftime("%Y-%... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyperclip
from chapter_12_通过编程检测英文 import detectEnglish
# 欧几里得算法找出两个数的最大公约数
def gcd(a, b):
while a != 0:
a, b = b % a, a
return b
LIST_TEXT = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encrypt(key):
list_encrypt = ''
for i in range(len(LIST_TEX... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def fib(x):
fib_list = []
a, b = 0, 1
while a < x:
fib_list.append(a)
a, b = b, a + b
return fib_list
def fib2(x):
fib_list = []
a, b = 0, 1
for i in range(x):
if a > x:
break
fib_list.append(a)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyperclip
from chapter_12_通过编程检测英文 import detectEnglish
from chapter_09_使用换位加密法解密 import transpositionDecrypt
def hackTransposition(message):
print('Hacking...')
print('(Press Ctrl-C or Ctrl-D to quit at any time.)')
for key in range(1, len(message))... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Soldier(object):
def __init__(self, unit_type, level):
self.unit_type = unit_type
if self.unit_type == "Knight":
if level == 1:
self.life = 400
self.speed = 5
self.attack_power = 3
... |
# Exercise 04 and 05
import sys
def humanise(num):
GB = 1024.0 ** 3
MB = 1024.0 ** 2
KB = 1024.0
if num > 1.5*GB:
return round(num / GB, 2), "GB"
elif 1.5*GB >= num > 1.5*MB:
return round(num / MB, 2), "MB"
elif 1.5*MB >= num > 1.5*KB:
return round(num / KB, 2), "KB"
... |
S = "\t"
size = int(input())
def main():
arr = []
for i in range(size):
# row = []
row = size*[0]
for j in range(size):
v = (i + 1) * (j + 1)
# row.append(v)
row[j] = v
arr.append(row)
# print()
print_array(arr)
def print_array(... |
"""
测试带选择框的GUI
"""
from tkinter import *
from tkinter.scrolledtext import ScrolledText
def get():
print(v.get())
master = Tk()
text = ScrolledText(master, font=('微软雅黑'))
# textbar = Scrollbar(master)
# textbar.grid(row=0,column=2)
text = Entry(master, font=('微软雅黑', 20))
text.grid(row=0,column=1, rowspan=4)
MO... |
## author Matt Blaul
## 1/26/2018
## CSI 3370
def main():
ninety_nine_bottles_of_beer()
def ninety_nine_bottles_of_beer():
numbottles = 99
for x in range(numbottles, 0, -1):
if (x > 1):
print(str(x) + " bottles of beer on the wall, " + str(x) + " bottles of beer")
if(x-1 > ... |
"""
Distance functions:
Euclidian distance, Hamming distance, Levenshtein distance, Damerau-Levenshtein distance
"""
import math
import itertools
import collections
try:
from itertools import izip
except ImportError:
# Python 3.x - zip is iterable
izip = zip
xrange = range
from pymisc.utils.structs im... |
# Spurs Draft MMXVI
# By Ryan Gentry
# PA Kassandra Smith
# This is a game based on the draft on the 2K MyTeam Central and
# the mode MyLEAGUE on the game NBA 2K16.
# This imports libraries for the game to call from, and sets the salary cap.
import math
import random
import statistics
import sys
SCOVR = 82
# This is ... |
import numpy as np
"""
Numpy basics
"""
# basic arrays - think matrices
a = np.array([[1,2], [1,1], [0,0]])
print(np.shape(a)) # (3, 2)
print(np.ndim(a)) # 2
# operators and methods
x = np.array([[2,0],[0,2]])
y = np.array([[1,1],[2,2]])
print(x*y) # element-wise multiplication of equal shape arrays
print(np.ma... |
'''
this code is used for scrap data from json file
'''
import json
ans=set()
f=open('csvjson.json',)
#this below line is used for load json file
data=json.load(f)
#below code for scrap data from json file
for j in range(len(data)):
for i in data:
ans.add(data[j]['email'])
print(ans)
print(len(ans))
f.close()... |
#Funktiot eli kysymykset
#Kysymys1
def kysymys1(kysymyslista):
vastaus = input("Kysymys:\na)vaihtoehto\nb)vaihtoehto\nc)vaihtoehto\nVastauksesi: ").lower()
if vastaus =="a" or vastaus=="b" or vastaus=="c":
if vastaus =="a":
oikeat_vastaukset +=1
else:
print("vastaa a, b tai c")
... |
# list - mutable
# 생성된 후에 변경가능
# 원소 추가 삭제 가능
# tuple - immutable
# 생성된 후에 변경 불가능
a = []
print(a)
a = [1,2,3,5,10]
print(a)
a = ['Korea','canada',1,23,[34,56]]
print(a)
a = 'hello world'
b = list(a)
print(b)
c = (1,2,3)
d = list(c)
print(d)
a = 'hello world nice weather'
b = a.split()
print(b)
a = [1,2,3,4,5,6]
... |
import string
from itertools import repeat
from random import choices, randint
_alphabet = string.ascii_lowercase + string.ascii_uppercase + string.digits
def _get_random_string(length):
return ''.join(choices(_alphabet, k=length))
def random_strings(min_length, max_length=None, N=None):
return (
... |
''' Read input from STDIN. Print your output to STDOUT '''
#Use input() to read input from STDIN and use print to write your output to STDOUT
'''
Method to read the input from STDIN
Format the qty values in a list and convert the
list elements into integers
'''
def read_user_input():
no_of_ingred = ... |
"""
Implementing Stack Datastructure in Python
Using List
"""
class Stack(object):
"""
Creates a stack using list
"""
def __init__(self):
"""
Initializing stack array
param: None
return: None
"""
self.stack = []
def push(self, value):
"""
... |
# 레퍼런스 복사
import copy
a = 1
b = a
a = [1, 2, 3]
b = [4, 5, a]
x = [a, b, 100]
y = x
# 레퍼런스 복사하는 것은 동일한 레퍼런스 (동일 객체)
print(x)
print(y)
print(x is y)
# swallow copy(얕은 복사)
# copy를 시킨 경우에는 새로운 객체가 만들어지긴 하지만 참조하는 변수들은 동일하게 참조함
a = [1, 2, 3]
b = [4, 5, a]
x = [a, b, 100]
y = copy.copy(x)
print(x)
print(y)
print(x is y)
... |
# Brian Powell 012362894
# EE381 - Chaw-Long Chu
#
# Homework_3
#
# Question_1
# Please Use:
#
# (1) One order equation (y=ax+b) and
# (2) Third order equation (y=ax^3+bx^2+cx+d) and
# (3) Second order equation (y=a+bx+cx^2) using spread sheet to manually calculate the coefficients of (a,b, and c) to fit the follow dat... |
valor = int(input())
n100 = 0
n50 = 0
n20 = 0
n10 = 0
n5 = 0
n2 = 0
n1 = 0
print(valor)
while valor >= 100:
n100 += 1
valor -= 100
else:
while valor >= 50:
n50 += 1
valor -= 50
else:
while valor >= 20:
n20 += 1
valor -= 20
else:
whil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.