Ejemplo n.º 1
0
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)
Ejemplo n.º 2
0
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)
Ejemplo n.º 3
0
def test():
    """test"""
    number = int(input("Please enter an integer: "))

    if number < 0:
        number = 0
        print('Negative changed to zero')
    elif number == 0:
        print('Zero')
    elif number == 1:
        print('Single')
    else:
        print('More')

    words = ['cat', 'window', 'defenestrate']
    for word in words:
        print(word, len(word))

    for number in range(2, 10):
        for ximp in range(2, number):
            if number % ximp == 0:
                print(number, 'equals', ximp, '*', number / ximp)
                break
        else:
            print(number, 'is a prime number')

    fibo.fib(2000)

    f100 = fibo.fib2(100)
    print(f100)
Ejemplo n.º 4
0
def test3():
    """Funcion Principal"""
    try:
        number = int(input('Please enter a number'))
        fibo.fib(number)
    except ValueError:
        print('Input is not a number')
Ejemplo n.º 5
0
def test2():
    """Funcion Principal"""
    if len(sys.argv) < 2:
        print('Usage: script number')
    else:
        number = int(sys.argv[1])
        print('Number value: ', number)

        fibo.fib(number)
Ejemplo n.º 6
0
def fib2(n):  # Write fibonacci series upto n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a + b
    return result

    import fibo
    fibo.fib(1000)
    fibo.fib2(100)
    fib = fibo.fib
Ejemplo n.º 7
0
def test26(): # module
    import fibo  # lookup file 'fibo.py'
    print(fibo.fib(10))
    print(fibo.fib2(10))    
    print(dir(fibo))

    fibo._ver_ = 2.0

    '''
    print(fibo.__builtins__
        , fibo.__cached__
        , fibo.__doc__        
        , fibo.__file__        
        , fibo.__loader__        
        , fibo.__name__        
        , fibo.__package__        
        , fibo.__spec__
        )
    '''

    print(fibo.__name__,     fibo.__cached__, fibo.__doc__, fibo.__file__, fibo.__loader__, fibo.__package__)
    print(fibo.__spec__, fibo._ver_)

    import builtins

    print(dir(builtins))
Ejemplo n.º 8
0
def test():
    """Test cases."""

    print('Example 1:')
    fibo.fib(1000)

    print('Example 2:')
    print(fibo.fib1(1000))
    
    print('Example 3:')
    print(fibo.__name__)

    # Assigning function a local name
    fib = fibo.fib

    print('Example 4:')
    fib(1000)
Ejemplo n.º 9
0
    def POST(self):
        form = web.input(numbers = None)

        if form.numbers:
            num = int(form.numbers)
            sequence = fibo.fib(num)
            return render.index(sequence = sequence)
        else:
            return "Error. A numeric value is required"
Ejemplo n.º 10
0
    def mathStuff(self):
        print(math.sqrt(25))
        print(math.pi)

        # 2 radians = 114.59 degrees
        print(math.degrees(2))

        # 60 degrees = 1.04 radians
        print(math.radians(60))

        # Sine of 2 radians, Cosine of 0.5 radians, Tangent of 0.23 radians
        print(math.sin(2))
        print(math.cos(.5))
        print(math.tan(.23))

        print(math.factorial(4))

        # random int between 0 and 5
        print(random.randint(0,5))

        # random floating point number between 0 and 1
        print(random.random())

        # random number between 0 and 100
        print(random.random() * 100)

        List = [1,4,True,800,"python",27,"hello"]

        # random element from a set such a list is chosen
        print(random.choice(List))

        # returns number of seconds since Unix Epoch, Jan 1st 1970
        print(time.time())

        # Converts a number of seconds to a date object
        print(date.fromtimestamp(454554))

        # Using modules to do fib sequence, first writing then returning a list.
        fibo.fib(100)
        print(fibo.fib2(100))
Ejemplo n.º 11
0
 def data_received(self, data):
     self.log.debug('Received: {}'.format(data))
     if not data.strip():
         return
     try:
         digits = data.split(b' ')
         result = [fib(int(digit)) for digit in digits if digit.isdigit()]
         for digit in result:
             self.transport.write(str(digit).encode('utf8'))
             self.transport.write(b'\n')
         self.log.debug('Sent: {}'.format(result))
     except TypeError as e:
         error_message = 'Can`t convert received data to int!'
         self.log.error(error_message)
         self.transport.write(error_message)
