text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
import random
import math
import time
import curses
import heapq
from libs import _Basic, _Fast, _Tank, _Mob, _Flying
from libs import _Pellet, _Aqua, _3, _4, _5
from libs import rounds
import pickle
import getopt
import sys
class Game:
def __init__(self, height, width, screen=None):
... |
# Python Classes Part 3
class Person:
def __init__(self, name, gender, hair, isActive, robotOwned):
self.name = name
self.gender = gender
self.hair = hair
self.isActive = isActive
self.robotOwned = robotOwned
def acting(self):
self.isActive = True
def reti... |
'''You are given with Principle amount($), Interest Rate(%) and Time (years) in that order. Find Simple Interest.
Print the output up to two decimal places (Round-off if necessary).
(S.I. = P*T*R/100)
Input Description:
Three values are given to you as the input. these values correspond to Principle amount, Interest... |
''' You are provided with a number, "N". Find its factorial.
Input Description:
A positive integer is provided as an input.
Output Description:
Print the factorial of the integer.
Sample Input :
2
Sample Output :
2 '''
num = int(input(""))
fact=1
if (num > 0):
for i in range(1,num+1):
fact=fact*i
print(f... |
"""
Set operations for 1D numeric arrays based on sorting.
:Contains:
ediff1d,
unique1d,
intersect1d,
intersect1d_nu,
setxor1d,
setmember1d,
union1d,
setdiff1d
:Notes:
All functions work best with integer numerical arrays on input (e.g. indices).
For floating point arrays, innacurate results may appe... |
from fractions import Fraction
n1 = int(input("dati numaratorul:"))
m1 = int(input("dati numitorul:"))
n2 = int(input("dati numaratorul:"))
m2 = int(input("dati numitorul:"))
adunarea = (Fraction(n1,m1)+Fraction(n2,m2))
inmultirea = (Fraction(n1,m1)*Fraction(n2,m2))
print("adunarea =",adunarea)
print("înmulțire... |
lista = [2, 5, 5, 8, 2, 5, 5, 8]
# Fatiar os elementos da lista.
print(lista[2:5])
print(lista[:5])
print(lista[2:])
print(lista[2:122546])
# Inverte a ordem da lista.
print('Invertido')
print(lista[::-1])
print(lista[5:2:-1])
lista.reverse()
print(lista)
# Colocar em ordem crescente ou descrecente
lista.sort(rever... |
# Para adicionar um elemento a uma pasta txt você
# primeiramente vai abrir usando open(), depois vai
# adcionar algum elemento usando o write() e depois
# fechando usando close()
# Usando o método do "w" você cria ou substitui o que tem
# na pasta, usando o "a" você poderá adcionar um elemento
# sem fazer nenhuma mud... |
# TODO: Dada uma string, imprima essa string inteira em maiuscula
# exemplo: 'python' -> 'PYTHON. (1 scores)
# def maiuscula(string):
# return string.upper()
# print(maiuscula('python'))
# TODO: Dada uma string, retorne um booleano que indique se ela é ou não um número.
# exemplo: '1243' -> True, 'a12' -> Fal... |
lista = [1,2,3]
lista2 = [4, 2, 3, 30, 77]
# lista[0] = 4
#
# copia = lista
#
# lista.append(30)
# copia.append(77)
#
# print(lista, copia, lista2)
# print(lista is copia)
# print(lista is lista2)
# print('#' * 10)
# enumerate transforma em tuplas
for i, numero in enumerate(lista):
print(i, numero) |
texto = 'O python e 42'
# o "w" ele coloca e modifica
arquivo = open('text.txt', 'w')
arquivo.write(texto)
arquivo.close()
texto = 'O python e 42'
# o "a" ele da um append
arquivo = open('text.txt', 'w')
arquivo.write(texto)
arquivo.close()
|
"""
Tomas Meszaros
Drawing basic shapes using bitmap graphics.
TODO:
- fix spiral sparse lines (draw bunch of pixels near each pixel
- ellipse tilt
"""
import math
from bmplib import BMPImage
def circle_implicit(save_file, r, a=None, b=None, img_scale=3):
""" circle implicit
(x-a)**2 + (y-b)**2 = r**2
... |
"""
Tomas Meszaros
https://en.wikipedia.org/wiki/Central_limit_theorem
"""
import random
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
"""
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])
plt.show()
"""
def roll_fair_dice():
return random.cho... |
"""
Tomas Meszaros
Solves maze where we want to connect 3 lamps with the shortest cable.
"""
import dijkstar
from pprint import pprint as pp
WALL = '#'
FREE_SPACE = '.'
CABLE = 'o'
def load_maze(file_path):
""" Loads maze from file into 2D array. Assigns each node unique id.
"""
with open(file_path) as... |
"""
Tomas Meszaros
Generates maze.
Maze algorithms:
- http://www.astrolog.org/labyrnth/algrithm.htm
"""
import random
import dijkstar
from svglib import SVGImage
def make_graph(maze_side_length):
""" Makes graph where nodes are rooms and edges are walls.
@maze_side_length is number of rooms of the maze in... |
try: name = raw_input("Enter a screen name: ")
except: name = input("Enter a screen name: ")
import pygame
from pygame.locals import *
import traceback
pygame.display.init()
pygame.font.init()
from mastermind_import import *
from settings import *
import scrabble
import game
#COLORES
NEGRO = (0, ... |
def unique_chars_in_string(input_string):
unique = {}
for i in input_string:
unique[i] = unique.get(i, 0) + 1
maxval = max(unique.keys(), key=(lambda k: unique[k]))
print(unique)
if unique[maxval] > 1:
return False
else:
return True
print(unique_chars_in_string("Language... |
class TreeNode:
def __init__(self, data,left_child = None, right_child = None):
self.data = data
self.left_child = left_child
self.right_child = right_child
class BinaryTree:
def __init__(self, root_node = None):
self.root = root_node
def number_of_leaves(self,root):
... |
#TO JEST KOMENTAZ
#WYŚWIETLANIE TEKSTU W KONSOLI
print("Hello, tu owca, wróciłam")
#TYP DANYCH -> STRING
owca = "owca jest fajna"
#TYP DANYCH -> LICZBY CALKOWITE (INT)
owcaJestLiczbaCalkowita = 7
#TYP DANYCH -> LICZBY ZMIENNOPRZECINKOWE(FLOAT)
owcaJestLiczbaZmiennoPrzecinkowa = 7.5
#TYP DANYCH -> PRWADA/FALSZ (BOOLEAN... |
# def start(self)
#---------------------------------- Properties (parameters)
# | | |
# v v v
class Person:
def __init__(self, name, gndr, occp):
# variable ---
# |
# V
self.name = name
self.gender = gndr
s... |
from random import shuffle
marbles = [
{'color':'red'},
{'color':'red'},
{'color':'red'},
{'color':'red'},
{'color':'red'},
{'color':'red'},
{'color':'red'},
{'color':'red'},
{'color':'blue'},
{'color':'red'},
{'color':'red'},
]
shuffle(marbles)
count = 0
for marble in marbles:
if marble['... |
def get_initials(fullname):
""" Given a person's name, returns the person's initials (uppercase) """
new_fullname = fullname
initials = ''
fullname = fullname.split(' ')
for i in range(len(fullname)):
initials += fullname[i][0].upper()
print('The initials of '+ new_fullname + ', are '+ ... |
# tuples
bob = ('bob', 40, 'Male', 'Miami')
print(bob)
# modifiy the tuple
bob = bob[:2] + ('female',) + bob[:3]
print(bob)
print(list(bob)) |
print('******************************')
print('******************************')
print('******************************')
print('****** Filter & map **********')
print('******************************')
print('******************************')
print('******************************')
myRange = range( 100 )
# long way home
... |
import test_data
import json
#Creates and returns a GameLibrary object(defined in test_data) from loaded json_data
def make_game_library_from_json( json_data ):
#Initialize a new GameLibrary
game_library = test_data.GameLibrary()
### Begin Add Code Here ###
#Loop through the json_data
#Create ... |
def reverse_dict(dict):
d = {}
for key in dict.keys():
tmp = dict[key]
d[tmp] = key
return d
# swap keys and values within dict and return dict
# dict = {'first': '1st', 'second': '2nd'}
# print(reverse_dict(dict)) |
# -*- coding: utf-8 -*-
"""
@author: Malik Türkoğlu , Ömer Okumuş , Varol Koçoğlu , Mert Egi
"""
import random
class generateWordPartOne:
def __init__ (self,totalSearching):
self.totalSearching=totalSearching
def generateWord(self, ValueWord, nounValue, nounList): # this function help us for fin... |
#Example1
x=2 #int
y=3.8 #float
z= 1j #complex
print (type(x))
print(type(y))
print(type(z))
#Example2 Int
i= 2
x= 68768464983164893
y=-27856
print (type(i))
print(type(x))
print(type(y))
#Example3 Float
i=2.20
j=2.3
z=-22.99
print (type(i))
print(type(j))
print(type(z))
x= 25e2
y= 21E5
d= -65.4e98
print (type(x))
... |
#File Handling
f = open("demofile.txt")
z = open("demofile.txt", "rt")
h = open("demofile.txt", "r")
#the code above is the same as
print(f.read())
print(z.read(6))
print(h.readline())
print(h.readline()) #by calling readline() two times, you can read the two first lines.
i = open("demofile.txt", "r")
for x in i:
... |
#Python PIP
import camelcase
c = camelcase.CamelCase()
txt = "lorem ipsum dolor sit amet"
print(c.hump(txt))
#This method capitlizes the first letter of each word.
|
#Example Set() constructore to make a set
z = set(("school", "univesity")) #note the double round-brackets
print(z)
#Example1
x = {"lemon", "orange", "mint"}
print(len(x))
#Example2 remove, discard item
y1 = {"strawberry", "blueberry", "blackberry"}
y1.remove("blackberry")
print(y1)
y2 = {"strawberry", "blueberry", "bl... |
#day12
i= "please, I want {} sandwishes and {} donutes"
i = i.replace("I", "We")
i= i.format(5, 7)
i= i.replace("a", "A")
print(i)
|
class calculator:
def __init__(ref,a,b):
ref.a=a
ref.b=b
def add (ref):
c=ref.a+ref.b
print(c)
def multiply(ref):
d=ref.a*ref.b
print(d)
def divide(ref):
e=ref.a/ref.b
print(e)
def subtratction(ref):
f=ref.a-ref.b
... |
'''this program will take a file containing a string of DNA and find it's reverse complement.
It is important to remember to not just find the complements according to how base pairs are formed,
but to also reverse the order as one strand runs bottom up, and the other strand top down.'''
f = open('string.txt', 'r')
s ... |
'''
'''
class History():
'''
Sequence of past states.
Here, only two past states.
States can be any class, but must implement equality operator.
Callers typically either call:
- roll(); update(new)
- collapse(new)
- update() (when caller only uses one past state.)
These do not result in the... |
'''
Copyright 2012 Lloyd Konneker
This is free software, covered by the GNU General Public License.
'''
class Relations(object):
'''
Binary, symmetric relations of objects to other objects.
Binary: relation between two objects (not three objects)
Symmetric: relation is commutative, A related to B implies... |
print "hello world"
sum=0
for x in range(0,1000):
if x % 3 == 0:
sum+=x
elif x % 5 == 0:
sum+=x
print sum
|
"""Create singly linked list data structure."""
class Node(object):
"""Create a node class."""
def __init__(self, val=None, next=None):
"""Initialize each node instance."""
self.val = val
self.next = next
class LinkedList(object):
"""Create a linked list class."""
def __ini... |
"""Kata: Sum of the first nth term of Series.
#1 Best Practices Solution by MMMAAANNN, doctornick5, Slx64, ninja37,
FablehavenGeek, nabrarpour4 (plus 20 more warriors)
def series_sum(n):
return '{:.2f}'.format(sum(1.0/(3 * i + 1) for i in range(n)))
"""
def series_sum(n):
"""Sum the first nth terms of a s... |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ... |
#!/usr/bin/python
# current release builds databases from which to compare and explore many documents
# future release will provide methods for doing this analysis
import numpy as np
import sqlite3
from sys import argv
def wordCount(file_name,docid):
try:
lst = []
# open file in read mode
... |
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
MS3 = 26
MS2 = 19
MS1 = 13
enable = 6
step = 20
direct = 21
GPIO.setup(enable, GPIO.OUT)
GPIO.setup(step, GPIO.OUT)
GPIO.setup(direct, GPIO.OUT)
GPIO.setup(MS3, GPIO.OUT)
GPIO.setup(MS2, GPIO.OUT)
GPIO.setup(MS1, GPIO.OUT)
def ful... |
class ListNode:
def __init__(self, value, next):
self._value = value
self._next = next
def get_value(self):
return self._value
def set_value(self,value):
self._value = value
def next(self):
return self._next
def set_next(self,next):
self._next = next
... |
import string
from random import randint
class CipherWheel:
def __init__(self, key=None):
self.letters = list(string.ascii_letters)
self.key = key or randint(0, len(self.letters))
def encrypt(self, message):
ciphers = ''
for m in message:
try:
index... |
import pandas as pd
import numpy as np
train_df = pd.read_csv("include/train.csv")
test_df = pd.read_csv("include/test.csv")
unique_ticket = train_df['Ticket'].unique()
# print(unique_ticket)
print("Total number of ticket entries ", len(train_df['Ticket']))
print("Number of unique ticket values ", len(unique_ticket)... |
"""
Ce fichier python sert à tester la gestion du joystick avec pygame
Pour les boutons, les types d'évenements sont JOYBUTTONDOWN et JOYBUTTONUP
event.button renvoit le numéro du button de l'évenement
Pour les directions, le type d'évenement est JOYAXISMOTION
event.axis renvoit l'axe (0 pour l'axe horizontal / 1 axe... |
import math
from abc import ABC, abstractmethod
class Figura(ABC):
@abstractmethod
def nazwa(self):
pass
def wypisz(self):
print(f"Jestem {self.nazwa()}. Moj obwod: {self.obwod()}, a pole: {self.pole()}.")
@abstractmethod
def obwod(self):
pass
@abstractmethod
def pole(self... |
liczba = int(input("Podaj liczbe ktora chce przekonwertowac: "))
binarna = bin(liczba)
osemkowa = oct(liczba)
szesnastkowa = hex(liczba)
print("Liczba w systemie binarnym to:", binarna, ",osemkowym:", osemkowa, "oraz w szesnaskowym", szesnastkowa)
# funkcje odpowiadajace za konwersje to bin() - binarny, oct() - osemk... |
if wysokosc < 1000:
kilometry = 0
print(kilometry, "km to za nisko")
if 1000 <= wysokosc < 2000:
kilometry = 1
print(kilometry, "km to za nisko")
if 2000 <= wysokosc < 3000:
kilometry = 2
print(kilometry, "km to za nisko")
if 3000 <= wysokosc < 4000:
kilometry = 3
print(kilometry, "km to za nisk... |
# need lxml from pip (pip3 install lxml)
#%%
## save requests response locally
import requests
import bs4 as bs
import json
res = requests.get('https://google.com')
with open('data.html', 'w') as f:
f.write(str(res.content)) ## str() to save
## load local html into bs4
with open('data.html') as f:
soup = b... |
numbers = [1,2,3,4,5,6,10,3]
# adding an element at the end: O(1)
numbers.append(1);
print(numbers)
# Adding an element at some index: O(n) because all elements after this index will be shifted
numbers[1] = '90'
# Find the max of the array is of O(N)
maximum = numbers[0]
for i in numbers:
if i > maximum:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# the above line is to avoid 'SyntaxError: Non-UTF-8 code starting with' error
'''
Created on
Course work:
@author: krish
Source: https://www.geeksforgeeks.org/numpy-divide-python/
'''
# Python program explaining
# divide() function
import numpy as np
def start... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# the above line is to avoid 'SyntaxError: Non-UTF-8 code starting with' error
'''
Created on
Course work:
@author: krish
Source: https://www.geeksforgeeks.org/data-type-object-dtype-numpy-python/
'''
# Python Program to create a data type object
# containing a 32 ... |
from abc import abstractmethod
from usuario_bu import UsuarioBU
class Funcionario(UsuarioBU):
@abstractmethod
def __init__(self, departamento: str, cpf: str, dias_de_emprestimo: int) -> None:
super().__init__(cpf, dias_de_emprestimo)
self.__departamento = departamento
@property
def de... |
#!/user/bin/python3
# -*- coding:utf-8 -*-
"""
构造一个字典,它是另外一个字典的子集
"""
#最简单的方法就是字典推导
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
p1 = {key:value for key ,value in prices.items() if value >200}
tech_name = {'AAPL','IBM','HPQ','MSFT'}
p2 = {key:value for key,value in prices.... |
#!/user/bin/python3
#!coding=utf-8
import time
from threading import Thread
#线程之间共享全局变量
g_num=100
def work1():
global g_num
for i in range(3):
g_num +=1
print("---in work1,g_num is %d---"%g_num)
def work2():
global g_num
print("---in work2,g_num is %d---"%g_num)
print("---线程创建之前 g_num is %d---"%g_num)
t1=Thr... |
#!/user/bin/python3
# -*- coding:utf-8 -*-
class Cat:
def __init__(self, new_name, new_age):
self.name = new_name
self.age = new_age
def eat(self):
print("Cat is eating...")
def drink(self):
print("Cat is drinking...")
def introduce(self):
print("%s的年龄是%s" % ... |
#!/user/bin/python3
# -*- coding:utf-8 -*-
# 如果你想要合并的字符串是在一个序列或者iterable中,那么最快的方式可就是使用join()方法
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print(' '.join(parts))
print('-'.join(parts))
print(','.join(parts))
print('*'*50)
# 如果仅仅只是合并少数几个字符串,使用加号“+”通常已经足够了
a = 'Is Chicago'
b = 'Not Chicago?'
print(a+' '+b)
# 如果你想在源码... |
import sys
def calculate_score(num,num_list):
return sum(map(lambda x: 3 if x>=num else 2,num_list))
if __name__=='__main__':
all_lines=sys.stdin.readlines()
a=map(int,all_lines[0].strip().split())
b=map(int,all_lines[1].strip().split())
a.sort()
b.sort()
result=[]
for i in a:
... |
import sys
leap=[0,31,29,31,30,31,30,31,31,30,31,30,31]
ordinary=[0,31,28,31,30,31,30,31,31,30,31,30,31]
leap_sum=366
ordinary_sum=365
today_sum=sum(ordinary[:10])+18
def is_leap(my_year):
if my_year%100==0:
if my_year%400==0:
return True
else:
return False
else:
... |
from collections import defaultdict
import argparse
def getString():
"""
This function reads the text from file,
clears the text from spare lexems and returns the list of words.
"""
with open(r'text_files/in_7.txt', 'r', encoding='UTF-8') as inp:
string = inp.read().lower()
... |
class Logger:
def __init__(self):
self.result = []
@staticmethod
def log(func):
def get_method_data(self, *args):
self.result.append({"function": func.__name__, "args": args, "result": func(self, *args)})
return get_method_data
def __str__(self):
... |
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
import heapq
class Solution:
"""
@param intervals: an array of meeting time intervals
@return: the minimum number of conference rooms required
"""
def minMee... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Credit & source: https://bitbucket.org/william_rusnack/to-precision/src/master/
"""
from __future__ import print_function, division, absolute_import
__author__ = '''William Rusnack github.com/BebeSparkelSparkel linkedin.com/in/williamrusnack williamrusnack@gmail.co... |
while True:
n = int(input())
if(0 <= n <= (2 * (10 ** 9))):
print(len(str(n)))
break
|
x=int(input())
if x<-4:
y=x+5
elif -4<=x<=7:
y=x**2-3*x
elif x>7:
y=x**3+2*x
print(y)
|
ededler = []
n = int(input())
m = 0
for i in range(0, n):
m += 2
ededler.append(m)
print(*ededler, end=" ")
|
n = int(input())
while (abs((n)) <= 10**9):
if(n < 0):
print("Negative")
elif(n == 0):
print("Zero")
else:
print("Positive")
break
|
n=int(input())
a=n//10000
b=n//1000%10
c=n//100%10
d=n//10%10
e=n%10
if a<b<c<d<e:
print("YES")
else:
print("NO")
|
from quadrilateral import Quadrilateral
from two_d_point import TwoDPoint
class Rectangle(Quadrilateral):
def __init__(self, *floats):
super().__init__(*floats)
if not self.__is_member():
raise TypeError("A rectangle cannot be formed by the given coordinates.")
def __is_member(se... |
import numpy as np
def L2_distance(X, Y):
"""
Computes pairwise distance between each vector of the two lists. The vectors has to be of same length.
Eq. || X_i - Y_j || ^ 2 = || X_i || ^ 2 + || Y_j || ^ 2 - 2* transpose(X_i) * Y_j
:param X: List of vectors
:param Y: List of vectors
:return D: ... |
from itertools import product
import numpy as np
def cartesian(list):
temp = product(list[0], list[1])
for i in range(2, len(list)):
temp = [(*a, b) for a, b in product(temp, list[i])]
return temp
if __name__ == '__main__':
A = np.array([1, 2, 3])
B = np.array([4, 5])
D = np.array([3... |
#=================================Part 1 : One word Frequency ==================================
import pyspark
#create spark context
sc=pyspark.SparkContext()
#load the text file
inputFl=sc.textFile("gs://1rashmibucket1/bible+shakes.nopunc");
#1)split using " "(it is set by default in split())
#2)Create a n... |
def alphabet_position(letter):
#find ordinal, and return letter position a0-z25
#does not need to be case sensitive
x = ord(letter.lower())
return (x - 97)
def rotate_character(char, rot):
y = alphabet_position(char)
rotated = 0
newchar = ''
cap_check = ord(char)
if ord(char) < 65 or ord(char) > 122... |
import urllib2
from bs4 import BeautifulSoup
from datetime import date
from datetime import timedelta
import os
import requests
DISH = "Creme Brulee"
TILL_URL = os.environ.get("TILL_URL")
# Sends the alert using Till
def sendAlert(text):
print "Sending alert msg: " + text
requests.post(TILL_URL, json={
"phone": [... |
#!/usr/bin/env python
"""Find the sum of all the multiples of 3 or 5 below 1000"""
def multiple_sum(base, limit):
"""Returns the sum of all multiples of base less than max"""
mult = base
total = 0
while mult < limit:
total += mult
mult += base
return total
print multiple_sum(3, 10... |
from random import seed
from random import radiant
seed(1)
for i in range(10):
value = radiant(0, 10)
print(value)
print("What is your first name?")
n = input("What is your first name?: ")
print(n)
print("What is your last name?")
v = input("What is your last name?: ")
print(v)
print("Hi there, "+str(n)+" "+str(v)+",... |
# encoding:utf-8
__author__ = 'luowei'
# tuple(元组)是不可变的,长度与值是不可伸缩与变化的
t1 = (0,1,2,3);t2 = (4,5,6)
t3 = (0,1,(2,3),'three',('four,one'))
t4 = ()
print t1+t2 # (0, 1, 2, 3, 4, 5, 6)
print t1*2 # (0, 1, 2, 3, 0, 1, 2, 3)
print t3 # (0, 1, (2, 3), 'three', 'four,one')
print t3.index("three") # 3
|
################################################################################
# Author: Fanyang Cheng
# Date: 2/24/2021
# This program asks user for a number and send back the answer whether it is
# a prime number or not.
################################################################################
def is_p... |
################################################################################
# Author:Fanyang Cheng
# Date:27/03/2021
# Description: This file read one sepcific text file and track the number of words
#, number of lines and the average words per line.
################################################################... |
################################################################################
# Author:Fanyang Cheng
# Date:27/03/2021
# Description: This program read the step conting file to read the user's steps
# for each day and calculate average steps for each month.
###########################################################... |
################################################################################
# Author: Fanyang Cheng
# Date: 2/16/2021
# This program ask user to give the print line number(x) and
# print a x lines of hash pattern.
################################################################################
m = int(input(... |
################################################################################
# Author: Fanyang Cheng
# Date: 2/11/2021
# This program calculates the number of
#days in February for the input year.
################################################################################
y = int(input("Please input a ye... |
################################################################################
# Author: Fanyang Cheng
# Date: 2/16/2021
# This program repeatedly asks user to enter a series of non-negative
# numbers and gives the sum and average of these numbers. negative
# number means the end of loop.
######################... |
################################################################################
# Author:Fanyang Cheng
# Date:03/20/2021
# Description:This program get the 3*3 squre and determine if it is Lo Shu square.
################################################################################
#define print_square and is_magic ... |
# input takes input value as string
# int() help to input int value
# you cant add string with int
number_one = int(input("enter first number :"))
number_two = int(input("enter second number :"))
total = number_one + number_two
# print("total is : " + total) # it give error
print("total is : " + str(total))
# str fun... |
# + addition
# - subtraction
# * multiplication
# / float division 4/2 = 2.0
print(4 / 2)
# // integer division 4//2 = 2
print(4 // 2)
# % modulo (it gives remainder) 6%2 = 0
print(6 % 2)
# ** exponent 2**3 = 8
print(2 ** 3)
print(2 ** 0.5) # below I round this as op is big 1.4142135623730951
print(round(2 ** 0.5, 4... |
my_list = [1,2,3]
for item in my_list:
print(item)
continue
i = 0
while i < len(my_list):
print(my_list[i])
i +=1
continue
while True:
response = input('say something: ')
if(response == 'bye'):
break
|
string='Grow Gratitude'
G=string[0]
len_str=len(string)
count_G=string.count('G')
print("G-->",G)
print('len_str-->',len_str)
print("Count_G-->",count_G)
#################################
#first methode
print("First method")
print('\n')
print('\n')
from collections import Counter
string1='Being... |
# Solution for a popular problem about outputting staircase of spaces and hash signs
def print_staircase(n):
for i in range(n):
print(' ' * (n - i - 1) + '#' * (i + 1))
# Test
m = 5
print_staircase(m)
|
list=[]
def evennum(i):
for i in range(1, i):
if(i%2 == 0):
list.append(i)
print(list)
evennum(20)
|
ss = input("enter any string: ")
print(ss)
a='ing'
if(ss.endswith(a)):
print('if string with ing will be = '+str(ss)+'ly')
elif(len(ss)>=3):
print('if string withoout ing then it will be = ' + str(ss) + 'ing')
else:
print("string is not longer than 3 characters \n " +str(ss))
|
import math
a = float(input("Intervalo A: "))
b = float(input("Intervalo B: "))
e = float(input("Tolerancia: "))
def f(x):
return x**2 - 5
if f(a)*f(b) < 0:
while (math.fabs(b-a)/2 > e):
xi = (a+b)/2
print(f'Iteração acontecendo | A: {a} | B: {b} | Xi Medio: {xi} | Função de Xi: {... |
def binToTern(digit):
if digit == "" or digit == " ":
return 0
if digit == 0:
return 2
if digit == 1:
return 1
def boardConvertToTernary(board):
"""takes in a game state in the format of a 6 x 6 array and converts it
to a ternary 36-length tuple where the first 9 bits a... |
#!/usr/bin/python
#coding: UTF-8
"""
题目:取一个整数a从右端开始的4〜7位。
程序分析:可以这样考虑:
(1)先使a右移4位。
(2)设置一个低4位全为1,其余全为0的数。可用~(~0<<4)
(3)将上面二者进行&运算。
"""
a = int(raw_input("input a number:\n"))
b = a >> 4
c = ~(~0 << 4)
d = b & c
print '八进制显示:%o\t%o' %(a,d) # %o 表示无符号八进制
|
#!/usr/bin/python
#coding: UTF-8
"""
题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
程序分析:无。
"""
a = [1,2,3,7,9,8]
print "原列表:%s" % a
min = min(a)
a.remove(min)
a.append(min)
max=max(a)
a.remove(max)
a.insert(0,max)
print "新列表:%s" % a
|
#!/usr/bin/python
#coding: UTF-8
"""
题目:使用lambda来创建匿名函数。
程序分析:无
"""
MAXINUM = lambda x,y : ( x > y ) * x + ( x < y ) * y
MININUM = lambda x,y : ( x > y ) * y +( x < y ) * x
a = 10
b = 20
print 'The largar one is %d' % MAXINUM(a,b)
print 'The lower one is %d' % MININUM(a,b)
|
#!/bin/usr/python
#coding:UTF-8
"""
题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
程序分析:请抓住分子与分母的变化规律。新分子等于前一个分子分母之和,新分母等于前一个分子
"""
a = 2.0
b = 1.0
s = 0
for i in range(0,20):
s += a/b
t = a
a = a+b
b = t
print '%.4f' % s
|
#/usr/bin/python
#coding: UTF-8
"""
题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
程序分析:无。
"""
a = []
n = input('你想输入几位数:')
for i in range(1,n+1):
s = input("请输入第%d位数:"%i)
a.append(s)
m=input("你想将列表移动几位:")
print '排序前的列表:%s'% a
b=a[-m:] #获取后面的m个数
c =a[:-m] #获取前面除了m的数
a = b+c
print '排序后列表:%s'%a
|
#!/usr/bin/python
#coding:UTF-8
def x(s):
if len(s)>0:
print s[-1]
x(s[0:-1])
a = 'abcdfg'
print a
x(a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.