text stringlengths 5 121k |
|---|
from tkinter import *
from random import *
from tkinter.font import *
root=Tk()
root.title('Guessing Number by System')
def start():
correct="n"
a,b=1,100
counter=1
while correct!="y":
my_guess=(a+b)//2
label_result1=Label(root,text="My guess is ")
label_result1.g... |
num = 0
while num <= 26:
print(num)
num = num + 1
if num == 26:
break
for numbers in range(0,26):
print(numbers) |
import pygame
import math
pygame.init()
WIDTH = 1000
HEIGHT = 600
class Ball(object):
def __init__(self, velocityX, velocityY, size, angle, speed, color):
self._posX = WIDTH/2 - size/2
self._posY = HEIGHT/2 - size/2
self._velocityX = velocityX
self._velocity... |
import tkinter as tk
class MyDialog:
def __init__(self, master):
self.top = tk.Toplevel(master)
self.label1 = tk.Label(self.top, text='版权所有')
self.label1.pack()
self.label2 = tk.Label(self.top, text='V 1.0.0')
self.label2.pa... |
y=int(input("请输入"))
if(y%400==0):print("Y")
else:
if(y%4==0):
if(y%100==0):
print("N")
else:
print("Y")
else:
print("N")
input()
|
from tkinter import *
import math
WIDTH = 510; HEIGHT = 210
ORIGIN_X = 2; ORIGIN_Y = HEIGHT / 2
SCALE_X = 40; SCALE_Y = 100
END_ARC = 360 * 2
ox = 0; oy = 0; x = 0; y = 0
arc = 0
root = Tk()
c = Canvas(root,bg = 'white', width=WIDTH, height=HE... |
x = int(input("请输入x坐标:"))
y = int(input("请输入y坐标:"))
if (x == 0 and y == 0): print("位于原点")
elif (x == 0): print("位于y轴")
elif (y == 0): print("位于x轴")
elif (x > 0 and y > 0): print("位于第一象限")
elif (x < 0 and y > 0): print("位于第二象限")
elif (x < 0 and y < 0): print("位于第三象限")
else: print("位于第四象限")
input()
|
def is_prime(value, know_primes=[]):
'''
Given a list of prime numbers, check if a number is a prime number
'''
if (max(know_primes)**2) > value:
for prime in know_primes:
if (value % prime) == 0:
return False
return True
else:
raise ValueError('List of known primes is too short for the given value'... |
from .piece import Piece
class Lance(Piece):
piece_type = "L"
""" Object constructor """
def __init__(self, color):
super().__init__(color)
""" A lance (L) moves one or more squares straight forward. It cannot moves backwards or to the side. """
def correct_move(self, from_x, from_y, ... |
import random
name = ""
question = "Will it rain?"
answer = ""
random_number = random.randint(1, 10)
if random_number == 1:
answer = "Oh yeah, for sure."
elif random_number == 2:
answer = "If I told you, I'd have to kill you."
elif random_number == 3:
answer = "Signs point to groovy."
elif random_number == 4... |
"""
Created on Tue Jan 12 10:46:34 2021
@author: nick
"""
list_1 = [222, 333, 444, 333]
list_1 = set(list_1)
print(list_1)
print('\n')
s_1= {1,2,3,4,4,5,5,6,6}
print(type(s_1))
print(s_1) |
'''
Created on Sep 5, 2017
@author: Jack
'''
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y', 'x'], rename=True)
p = Point(11, 1, 22)
print(p)
if __name__ == '__main__':
for i in p:
print(i)
pass
|
'''
Created on Nov 13, 2017
@copied_by: Jack
'''
import threading
from time import sleep
import time
import _thread
def function(i):
sleep(3)
print ("function called by thread %i\n" % i)
return
def main():
threads = []
for i in range(5):
t = threading.Thread(target=function, args=(i, ))... |
def retrieve(d):
print_d(d)
print("INVERTED INDEX:")
b = inv_index(d)
print_inv_d(b)
def inv_index(d):
idx = {}
for k,v in d.items():
for element in v:
idx[element] = idx.get(element, []) + [k]
return idx
def intersect(d):
pass
def print_d(d):
for k,v in d.item... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
def init_weights(shape):
init_random_dist=tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(init_random_dist)
def init_bias(shape):
init_bias_vals=tf.con... |
import pygame
from common.common import *
class Player:
"""
"""
def __init__(self, x, y, name, conn, world_ref):
self.name = name
self.score = 0
self.conn = conn
self.pict = pict_player
self.case_x = x
self.case_y = y
self.world = world_ref
'''... |
class Person:
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
def bmi(self):
result = self.weight / (self.height*self.height)
print(self.name, 'のBMI値は', result, 'です。')
class BusinessPerson(Person):
def __init__(s... |
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""A class to manage the ship."""
def __init__(self, ai_game):
"""Initialize the ship and set its starting position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
se... |
from __future__ import annotations
from abc import ABC, abstractmethod, abstractproperty
from typing import Any
class ManufacturerBuilder(ABC):
@abstractproperty
def product(self) -> None:
pass
@abstractmethod
def gatherRawMaterials(self) -> None:
pass
@abstractmethod
def sti... |
import random
random_num = random.randint(1,10)
tipp = -1
for i in range(0,10):
print("You have " + str(10 - i) + " try/tries left!")
tipp = int(input("Guess a number between one and ten!"))
if random_num == tipp:
print("YOU WIN!")
break
else:
print("Try again!")
if ... |
import random
shapes = {"s": "✂", "p": "📄", "r": "🤘"}
def gameLogic():
print("Welcome to classic awesome Rock Paper Scissor.\nChoose a shape by entering its initial.\nEx r for Rock, s for Scissors and p for paper.\nGood luck :)\n")
playerName = input("Please enter your name: ").capitalize()
print("")
... |
"""
The aim of the kata is to try to show how difficult it can be to calculate decimals of an irrational number with a certain precision. We have chosen to get a few decimals of the number "pi" using the following infinite series (Leibniz 1646–1716):
PI / 4 = 1 - 1/3 + 1/5 - 1/7 + ... which gives an approximation of P... |
def simplest(vals):
sz = len(vals)
longest_so_far = 0
for ii, left in enumerate(vals):
for jj in range(sz-1, ii, -1):
right = vals[jj]
if right > left:
if jj - ii > longest_so_far:
longest_so_far = jj - ii
return longest_so_far
def li... |
from collections import deque
class Node():
def __init__(self, val=None):
self.left = None
self.right = None
self.val = val
class BST():
def __init__(self, vals=None):
self._root = None
if vals is not None:
for val in vals:
s... |
print("\nWONDER WOMAN 1984 Quiz\n")
print("Which WONDER WOMAN 1984 character are you most like?")
print("To find out, answer the following questions.\n")
activity = input( "How would you like to spend your evening?\n(A) Reading a book\n(B) Attending a party\n\nAnswer: " )
if activity == "A":
print( "Reading a boo... |
'''
Modulo + Array
As one of the most intuitive implementations, we could adopt the modulo operator as the hash function, since the key value
is of integer type. In addition, in order to minimize the potential collisions, it is advisable to use a prime number as
the base of modulo, e.g. 2069.
We organize the storag... |
'''
Dynamic Programming -
Here, instead of a complete n*n matrix, we only use a triangle (or upper diagonal triangle of the n*n matrix)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
which is
1 1 1 1 1
1 2 3 4 .
1 3 6 . .
1 4 . . .
1 . . . .
And we return the values out
Time: O(N^2)
Space: O(N^2)
'''
class Solution:
def gen... |
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
Here,
time complexity - O(n)
Space complexity - O(2) or O(1) for i and temp
"""
temp = 0
i=0
while i<len(s)//2:
... |
'''
Using one Dictinary
Increment by 1 if the key is found in s[i]
Decrement by 1 if the key is found in t[i]
return if all values of the dictionary are zero
'''
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s)!=len(t):
return False
dic1 = {}
for i... |
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
""By applying mathematical formula and generating the integer back in reverse order""
"""
result = 0
multiplier = 10 ... |
import math
def get_min(visited, table, neighbors):
pass
def build_shortest_path(graph, start):
table = {}
unvisited = []
for v in graph.keys():
unvisited.append(v)
if v == start:
table[v] = [0, ""]
else:
table[v] = [math.inf, ""]
print(table)
print... |
def get_resistance(voltage, current):
try:
resistance_value = int(voltage) / int(current)
resistance_value = f'Resistance = {resistance_value:.3f} Ω'
except:
resistance_value = 'Current should not be 0'
return resistance_value
def get_current(voltage, resis... |
from typing import List
def combine_ropes(ropes: List[List[str]]) -> bool:
count = 0
prev = len(ropes)
ropes_remaining = ropes
while ropes_remaining:
print(ropes_remaining)
if count == prev:
return False
current_rope = [ropes_remaining[0][0], ropes_remaining[0][1]]
... |
from collections import deque
def level_order_traversal(r):
q = deque()
q.append(r)
while q:
top = q.popleft()
print(top.val)
if top.left:
q.append(top.left)
pass
if top.right:
q.append(top.right)
pass
|
def check_duplicate(array, k):
s = set(array[:k])
if len(s) < k:
return True
l = len(array)
if l < k:
return False
for i in range(k, l):
top = array[i-k]
if array[i] in s:
return True
s.remove(top)
s.add(array[i])
return False
if __... |
from collections import deque
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def min_depth(root: TreeNode) -> int:
if not root:
return 0
else:
md = 0
q1 = deque()
q1.append(root)
... |
"""
Created on Sun Jan 31 16:46:44 2021
@author: anand
"""
def new(dict):
for key, value in dict.items():
return key, value
a = {1:"One", 2:"Two", 3:"Three"}
b = new(a)
def ex():
n = 3
yield n
n = n * n
yield n
v = ex()
for x in v:
print (x)
... |
"""
At the county fair there is a contest to guess how many jelly beans are in a jar. Each entrant is allowed to submit a
single guess, and cash prizes are awarded to the entrant(s) who come closest without going over. In the event that there
are fewer guesses less than or equal to the answer than the number of prize... |
"""
A group of n people played a game in which the loser must double the money of the rest of the players. The game has been played n
times, and each player has lost exactly once. Surprisingly, each player ended up with the same amount of money of m dollars.
Considering all that, find the amount of money each player ... |
"""
You guys should probably know the simple y = sin(x) equation.
Given a range of x [start, end], your mission is to calculate the total signed area of the region in the xy-plane that
is bounded by the sin(x) plot, the x-axis and the vertical lines x = start and x = end. The area above the x-asix should
be added to... |
"""
As a high school student, you naturally have a favourite professor. And, even more natural, you have a least favourite
one: professor X!
Having heard that you're an experienced CodeFighter, he became jealous and gave you an extra task as a homework. Given a
sentence, you're supposed to find out if it's a palindr... |
"""
You would like to create your own little farm. Since you're not an expert (yet!), you bought seeds of just two types of plants:
flowers and florets. Each pack of seeds was provided with the instructions, explaining when the plant can be planted.
In the instructions two dates are given, to and from, which denote t... |
"""
Numbers x and y (x ≠ y) are called friendly if the sum of proper divisors of x is equal to y, and the other way round.
Given two integers x and y, your task is to check whether they are friendly or not.
Example
For x = 220 and y = 284, the output should be
friendly_numbers(x, y) = "Yes".
The proper divisors of ... |
"""
My kids very fond of winter breaks, and are curious about the length of their holidays including all the weekends.
Each year the last day of study is usually December 22nd, and the first school day is January 2nd (which means that
the break lasts from December 23rd to January 1st). With additional weekends at the... |
import sys
import requests
import json
from today import today
from hourbyhour import hourbyhour
from monthly import monthly
def the_weather():
arguments = sys.argv
if len(arguments) == 2:
place = arguments[1]
type_of_forecast = 'today'
elif len(arguments) == 3:
place = arguments[... |
"""Documentation strings, or docstrings, are standard ways of documenting modules, functions, methods, and classes"""
from collections import Counter
def words_occur():
"""words_occur() - count the occurrences of words in a file."""
file_name = input("Enter the name of the file: ")
... |
import doctest
def most_repeating_word(words: list) -> str:
"""
Write a function, most_repeating_word, that takes a sequence of strings as input. The function should return the string that contains the greatest number of repeated letters. In other words:
for each word, find the letter that appears the mo... |
name = "Amaury Zapien"
age = 35
height = 74
weight = 180
eyes = 'Blue'
teeth = 'white'
hair = 'brown'
print(f"let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got{eyes} eyes and {hair} hair.")
... |
n=6
i=0
for i in range(n):
i+=1
if i==3:
continue
print(i)
|
import random
cont = True
print("H A N G M A N")
s = input('Type "play" to play the game, "exit" to quit:')
while s == "play":
print()
lives = 8
words = ['python', 'java', 'kotlin', 'javascript']
current_word = random.choice(words)
current_word_cipher = ""
for i in range(len(current_word)):
... |
import heapq
class MaxStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.heap = []
self.popped_item = []
self.id_count = 0
def clear_stack(self):
while self.stack and self.stack[-1] in self.po... |
import collections
class Solution(object):
def findLeaves(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
self.res = collections.defaultdict(list)
def dfs(node):
if not node:
return 0
l = dfs(node.le... |
import collections
def distanceK(self, root, target, K):
adj, res, visited = collections.defaultdict(list), [], set()
def dfs(node):
if node.left:
adj[node].append(node.left)
adj[node.left].append(node)
dfs(node.left)
if node.right:
adj[n... |
def delNodes(self, root, to_delete):
"""
:type root: TreeNode
:type to_delete: List[int]
:rtype: List[TreeNode]
"""
des = set(to_delete)
self.res = []
def find(node):
if not node:
return None
if node.val in des:
self.res.append(node.left... |
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
arr = []
self.inorder(root, arr)
for i in range(len(arr) - 1):
if arr[i] >= arr[i + 1]:
return False
return True
d... |
import collections
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.res = []
def bfs(node):
if not node:
return
q = collections.deque()
q.append((... |
class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 1000
self.buckets = [([], []) for _ in range(self.size)]
def get_hash_code(self, key):
return key % self.size
def get_bucket(self, key):
h... |
import collections
class Solution(object):
def findLeaves(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
def dfs(root):
if not root:
return -1
height = max(dfs(root.left), dfs(root.right)) ... |
def login():
username_vault = ["john", ]
password_vault = ["smith", ]
choose = input(
"Do you want to create a account or login? Type login for logging in or type create for creating an account: ")
choose.lower()
six = 6
if choose == "create":
Create()
elif choose == "login":... |
khana = ["roti","sabzi","chawal"]
for item in khana:
if item == "roti":
print(item)
break
else:
print("Your item is not found") |
list_value=input("enter a list with spaces between numbers.")
list_value=list_value.split(" ")
for i in range(len(list_value)):
list_value[i] = int(list_value[i])
print(list_value)
print(type(list_value[1]))
list_value.reverse()
print(list_value)
list_value.reverse()
print(list_value[::-1])
len=len(list_v... |
def adddata(name):
whattoadd = input("diet or exercise")
details = input("what you what to add")
f = open(name + whattoadd + ".txt", "a")
f.write(details)
f.close()
def retrievedata(name):
whattoretrieve = input("diet or exercise")
f = open(name + whattoretrieve + ".txt")
p... |
c = sum((5,7))
print(c)
def function1(a,b):
"""this is a doc which we can print using doc whic i will show you . So we should write here about the role of the function so that we can see it using the the doc function."""
print("thsi is a nice function.")
print(function1.__doc__)
num1 = input()
num2 = inp... |
lis = ["1","2","5","3","4"]
num = list(map(int,lis))
print(num,type(num),lis)
def sq (a):
return a*a
square = list(map(sq,num))
print(square)
sqr = list(map(lambda x: x*x,num))
print(sqr)
def sqr1(a):
return a*a
def cube(a):
return a*a*a
func = [sqr1,cube]
for i in range(5):
val = list(ma... |
import openpyxl
wb=openpyxl.load_workbook('produceSales.xlsx')
sheet = wb.get_sheet_by_name('Sheet')
PU = {'Garlic':3.07,
'Celery': 1.19,
'Lemon':1.27}
condition = "y"
while condition == "y":
produce = input("item whose price is increased")
for keys,values in PU.items():
if keys ... |
class A:
classvar1= "I am a class variable in class A."
def __init__(self):
self.var1 = "I am in class A's constructor."
self.classvar1 = "Instance variable of class A"
self.special = "Special"
class B(A):
classvar1="I am in class B"
classvar2 = "I am variable of class ... |
def greet_users(names):
for name in names:
print ("hello : " + name)
usernames = ["yang","li","he"]
greet_users(usernames)
unprinted_designs = ["iphone_case","robot_pendant","yyy"]
completed_models = []
def print_mode(unprinted_designs):
while unprinted_designs:
current_design = unprinte... |
import time
def display_time(func):
def wrapper(*args):
t1 = time.time()
result = func(*args)
t2 = time.time()
print("Total time: {:4}s".format(t2-t1))
return result
return wrapper
def is_prime(num):
if(num <2):
return False
elif num ... |
from getpass import getpass
import random,hashlib,sys
def getphrase():
passphrase = getpass("Passphrase:")
if len(passphrase) < 16:
print("Passphrase too short, enter at least 16 characters.")
exit()
hashphrase = hashlib.sha512(passphrase.encode('utf-8')).hexdigest()
... |
def func1(x):
while True:
print(x)
x=x-1
if x == 0:
break
func(5)
|
x = 10
y = 20
resulte = x < y
print (resulte) |
""" Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a li... |
import pandas as pd
import re
def main():
data = pd.read_csv("../data/NYPL-menus.csv")
'''Select a subset of the data for cleaning with Python'''
subset = data[['event', 'venue', 'place', 'date']]
'''Destructure DataFrame to return individual column Series to pass to functi... |
import random
count_draws = 0
count_loses = 0
count_wins = 0
TYPE_LIST = ('rock', 'scissors', 'paper')
def inp():
global n
while True:
try:
n = int(input('Enter an amount of games n '))
return n
except ValueError:
print("It's not a number!... |
"""
Author: Qixiang Liu
Description: depth-first search
Date: 03/14/2019
Log: depth-first search is recursion;
"""
import os
import sys
if len(sys.argv) != 2:
print ("python3 <EXE><Input.txt>")
exit(1)
filename = sys.argv[1]
inFile = open(filename)
head = inFile.readline();
head = int(head.strip());
se... |
print('Welcome to Aryanshu Quiz')
answer=input('Are you ready to play the Quiz ? (yes/no) :')
score=0
total_questions=3
if answer.lower()=='yes':
answer=input('Question 1: what is the easiest programming language?')
if answer.lower()=='python':
score += 1
print('correct')
else:
pr... |
from abc import abstractmethod, ABCMeta
class Organism(metaclass=ABCMeta):
def __init__(self, tile, world):
self.tile = tile
self.world = world
self.isDead = False
def kill(self):
self.isDead = True
@property
def strength(self):
return self.__strength
@s... |
from Organisms.Animals.Animal import Animal
import random
class Antilope(Animal):
def __init__(self, tile, world):
super().__init__(tile, world)
self.strength = 4
self.initiative = 4
def draw(self):
return "#875409"
def action(self):
moves = set()
moves.u... |
"""
Exercise: happy
Finger Exercises due Aug 5, 2020 20:30 -03
Completed
Bookmark this page
Exercise: happy
5.0/5.0 points (graded)
ESTIMATED TIME TO COMPLETE: 3 minutes
Write a piece of Python code that prints out the string 'hello world' if the
value of an integer variable, happy, is strictly greater than 2.
Do no... |
"""
Exercise: for
Finger Exercises due Aug 5, 2020 20:30 -03
Completed
Bookmark this page
Exercise: for exercise 1
5.0/5.0 points (graded)
ESTIMATED TIME TO COMPLETE: 5 minutes
In this problem you'll be given a chance to practice writing some for loops.
1. Convert the following code into code that uses a for loop.
... |
"""
Exercise 4
Finger Exercises due Aug 5, 2020 20:30 -03
Completed
Bookmark this page
Exercise 4
5/5 points (graded)
ESTIMATED TIME TO COMPLETE: 8 minutes
Below are some short Python programs. For each program, answer the associated
question.
Try to answer the questions without running the code. Check your answers,... |
import pila
class Almacen:
def __init__(self, peliculas):
self.peliculas= peliculas
def buscar_peliculas_por_genero(self,busqueda):
if self.peliculas.es_vacia():
print ("No hay mas peliculas para mostrar.")
print ("______________________________________... |
import numpy as np
def mm2cm(v):
"""
Converts value from mm to cm
Parameters
----------
v: value
input value, mm
returns:
value in cm
"""
if np.isnan(v):
raise ValueError("mm2cm", "Not a number")
return v * 0.1
... |
def swap(A,p,q):
tmp = A[p]
A[p] = A[q]
A[q] = tmp
def cariPosisiYangTerkecil(A, dariSini, sampaiSini):
posisiYangTerkecil = dariSini
for i in range(dariSini+1, sampaiSini):
if A[i] < A[posisiYangTerkecil]:
posisiYangTerkecil = i
ret... |
classroom = [
[None, "Pumpkin", None, None],
["Socks", None, "Mimi", None],
["Gismo", "Shadow", None, None],
["Smokey","Toast","Pacha","Mau"]
]
row_index = 0
seat_index = 0
for row_index, row in enumerate(classroom):
for seat_index, seat in enumerate(row):
if seat == None:
print("Row {... |
s1={1,2,3,4}
s0={"a","b","c"}
s2={True,False}
s3=set((1,2,3,4))
print(1 in s3)
print(s1)
s4={1,2,3,4,5,5,3,2,1,3,5}
print(s4)
print(len(s4))
print(type(s4))
for i in s4:
print(i)
s4.add(10)
print(s4)
s4.update(s3)
print(s4)
s4.update(tuple((1,2,4,6,8,9... |
Normal_num=4
Float=4.89988
Complex=5j
x=4
y=6
z=5
print(x+y)
print(x*y)
print(x**y)
print(x/y)
print(x//y)
print(x%y)
x+=1
print(x)
x%=2
print(x)
print(10000)
print(2.44)
print(5j)
print(float("nan"))
print(float... |
a = 20
print(not a < 20)
print(a < 30 and a !=30)
b = a > 1
print(bool(10), bool(0))
print(bool(3.14), bool(0.))
print(bool('hello'), bool(''))
print(bool([0,1]), bool([]))
print(bool((0,1)), bool(()))
print(bool({'k1':'v1', 'k2':'v2', 'k3':'v3'}), bool({}))
print(bool(None))
t = True or bool('logical')
print(t)
... |
Phi = 3.14
r = float(input("Masukkan nilai jari-jari: "))
keling = 2*Phi*r
print("Jadi nilai keliling: " + str(keling))
|
import random
num = random.randrange(10)
Guesses = 5
for i in range(1, Guesses+1):
guess = int(input("Enter your guess:"))
if(guess == num):
print("Your guess is correct!")
break
elif(guess > num and i < Guesses):
print("You are close, keep trying lower")
elif... |
class Sequence:
"""
A simple class for a sequence (protein or DNA) from a FASTA file
"""
def __init__(self, name, sequence='', header=''):
self.name = name
self.header = header
self.sequence = sequence
def __repr__(self):
return self.name
|
import pygame
import random
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
bg = pygame.image.load("gwcpic3.png")
pygame.display.set_caption("Snow")
color = WHITE
class SnowFlake:
... |
"""
Part 5:
Run-through of exploratory data analysis, evaluation, comments, and conclusions printed to the output.
Please follow through with the output.
Dataset: https://www.kaggle.com/jeevannagaraj/indian-liver-patient-dataset
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from ... |
""" This program will create the substring of the string and check the substring or not. if the substring is a
palindrome then it will print the substring if anyone of the substring is not a palindrome it will print invalid
input. """
def pal(st):
if st == st[::-1]:
return 1
def l(s):
l1 ... |
import random
turns = 32
num_ships = 7
size = 8
admitted_input = [str(x) for x in range(size + 1)]
nl = '\n'
def create_sea(board):
"""
This function prints the board for the user to see.
Aswell as printing out numbers for each row and column.
"""
print(' 1 2 3 4 5 6 7 8')
print(' -... |
"""
Encapsulation = Abstraction + data hiding
encapsulation means we are only going to show required part and rest will keep as private
"""
class Data:
__speed = 0
__name = ''
def __init__(self):
self.a = 123
self._b = 456
self.__c = 789
self.__updates... |
from datetime import datetime
log = "log_file.txt"
"""
when we use "with open" then we don't need to explicitly close open file , it will be atomically taken care
"""
def read_log(log):
with open(log, "r") as f:
print(f.read())
def write_log(log, data):
with open(log, "a") as f:
... |
import csv
raw_csv = open('text.csv').read()
print(raw_csv)
exp_csv = open('text.csv')
data_read = csv.reader(exp_csv)
for data in data_read:
print('{} is in {} with ip : {}'.format(data[0], data[2], data[1]))
|
import math
import os
import random
import re
import sys
def staircase(MySteps):
air_fill = ' '
for step in range(MySteps):
step_len = step + 1
wood_step = step_len * '#'
whole_step = wood_step.rjust(MySteps, air_fill)
print(whole_step)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.