Ejemplo n.º 12
0
async def fibo_handler(reader, writer):
    address = writer.get_extra_info('peername')
    log = logging.getLogger('fib_serv_{}_{}'.format(*address))
    log.debug('Connection accepted')

    while True:
        data = await reader.read(128)
        terminate = data.endswith(EOF)
        data = data.rstrip(EOF)

        if data:
            log.debug('Received {!r}'.format(data))
            try:
                result = fibo.fib(int(data.strip()))
                writer.write(str(result).encode('utf8'))
                await writer.drain()
                log.debug('Sent {!r}'.format(result))
            except TypeError:
                log.error('Could not convert data to int: %s', data)
            await writer.drain()
        if not data or terminate:
            log.debug('Closing..')
            writer.close()
            return
Ejemplo n.º 13
0
## 이렇게 사용 할 수도 있다.
import fibo

fibo.fib(500)
print(fibo.__name__)

## 아래와 같은 방식으로 할 수 있다.
from fibo import *

fib(1000)
Ejemplo n.º 14
0
# 6 模块
# 模块的目的是 更好的复用文件中的函数
# Python 提供了一个方法可以从文件中获取定义,在脚本或者解释器的一个交互式实例中使用.这样的文件被称为 模块
# 模块是包括 Python 定义和声明的文件.文件名就是模块名加上 .py 后缀.
# 模块的模块名(做为一个字符串)可以由全局变量 __name__ 得到
import fibo
print('fibo.fib(10)', end=' ')
fibo.fib(10)
print('fibo.fib_ary(20)', fibo.fib_ary(20))
localfib = fibo.fib
localfib(55)
# 每个模块都有自己私有的符号表,被模块内所有的函数定义作为全局符号表使用.
# 因此,模块的作者可以在模块内部使用全局变量,而无需担心它与某个用户的全局变量意外冲突
# 模块可以导入其他的模块 import 语句的一个变体直接从被导入的模块中导入命名到本模块的语义表
from fibo import fib, fib_ary
fib(56)

# 作为脚本来执行模块
# 通常用来为模块提供一个便于测试的用户接口(将模块作为脚本执行测试需求)
'''
python fibo.py 123
fib. __name__ __main__
1 1 2 3 5 8 13 21 34 55 89
'''
# 模块中的代码会被执行,就像导入它一样,不过此时 __name__ 被设置为 "__main__",
# 通过import导入后调用__name__ 被设置为 模块名称 fibo
'''
# 在脚本的最后加上 
 if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
Ejemplo n.º 15
0
# module_name can be wtv; filename is module_name.py

# within module, module_name (as a string) is available as the value
# of the global variable __name__ .

# use your favorite text editor to create a file called fibo.py in the
# current directory with 'Fibonacci numbers module' as 1st line comment

# then import module in console
>>> import fibo

# cannot directly access functions defined in module!
# module is an object, its functions are its member functions
>>> import fibo
>>> for i in range(20):
...     print fibo.fib(i)  # see here
... 
0
1
1
1
2
3
5
8
13
21
34
55
89
144
Ejemplo n.º 16
0
import fibo as mod
import sys

# mod.fib(10)
# mod.fib(int(sys.argv[1]))

if __name__ == "__main__":
    mod.fib(int(sys.argv[1]))
Ejemplo n.º 17
0
from fibo import fib

if __name__ == '__main__':
    fib(50)
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 13:00:56 2020

@author: demir
"""

import fibo
import sys

fibo.fib(5)

print(fibo.fib2(4))

print("filename:")
print(sys.argv[0])

print(
    fibo.fib2(int(sys.argv[1]))
)  # to give arg on Spyder, use Ctrl+F6 and select "Command Line Options". Fill the box next to it. !It takes as STRING!
Ejemplo n.º 19
0
import fibo
fip = fibo.fib(4000000)
print sum(filter(lambda x: x % 2 == 0, fip))
Ejemplo n.º 20
0
import fibo

#fibo.fib(1000)
print ''

from fibo import fib, fib2

fib(500)
print ''
fib2(500)

Ejemplo n.º 21
0
# -*- coding: UTF-8 -*-

# > When you run a Python module with
#python fibo.py <arguments>

# > Note If you use docker, use next command instead of 'python fibo.py <arguments>'.
#docker run --rm -it -v $(pwd):/app python:3 python /app/fibo.py <arguments>

# > the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__".
# > That means that by adding this code at the end of your module:
#if __name__ == "__main__":
#    import sys
#    fib(int(sys.argv[1]))

# > you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

# > If the module is imported, the code is not run:
import fibo
fibo.fib(500)  # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

# > This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).
Ejemplo n.º 22
0
#import fibo
#or
#print( fibo.fib(10000))
#print(fibo.fib2(100))


# from fibo import fib, fib2
from fibo import fib, fib2



print ('If you intend to use a function often you can assign it to a local name:')



#fib = fibo.fib
print(fib(500))
Ejemplo n.º 23
0
'''
The advantage of the lambda operator can be seen when it is used in combination with the map() function. 
map() is a function with two arguments:

