text stringlengths 37 1.41M |
|---|
from turtle import*
import time
from random import randint
Nom = input("\nEntrez votre nom : ").upper()
if len(Nom) > 1:
Nom = Nom[0] + Nom[1:].lower()
print("\nNiveau de difficulté possible :\n")
print("Facile")
print("Moyen")
print("Difficile")
print("Impossible")
print("")
Level = inp... |
import structs.cell
class Sudoku(object):
def __init__(self, puzzle, board_size=9, square_size=3):
'''
constructor for sudoku puzzle
- assumes a 9x9 puzzle unless otherwise stated
- tracks board size and square size (should solve puzzles of varying sizes)
- saves... |
"""
utility functions to determine if a command is a tip or not.
"""
import re
is_tip_regex = re.compile("^tip *\$?(?:0|[1-9]\d{0,2}(?:,?\d{3})*)(?:\.\d+)?$")
amount_regex = re.compile("-?(?:0|[1-9]\d{0,2}(?:,?\d{3})*)(?:\.\d+)?$")
def is_tip(user_response):
if re.match(is_tip_regex, user_response) is not None:... |
""""
Bubble Sort is the simplest sorting algorithm that works
by repeatedly swapping the adjacent elements if they are in wrong order.
"""
# Python program for implementation of Bubble Sort
def bubbleSort(input_list):
list_length = len(input_list)
# initial index of all elements in the given list
for i i... |
#Class Utama
class merek:
def __init__(self, A, B, C, D):
self.A = A
self.B = B
self.C = C
self.D = D
def Daftar_merek(self):
print ("Daftar_merek : ", self.A, self.B, self.C, self.D)
#Subclass 1
class yamaha (merek):
def __init__(self, A, B, C, D ):
merek.__... |
#Tehdään liikkuva pelaaja
import pygame
pygame.init()
displayWidth = 750
displayHeight = 500
title = "Player Movement"
screen = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption(title)
class Player:
def __init__(self, posX, posY):
self.posX = posX
... |
cantantes = ['Freddy Mercuri' , 'Gustavo Cerati' , 'Michael Jackson' , 'Steven Tyler']
numeros = [1, 2, 5, 8, 3, 4]
#Ordenar una lista
#print(numeros)
#numeros.sort()
#print(numeros)
#Agregar Elementos a una lista
#cantantes.append('Bon Jovi')
#cantantes.insert(1, 'Sting')
#print(cantantes)
#Eliminar Elementos
#c... |
"""
Hacer una lista con 8 enteros
Recorrerla y mostrar
(harcerla en una funcion)
Ordenarla y mostrarla
Longitud
Mostrar un elemento que se pida
"""
numeros = [2, 4, 6, 8, 1, 3, 5, 7]
#Recorrer y mostrar
"""
print("------------ Recorrer y mostrar ------------")
for numero in numeros:
print... |
from tkinter import *
from tkinter import messagebox as MessageBox
ventana = Tk()
ventana.config(bd=100)
def sacarAlerta():
#MessageBox.showinfo("Alerta", "deja de darle ahí")
#MessageBox.showerror("Alerta", "deja de darle ahí")
MessageBox.showwarning("Alerta", "deja de darle ahí")
Button(ventana, text="... |
"""
sacar porcentaje de un número
"""
numero = int(input("Ingrese el número al cual le desea sacar un porcentaje "))
porcentaje = int(input("¿Qué valor porcentual le quiere sacar al primer valor? "))
operacion = ((numero/100)*porcentaje)
print(f"el {porcentaje}% de {numero} es {operacion}") |
"""
hacer un programa que pida numeros al usuario indefinidamente hasta que ingrese el 111
"""
contador = 1
while contador < 100:
numero = int(input("Ingresa un numero e intenta adivinar el número secreto "))
if numero == 111:
print("¡¡¡Adivinaste!!!")
break
else:
print("Sigue i... |
string1 = "he's "
string2 = "thinking "
string3 = "about"
string4 = "something"
string5 = "stupid"
print(string1, string2, string3, string4, string5)
# Strings can also be multiplied
print("^_^ " * 5) # ^_^ ^_^ ^_^ ^_^ ^_^
print("Hello " * (5 + 2)) # Hello Hello Hello Hello Hello Hello Hello
print("Hello " * 5 + "2... |
# Strings are sequence type so you can index through each character
# [ ] used for indexing
parrot = "Norwegian Blue"
print(parrot) # Norwegian Blue
print(parrot[3]) # w bc index starts at 0
# Add code to program to print out we win
# Each char on new line and get from string using indexing
print(parrot[4])
print(par... |
import tkinter
class GUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.top_frame = tkinter.Frame(self.main_window)
self.top_frame.pack(side = "top")
self.bottom_frame = tkinter.Frame(self.main_window)
self.bottom_frame.pack(side = "bottom")
self.la... |
def histogram(lst):
for i in lst:
output=''
k=i
while (k>0):
output += '*'
k=k-1
print(output)
lst=[4,6,2,10.,16,20]
histogram(lst) |
def symm(set1,set2):
s_diff=set1^set2
symmDif1 = set1.symmetric_difference(set2)
print(s_diff)
print(symmDif1)
set1={'a','e','i','o','u',1,2,3,4,5,6,7,8,9,0,'1'}
set2={'i','1','u',4,3,1,'h','b','v','z'}
symm(set1,set2) |
# program to count the number occurrence of a specific character in a string
try:
str="Basic Python"
print("count of i : ",str.count('i'))
except:
print("The character not present in the string")
|
x=int(input("Enter the first integer: "))
y=int(input("Enter the second integer: "))
z=int(input("Enter the third integer: "))
a1=min(x,y,z)
a3=max(x,y,z)
a2=(x+y+z) - a1 - a3
print("number in sorted order is : ", a1,a2,a3)
|
def occ(elements):
for i in range(len(elements)-1):
print(elements[i],"count is: ",elements.count(elements[i]))
elements=[1,1,2,3,4,4,4,5,6,6,6,6,7,4,8,9]
occ(elements)
|
def cloning(lst):
lst1_copy=[i for i in lst]
return lst1_copy
lst=[4,8,2,6,8,9,10]
lst1=cloning(lst)
print("The original list is: ",lst)
print("After cloning the list: ",lst1)
cloning(lst) |
dict1={1:"Telangana",2:"Maharastra",3:"Gujrat",4:"Rajasthan",5:"Madhya Pradesh"}
del dict1[5]
print("The dictonary after removinga key is: ",dict1)
|
# program to print a dictionary in table format.
my_lst={"Name":["Jagadish","Santosh","Haneef"], "Salary":["30K","40K","50K"]}
for row in zip(*([key] + (value) for key, value in sorted(my_lst.items()))):
print(*row)
|
try:
color_list=["Red","Green","White","Black"]
color1=color_list[:1]
color2=color_list[-1:]
print("The first and last colors are: ",color1,color2)
except:
print("No color") |
def rev(str):
str1=str[: :-1]
print(str1)
str="India"
rev(str) |
'''
Question:
Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string in upper case.
'''
import sys
class String:
def __init__(self, str=""):
self.str = str
def getString(self):
# i = 0
# for s in sys.argv:
# if i != 0:
# self.str... |
def greeting(name):
return f"Hello, {name}"
def is_positive(num):
return num > 0
def is_even(num):
return num % 2 == 0
class MyClass:
def __init__(self, val):
self.__val = val
obj = MyClass(10)
print(obj.__val)
|
'''
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the ... |
# Immutable
t1 = ('apple', 'banana', 'grapes', 'pineapple', 3, 78, 8.12)
print(t1[::-1])
t2 = (10,)
print(type(t1))
print(type(t2))
print(len(t1))
print(t1 + t2)
print('banana' in t1)
# Unpacking/destructing of tuple
a, b, c = (10, 20, 30)
print(a)
print(b)
print(c)
a, *b, c = (10, 20, 30, 40, 50, 60)
print(a, b,... |
# Prime numbers are divisible by 1 and itself
# Ourtest would be to check whether a number is divisible by 2 to n-1, for n
def is_prime(n):
if n % 2 == 0 and n != 2:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
print(is_prime(33))
|
from Board import Board
class MergingQueue(object):
def __init__(self):
self.buffer = []
def Append(self, x):
if 0 == x:
return
self.buffer.append(x)
def Merging(self):
self.FillZero(self.buffer,5)
result=[]
while len(self.buffer) >= 2:
... |
import unittest
from casino.roulette.bet import Bet
from casino.roulette.outcome import Outcome
from casino.roulette.table import InvalidBet
from casino.roulette.table import Table
class TableTest(unittest.TestCase):
"""Test the implementation of the class Table."""
def setUp(self):
self.table = Tab... |
import string
import itertools
# print(string.ascii_lowercase.index('z')) -------------> this is to check the position of the alphabet
S = "anwiuu"
K = 3
sub = []
combs = []
combs = []
for l in range(1, len(S)+1):
combs.append(list(itertools.combinations(S, l)))
for c in combs:
for t in c:
print(com... |
#The number guess game
import random
guessTaken=0
points=0
chance=0
totalpoints=0
guesses=10
i=0
print('.....................................................................APPROXIMATE TO THE BEST................................................................')
print('Hello!What is your name?')
name=in... |
'''
Coded by: Harley Ehrman
Date: June 9, 2018
From book:
Introduction to Programming Using Python
By Y Daniel Liang
Instructions (Page 61, Exercise 2.24):
(Turtle: draw four hexagons) Write a program that draws four hexagons in the
center of the screen, as shown in Figure 2.4b
'''
import turtle
turtle.penup()
turtl... |
'''
Coded by: Harley Ehrman
Date: June 9, 2018
From book:
Introduction to Programming Using Python
By Y Daniel Liang
Instructions (Page 59, Exercise 2.17):
(Health application: compute BMI) Body mass index (BMI) is a measure of health
based on weight. It can be calculated by taking your weight in kilograms and
dividi... |
print(" ")
print('"Python Program To Compute The Distance Between The Points (x1, y1) and (x2, y2)"')
print(" ")
val1 = float(input("Enter Point(x1): "))
print(" ")
val2 = float(input("Enter Point(y1): "))
print(" ")
val3 = float(input("Enter Point(x2): "))
print(" ")
val4 = float(input("Enter Point(y2... |
# NUMBER GUESS:-
import random
x=random.randint(1,9)
turn=0
while turn<4:
num =int(input("Enter your number"))
if num==x:
print("Congrats! You have guessed the right number.",x)
break
elif num>x:
if num-x>6:
print("Hint: You are very far... |
class Stack:
def __init__(self, SizeOfField):
self.SizeOfField = int(SizeOfField)
self.Top = -1
self.Field = [self.SizeOfField]
def pop(self):
if not self.isEmpty():
self.Top -= 1
print(self.Field[self.Top + 1])
self.Field.pop(self.Top + 1)
... |
import sqlite3 as sql
import csv
def categorize_data(first_row):
print("We need to understand what kind of data is in each column to cluster correctly.")
print("(I)d - This column has an id in it, don't consider it when clustering")
print("(S)pecimine - This column contains specimine data, do consider it w... |
#
# This is a continuation of our math game from lesson 02. This time, we're going to use what
# we've learned about functions to add in support for letting the user choose what game they
# want to play (addition, subtraction, multiplication, division). We'll also let the user
# choose the maximum_number in addition ... |
#Link: https://replit.com/@appbrewery/day-1-2-exercise
print('Day 1 - String Manipulation\nString Concatenation is done with the ' + '"+" sign.\n'+'e.g. print("Hello " + "world")\n'+"New lines can be created with a backslash and n.")
|
# Dividir para Conquistar
# Recursão
# Padrão
def somaPadrao(lista):
total = 0
for x in lista:
total += x
return total
# Recursiva
# exercicio 4.1 pag 77
def somaRecursiva(lista):
if len(lista) == 1:
return lista.pop()
soma = lista.pop()
return soma + somaRecursiva(lista)
print(somaRecursiva([1,2,3,4])) |
# Python program to
# demonstrate implementation of
# queue using queue module
from queue import Queue
from qjetdatabase import *
database = r"C:\Users\Deadsec\Desktop\QJet\Qjet\qjetdatabase.db"
connection = CreateConnection(database)
c = connection.cursor()
c.execute("SELECT Firstname FROM Member")
data = c.fet... |
from lab1.algorithm_analysis import AlgoAnalysis
from lab1.csv_reader import read_csv_file
from lab1.algorithms.heap_sort import heap_sort
from lab1.algorithms.insertion_sort import insertion_sort
if __name__ == '__main__':
file = input("Enter name of csv file in format \"pumps.csv\": ")
water_pumps = read_cs... |
import unittest
def find_min_speed_per_hour(piles, hours):
"""
Finding minimum speed at which the gorilla can eat all bananas for n hours
:param piles: list of piles with bananas
:param hours: the time it takes for a gorilla to eat bananas
:return: the minimum speed at which the gorilla can eat al... |
#!/usr/bin/env python
# Author: Rujie Jiang jrjbear@gmail.com
# Date: Fri Apr 8 00:41:50 2016
"""A simulation of animals' words
"""
class Animal:
def speak(self): print("What do animal speak?!")
def reply(self): self.speak()
class Mammal(Animal):
def speak(self): print("What do mammal speak?!")
class C... |
#!/usr/bin/env python
# Author: Rujie Jiang jrjbear@gmail.com
# Date: Sat Apr 2 20:45:16 2016
"""Functions return the sum of all the arguments
"""
from functools import reduce
import operator
def list_adder(*args):
return reduce(operator.add, args)
print("list_adder(1, 2, 3) =", list_adder(1, 2, 3))
print("lis... |
import unittest
import turtle
from Maze import Maze
class MazeTests(unittest.TestCase):
def setUp(self):
self.m = Maze()
def test_maze(self):
self.assertTrue(type(self.m.screen) == turtle._Screen, "No Screen! type is " + str(type(self.m.screen)))
def test_turtle(self):
t = self.m.g... |
#encoding:utf-8
import nltk
def plural(word):
if word.endswith('y'):
return word[:-1] + 'ies'
elif word[-1] in 'sx' or word[-2:] in ['sh', 'ch']:
return word + 'es'
elif word.endswith('an'):
return word[:-2] + 'en'
else:
return word + 's'
# w_1 = plural('man')
# w_2... |
"""
Utilities
"""
from decimal import Decimal
from fractions import Fraction
from numbers import Number
from typing import Any, Optional, Iterable
from math import modf
def _parse_value(value: Any) -> Fraction:
"""
Ensures that the given value has the type Fraction.
"""
if isinstance(value, Decimal)... |
"""
AttemptListQuery
"""
from typing import Optional
class AttemptListQuery(object):
"""
An AttemptListQuery summarizes parameters that can be used to search for an TransactionAttemptList.
"""
def __init__(self,
trigger_tx: Optional[str] = None,
trigger_currency: Op... |
"""
PollingState
"""
from typing import Dict
class PollingTransactionState(object):
"""
Stores information about a processed transaction.
"""
DICT_TRIES_KEY = 'tries'
DICT_OK_KEY = 'ok'
def __init__(self, ok: bool = False, tries: int = 0) -> None:
self._ok = ok
self._tries =... |
"""
WalletStorage
"""
from abc import ABC, abstractmethod
from typing import Optional
from waves_gateway.model import KeyPair
from waves_gateway.common import DuplicateSecretError
class WalletStorage(ABC):
"""
Storage for private keys.
"""
@abstractmethod
def get_secret_by_public_address(self, ... |
"""Module for utility functions contained by multiple components of medspaCy."""
import re
def span_contains(span, target, regex=True, case_insensitive=True):
"""Return True if a Span object contains a target phrase.
Case insensitive.
span: A spaCy Span, such as an entity in doc.ents
target: A target p... |
lista = [10, 15, 34, 33, 76, 150, 50, 10]
for numero in lista:
if numero >= 150:
break
if numero%5 == 0:
print(numero) |
import random
class Unit:
def __init__(self, id, team):
self.id = id
self.team = team
class Hero(Unit):
lvl = 0
def lvl_up(self, lvl):
self.lvl += lvl
class Soldier(Unit):
def follow(self, hero):
print(f"Soldier with id: {self.id} follow to the {hero} hero")
... |
"""
This script can be used to download Youtube playlists.
It uses regex to find links of youtube videos in a playlist.
With the help of 'pytube' module, it downloads the videos one-by-one.
Currently, if a playlist has more than 100 videos, it will only download the first 100.
Made by :- Vikas Jethwani( StAn.Vj )
"""
i... |
#Name :Geetika Joshi
def modinv(a, m):
for x in range(1, m):
if (a * x) % m == 1:
return x
return None
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
p = int(input('Enter a prime number p = '))
q = int(input('Enter a prime number q = '))
m = int(input('Enter plain te... |
'''
5402. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
Given an array of integers nums and an integer limit, return the size of the longest continuous subarray such
that the absolute difference between any two elements is less than or equal to limit.
In case there is no subarray satisfyi... |
'''
540. Single Element in a Sorted Array
You are given a sorted array consisting of only integers where every element
appears exactly twice, except for one element which appears exactly once.
Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: [3... |
#Diffie Hellman
#Edson Lemes da Silva
#Disciplina de Segurança
import sys
#Exponenciação modular
def expMod(base,key,mod):
exp = base%mod
resp = 1
while key > 0:
if(key%2==1):
resp = int((resp*exp)%mod)
exp = int((exp*exp)%mod)
key = int(key/2)
return resp
base = 5
prime = "E53DF5FC3F650D0668758... |
from unittest import TestCase, mock
from section1.fraction import Fraction, FractionException
class FractionTests(TestCase):
def setUp(self):
self.fraction = Fraction(1, 2)
def test___str__(self):
self.assertEqual(str(self.fraction), "1 / 2")
def test___repr__(self):
self.assertE... |
def prediction(self,car_full_data,integer_data):
## Training and predicting the target for the specification provided by the customer and decision based on the inputs provided##
(buying, maint, doors, persons, lug_boot, safety) = self.input_(car_full_data) ##Getting the car specifications from input functio... |
favorite_numbers = {
'florient': 13,
'elodie': 3,
'seb': 42,
'faerie': 27,
'sedokun': 66,
}
number = favorite_numbers['elodie']
print(f"Elodie's favorite number is {number}")
|
guests = ['Einstein', 'Newton', 'Hawking']
message = f"Hello {guests[0]}, would you like to have a dinner?"
print(message)
message = f"Hello {guests[1]}, would you like to have a dinner?"
print(message)
message = f"Hello {guests[2]}, would you like to have a dinner?"
print(message)
print(f"\nUnfortunately, {guests[1]} ... |
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
peoples = ['edward', 'seb', 'florient', 'sarah']
for people in peoples:
if people not in favorite_languages.keys():
print(f"{people.title()}, please take our poll")
else:
print(f"{people... |
## Guessing Game
max = 101
min = 0
print("Think of a number between 1 and 100")
middle = int((max + min)/2)
answer = input("Is your number [H]igher, [L]ower or the [S]ame as {}".format(middle)).upper()
if answer == "H":
min = middle
elif answer == "L":
max = middle
else:
print("Your number is {... |
""" Merge sort example"""
from timeit import timeit
from random import randint
# Generate random list
list_to_sort = [randint(0, 1000) for i in range(1000)]
############################################################################################
def merge(list_a, list_b):
list_c = []
while l... |
#!/usr/bin/env python
def findPivot(myList, low, high):
mid = int((low + high)/2)
if ((mid < high) and (myList[mid] > myList[mid+1])):
return mid
if ((mid > low) and (myList[mid] < myList[mid+1])):
return mid-1
if myList[low] >= myList[mid]:
return findPivot(myList, low, mid-1)... |
print("Welcome To Fast Food Zone")
menu = {"California BBQ Chicken Pizza":1136,"Burger King 8 Piece Chicken Tenders":360,
"McDonald’s Premium Grilled Chicken Classic":520,"Starbuck’s Old-fashioned Glazed Donut":480,
"Dunkin Donuts Coolatta with Skim Milk (16 oz)":210,"Burger King Sausage, Egg, and Ch... |
#Joe Gutierrez - 2/1/18 - Chapter 8 - Exercise 1
#Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None.
#Then write a function called middle that takes a list and returns a new list that contains all but the first and last elements.
a = ['a', 'b... |
import math
number = float(input())
firstUnit = input()
secondUnit = input()
if firstUnit == "mm" and secondUnit == "m":
print(F"{(number / 1000):.3f}")
elif firstUnit == "mm" and secondUnit == "cm":
print(F"{(number / 10):.3f}")
elif firstUnit == "cm" and secondUnit == "m":
print(F"{(number / 100):.3f}")... |
sideA = int(input())
sideB = int(input())
sideC = int(input())
occupied = float(input())
volumeAquarium = (sideA * sideB * sideC) * 0.001
occupiedPercent = occupied * 0.01
needWater = volumeAquarium * (1 - occupiedPercent)
print(needWater) |
print("Abhinav Vasu")
# Precedence is PEMDAS
a = 10 / 3
b = 10 // 3
c = 5 / 2
d = 2**2
print("a is equal to", a)
print("b is equal to", b)
print("c is equal to", c)
print("d is equal to", d)
# Logical operators are used to combine conditional statements
x = 5
print(x > 3 and x < 10)
print(x > 3 or x < ... |
def my_square(x):
'''
this is sample method that we are editing in GIT Hub and we are going to check in the local git
i am adding the line in git hub before pushing file from local to Git
hub.
this fucntion is calculating squares using operator **
'''
return(x**2)
def add(x,y):
'''
Adding... |
#To get the input for the user
val = input("Enter a word : ");
#To print the user input for reference
print("You have just entered:",val);
#Deleting the last two charachters from the given word
#val = val[:-2] for removing last charachtesrs
val = val[2:]
#Printing the word ater deletion two for characters
pri... |
# function which return reverse of a string
s = input("Enter a word : ");
s=s.casefold()
har = s[::-1]
if(s==har):
print("yes, it is a palindrome")
else:
print("no, it is not a palindrome")
|
arr=[3, 0, 1, 0, 5, 9, 0, 6, 7]
for i in range(1,len(arr)):
if(arr[i]!=0):
j=0
while(arr[j]!=0):
j=j+1
arr[j]=arr[i]
arr[i]=0
print(arr) |
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#Two pointers (same direction to the right)
#move 0 to the end of the array, means set all non-zeros values to the head of the array, and fill... |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
#given the majority element are more than half of the array, that means if we sort the array and return the middle one, it will be the majority element
nums.sort()
return nums[len(nums)//2] |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
'''
def mergTwo(l1, l2):
if None i... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
de... |
# you need to replace a section of a string with new comments.
str1 = "Here are a string"
# replaces 5 - 8 with "is"
corrected_str1 = str1[:5] + "is" + str1[8:]
print corrected_str1
|
# -*- coding: utf-8 -*-
from sys import argv
script, first, second, third = argv
print "What kind of animal are you?"
animal = raw_input()
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
print "You are a %s"... |
class UI:
def __init__(self,game_manager):
self.__game_manager=game_manager
def print_board(self):
board=self.__game_manager.get_game_board()
for i in range(8):
for j in range(8):
print(board[i][j],end=' ')
print()
def player_move(self):
... |
from entities import *
import copy
def print_list(list):
for element in get_value(list):
print(get_value(element))
def initialise(expenses_list):
'''
Initialises expenses_list with 10 initial values
'''
initial_values=[['add',100,'food'],['add',400,'taxes'],['add',50,'... |
def is_leap(year):
if year%4==0 and year%100==0:
return False
elif year%4==0 and year%100!=0:
return True
def determine_month(year,day):
number_of_days=31
number_of_month=1
while day-number_of_days > 0:
months=(4,6,9,11)
day-=number_of_days
number_of_month+=1... |
'''
Module for building a map and some practical functions!
'''
from math import radians, cos, sin, asin, sqrt
import csv
import folium
def haversine_distance(lng1, lat1, lng2, lat2) -> float:
'''
Return the distance between two point on Earth with given longitudes and
latitudes.
>>> haversine_distance... |
def is_anagram(word1, word2):
word1 = word1.lower()
word2 = word2.lower()
return sorted(word1) == sorted(word2)
print(is_anagram('Iceman', 'Cinema'))
print(is_anagram('Ookinakuri', 'Kiokunairo'))
print(is_anagram('Abcc', 'Cabb')) |
# Client side
import socket
#创建客户端socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#服务端IP地址和端口号元组
server_address = ('127.0.0.1', 8888)
#客户端连接指定的IP地址和端口号
client_socket.connect(server_address)
while True:
#输入数据
data = input('please input:')
#客户端发送数据
client_socket.sendall(bytes(... |
balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
mi = 0
for i in range(1,13):
mini = balance * monthlyPaymentRate
mini = round(mini,2)
balance = round(balance,2)
balance = balance - mini + (annualInterestRate/12)*(balance - mini)
balance = round(balance, 2)
print "Month:... |
# Bryan Morris
# 9/19
# Math Lab - Triangles
#create and assign values to base and height
base = 10
height = 5
#calculate area
area = base*height*0.5
print(area)
areaType = type(area)
print(areaType)
|
#Zadanie 3: Age in Seconds - oblicz swój wiek w sekundach.
#Tu przydatne będzie zaimportowanie date z modułu datetime.
#Pewnym utrudnieniem (chyba) jest poproszenie, aby użytkownik wpisał date swoich urodzin.
import datetime
now=datetime.datetime.now()
print(now)
you=input("When did you birth? (In YYY-MM-DD)\n")
you_... |
### Write a function called partition. This function accepts a list and a callback function.
### You can assume returns True or False.
### The function should iterate over each element in the list and invoke the callback function
### at each iteration.
### If the result of a callback function is True, the element sho... |
### abs
### stands for absolute value. Returns the absolute value of a number.
### The argument may be an integer or a floating point number.
print(abs(-23))
# You can import math to turn everything to float first
import math
print(math.fabs(-4)) # returns 4.0
### Sum
### takes an iterable and an optional start.
#... |
# Let's pretend we're making an RPG.
# Define a base class "Character" with the following properties
# 1. name - string
# 2. hp - an intger for health
# 3. level - an integer for level
# Define a subclass NPC which inherits from Character and has additional instance method called speak
# which prints the speech they ... |
[40,32,73]
"hello"
range(1,10)
# The above are items that can be looped over.
# For loops are written like
#for item in iterable_object:
# do something with item
#print 1-7
for number in range(1,8):
print(number)
for letter in "coffee":
print(letter * 10) |
### String representation example ###
# The __repr__ method is one of several ways to provide a nicer string representation:
class Human:
def __init__(self, name="somebody"):
self.name = name
def __repr__(self):
return self.name
dude = Human()
print(dude)
colt = Human(name="Colt ... |
#A range is just a slice of a number line.
range(7) #gives you 0 to 6
range(1,8) #gives you 1 to 7 || two parameters
range(1,10,2) #give you odds from 1 to 10
r = range(10)
print(list(r))
print(r)
for num in range(0,100,5): #print 0-99 by 5
print(num)
x = 0
for num in range(10,21,2):
x += num
pr... |
### Nested Lists ###
# Why use nested lists?
# They are great for
# - Complex data structures - matricies
# - Game boards / mazes
# - Rows and Columns for visualization, tabulation, and grouping data
import random
nested_list = [[1,2,3], [4,5,6], [7,8,9]]
print(nested_list[0][1]) # 2 from 1st list, 1st index
## Prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.