r = map(func, seq)

The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func
'''
f = lambda x : x**2
print(f(3))
squares = list(map(lambda x : x**2, range(10)))
print(squares)
print("-" * 50)
import fibo #This is module
fibo.fib(1000) #This is method function in module
print(fibo.fib2(1000))
Ejemplo n.º 24
0
#!/usr/bin/env python

from fibo import fib

print fib(1000)

from fibo import fib2

print fib2(1000)
Ejemplo n.º 25
0
#!/usr/bin/python

import fibo

fibo.fib(1000);
print fibo.fib2(1000);

# The dir function is used to find out what symbols a module defines.
print dir(fibo);
Ejemplo n.º 26
0
def test27(): # module 2
    from fibo import fib, fib2
    print(fib(10))
    print(fib2(10))    
Ejemplo n.º 27
0
#Learning Python

#from fibo import fib

import fibo


print(fibo.fib(0))
print(fibo.fib(1))
print(fibo.fib(2))
print(fibo.fib(3))
print(fibo.fib(4))
print(fibo.fib(5))
print(fibo.fib(6))


11018  11022  11026 11030 11036 11040 11044 11055 11066  11077  11081  11085  11089  11093  11097  11101
Ejemplo n.º 28
0
#! /usr/bin/env python

if __name__=="__main__":
	import sys
	from fibo import fib
	print fib(int(sys.argv[1]))
Ejemplo n.º 29
0
"""Import a module to show statements and functions definitions being executed."""

import fibo

print("Initialise demo_import")

fibo.fib(5)

if __name__ == "__main__":
    import sys

    fibo.fib(int(sys.argv[1]))
Ejemplo n.º 30
0
from fibo import fib

print "Bis zu welcher Zahl willste gehen?"
n = int(raw_input("> "))
# x = input() # oder so

print fib(n)
Ejemplo n.º 31
0
# -*- coding: utf-8 -*-

# file name import
import fibo

# method import
print(fibo.fib(1000))

# module name
print(fibo.__name__)

# method import
from fibo import fib, fib2
# from fibo import *
# from fibo import fib as fibonacci
print(fib(1000))
print(fib2(1000))
Ejemplo n.º 32
0
import fibo

def isEven(x):
    return x%2==0

fiboList =  fibo.fib(4000000)

evenFibs = filter(isEven, fiboList)

evenFibsSum = sum(evenFibs)

print(evenFibsSum)
Ejemplo n.º 33
0
import fibo
fibo.fib(1000)
print(fibo.fib2(100))
print(fibo.__name__)
# 导入模块的其他方式
from fibo import *  #  * 导入模块的全部关键字
fib(500)
print(fib2(1000))

import fibo as fib  # 导入模块里的fib关键字
fib.fib(500)

from fibo import fib as fibonacci  # 导入fib关键字,用fibonacci代替
fibonacci(500)
Ejemplo n.º 34
0
#!/usr/bin/python

import fibo

fibo.fib(10)

print fibo.fib2(10)

fib = fibo.fib

fib(20)
Ejemplo n.º 35
0
import fibo

list1 = []
fibo.fib(200)
list1 = fibo.fib2(10)
print list1
Ejemplo n.º 36
0
'''
Created on 2013/4/8

@author: kim.hsiao
'''

# it's a file for fibo testing

import fibo  # import fibo which name is fibo.py

print fibo.fib(1000)  # import from fibo.py and execute the module within

print fibo.fib2(100)  # import from fibo.py and execute its module within

print fibo.__name__  # show the module name
Ejemplo n.º 37
0
import fibo

meuFibo = fibo.fib(10)

print(__name__)
Ejemplo n.º 38
0
#!/usr/bin/env python

import fibo

fibo.fib(5)
print fibo.fib2(10)
Ejemplo n.º 39
0
# -*- coding: utf-8 -*-
import fibo
import sys

#print fibo.fib(1000)
#print fibo.__name__

print fibo.fib(50)
print dir()
#1 1 2 3 5 8 13 21 34 None
#['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'fibo', 'sys']
Ejemplo n.º 40
0
def test():
    """Test cases."""

    print(fib(500))
Ejemplo n.º 41
0
#import fibo # full import
# print("running from main")
# fibo.fib(100)
# f = fibo.fib2(30)
# print(f)

# # we can also import a part of the file
# from fibo import fib2
# print("running from main")
# f = fib2(30)
# print(f)

#_______________
# import BMIcalculator
# print(BMIcalculator.BMI(120, 2))
# print(BMIcalculator.bmi2(220, 77.8))

import fibo
from BMIcalculator import BMI
f = fibo.fib(100)
print(f)
print(BMI(100, 2))
Ejemplo n.º 42
0
print(list(range(10)))
    
###
# 4.6 Defining Functions
###

def fib(n):
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()

fib(2000)
fib

###
# 4.7.1. Default Argument Values
###

#%%
# The default values are evaluated at the point of function definition in the defining scope, 
# so that will print 5.
i = 5

def f(arg=i):
    print(arg)

i = 6
Ejemplo n.º 43
0

from fibo import fib, fib2
from fibo import *  # import all
import fibo as f
from fibo import fib as fibonacci
import directory.moduleChild as f2  # when importing from different directory. need as
from directory.moduleChild import *  # when importing from different directory. need as


# need to configure parent package. https://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py/27876800#27876800
# from ..moduleParent import *

import main.modules.moduleParent as f3 # import by absolute path

f3.fibParent(1)
# fibParent(1)
fib(1)
f.fib(1)
fibonacci(1)
f2.fibChild(1)
# If module.py is imported by other, then this is not invoked.
if __name__ == "__main__":
    print(1)
    # import sys

    # fib(int(sys.argv[1]))

# shows member field or functions of the imported module
dir(f2)
Ejemplo n.º 44
0
#! /usr/bin/python


from fibo import fib, fib2


print (fib(100))
print (fib2(100))
Ejemplo n.º 45
0
在字典中循环时,关键字和对应的值可以使用 iteritems()方法同时解读出来。 
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v

同时循环两个或更多的序列,可以使用 zip() 整体解读。 
in 和 not in 比较操作符审核值是否在一个区间之内。操作符 is is not 和比较两个对象是否相同;
在表达式内部不能赋值。

import fibo
这样做不会直接把 fibo中的函数导入当前的语义表;它只是引入了模块名 fibo。

import 语句的一个变体直接从被导入的模块中导入命名到本模块的语义表中。例如: 
>>> from fibo import fib, fib2
>>> fib(500)

from fibo import *
导入所有除了以下划线(_)开头的命名。

变量 sys.path 是解释器模块搜索路径的字符串列表。它由环境变量 PYTHONPATH 初始化,
用标准的字符串操作修改它: 
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

dir() 用于按模块名搜索模块定义,
----------------

必须要有一个 __init__.py 文件的存在,才能使Python视该目录为一个包;
最简单的情况下,__init__.py 可以只是一个空文件,不过它也可能包含了包的初始化代码,或者设置了 __all__ 变量
Ejemplo n.º 46
0
# demo union ...
a = set('abcdfgh')
b = set('cdefhijk')
print('a-b:'+str(a - b))
print('aUb:'+str(a | b))
print('a&b:'+str(a & b))
print('a^b:'+str(a ^ b))

""" dict """
tel = {'jack':1234, 'rose':4531, 'snape':8872}
tel['jack'] = 1038
print(tel)
del tel['snape']
print(tel)
tel['ron'] = 1048
print(list(tel.keys()))
print(dict(ron=1,harry=2,snape=4))
for k,v in tel.items():
    print(k,v)
    
questions = ['name', 'job', 'expertise']
answers = ['cai', 'engineer', 'sensors']
for q,a in zip(questions, answers):
    print('What is your {0}? It is {1}.' .format(q,a))
    
import fibo
print(fibo.fib(10))

with open('README.md') as f:
    read_data = f.read()
print(read_data)
Ejemplo n.º 47
0
from fibo import fib

series = fib(100)
for item in series:
    print(item)
Ejemplo n.º 48
0
print("----------------Module----------------")

# 1.
# This does not enter the names of the functions defined in fibo directly in the current symbol table; 
# it only enters the module name fibo there. Using the module name you can access the functions:
import fibo
fibo.fib(100)
fib3=fibo.fib
fib3(100)

# 2.
# This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined).
from fibo import fib, fib2
fib(500)

# 3.
# this is not recommended, that is frown upon(眉头一皱不赞同,LOL)
# This imports all names except those beginning with an underscore (_).
from fibo import *
fib(100)

# Note: Note For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload(), e.g. import importlib; importlib.reload(modulename).

 # The Module Search Path
 # When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path.
print('The Module Search Path--------------------')

# not work????
# These two variables are only defined if the interpreter is in interactive mode.
'''
# 命令行开始符
Ejemplo n.º 49
0
# Diatas ini merupakan implementasi dari module yang sudah di buat sebelumnya

# Dibawah cara pemanggilan module
>>> import fibo as fib
>>> fib.fib(500)

# Berikut ini adalah hasil dari fib.fib(500)
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Ejemplo n.º 50
0
#Module in Python
#把定义放在文件中,为了一些脚本或者交互式的解释器实例使用,这个文件被称为模块
#模块是一个包含你自定义的函数和变量的文件,后缀名是.py
import sys
print("command line args is :");
for i in sys.argv:
        print(i);

print("Python path is ", sys.path);

import fibo

fibo.fib(100);#fib(100) will lead to an error, using mudule name prefix
print(fibo.fib2(100));

#module name ===> fibo.__name__
print("fibo module name is ", fibo.__name__);

#if you use a module frequently, just assign a variable intead of fibo.fib
wtf = fibo.fib2;
print("wtf(100) is :", wtf(100));

#模块除了方法定义以外可以包括可执行的代码,这些代码一般用来初始化这个模块
#这些代码在第一次导入时才会被执行,每一个模块都有各自独立的符号表,在模块内部为所有的函数当做全局
#符号表来使用

from fibo import fib, fib2#这种方式把所有的名字都导入进来
print("from fibo import fib, fib2");
fib(100);

#__name__属性
Ejemplo n.º 51
0
import sys
from fibo import fib, fib2

if __name__ == '__main__':
    n = 50
    print("Fibonacci numbers up to ", n)
    fib(n)
    m = 30
    print("Fibonacci numbers up to ", m, " in a list")
    print(fib2(m))
Ejemplo n.º 52
0
#MODULES/LIBRARIES

#Another way to import a module:
from fibo import *
fib(100)

print("Another way:")
print()

import fibo

fibo.fib(300)

print()

print("Random Number:")
import random
x = random.randrange(1, 100)
print(x)
Ejemplo n.º 53
0
# -*- coding: utf-8 -*-
"""
Created on Mon Feb  5 14:01:38 2018

@author: AnthonyN
"""

from fibo import fib, fib2
fib(500)

Ejemplo n.º 54
0
# -*- coding:utf-8 -*-

import builtins
import fibo

result1 = fibo.fib(1000)
result2 = fibo.fib2(100)
print(result1)
print(result2)
print(dir(fibo))
print(dir(builtins))

# rw file

#with open('workfile.txt') as f:
#    read_data = f.read()
f = open('workfile.txt')
for line in f:
    print(line, end='')
Ejemplo n.º 55
0
# import fibo
#
# fibo.fib(100)
#
# print(fibo.fib2(100))

from fibo import fib,fib2

fib(100)

print(fib2(200))
Ejemplo n.º 56
0
import fibo

fibo.fib(1000)

fibList = fibo.fib2(100)
print " "

print fibList

# can assign the function name to a variable to make it easier to call
f = fibo.fib2
print f(100)


# find out the names that a module defines
print dir(fibo)
Ejemplo n.º 57
0
# -*- coding: utf-8 -*-
"""
Created on Fri Nov  8 19:52:23 2019

@author: CEC
"""

import fibo
fibo.fib(100)
Ejemplo n.º 58
0
'''
Created on 2013/4/8

@author: kim.hsiao
'''

if __name__ == "__main__":
    from fibo import fib
    import sys
    fib(int(sys.argv[1]))

'''
1. the code in the module will be executed, just as if you import it,
but with the "__name__" set to "__main__". That means that by adding
this code at the end of your module

2. you can make the file usable as a script as well as an importable
module, because the code that parses the command line only runs if
the module is executed as the "main" file

may issue following command:
$ python fibo2.py 50
1 1 2 3 5 8 13 21 34

3. the code is also importable. but now we do not re-duplicate the same
code from fibo, otherwise this file can be also importable from other
'''