Уведомления

Группа в Telegram: @pythonsu

#1 Июнь 1, 2012 21:56:27

frenchsasha
Зарегистрирован: 2012-06-01
Сообщения: 4
Репутация: +  0  -
Профиль   Отправить e-mail  

Python Помощь!!

Я пишу тест на Python, и мне нужна помощь с некоторыми вопросами. Можете ли вы помочь? Вопросы на английском языке. Но я не думаю, что это должно быть для вас проблемой.

# Question 1: Remove Tags

# When we add our words to the index, we don't really want to include
# html tags such as <body>, <head>, <table>, <a href=“…”> and so on.

# Write a procedure, remove_tags, that takes as input a string and returns
# a list of words, in order, with the tags removed. Tags are defined to be
# strings surrounded by < >. Words are separated by whitespace or tags.
# You may assume the input does not include any unclosed tags, that is,
# there will be no ‘<’ without a following ‘>’.

def remove_tags():


print remove_tags('''<h1>Title</h1><p>This is a
<a href="http://www.udacity.com">link</a>.<p>''')
#>>>

print remove_tags('''<table cellpadding='3'>
<tr><td>Hello</td><td>World!</td></tr>
</table>''')
#>>>

print remove_tags(“<hello><goodbye>”)
#>>>


# Question 2: Find and Replace

# For this question you need to define two procedures:
# make_converter(match, replacement)
# Takes as input two strings and returns a converter. It doesn't have
# to make a specific type of thing. Itcan
# return anything you would find useful in apply_converter.
# apply_converter(converter, string)
# Takes as input a converter (produced by create_converter), and
# a string, and returns the result of applying the converter to the
# input string. This replaces all occurrences of the match used to
# build the converter, with the replacement. It keeps doing
# replacements until there are no more opportunities for replacements.


def make_converter(match, replacement):



def apply_converter(converter, string):



# For example,

c1 = make_converter('aa', ‘a’)
print apply_converter(c1, ‘aaaa’)
#>>> a

c = make_converter('aba', ‘b’)
print apply_converter(c, ‘aaaaaabaaaaa’)
#>>> ab

# Note that this process is not guaranteed to terminate for all inputs
# (for example, apply_converter(make_converter('a', ‘aa’), ‘a’) would
# run forever).



# Question 3: Longest Repetition

# Define a procedure, longest_repetition, that takes as input a
# list, and returns the element in the list that has the most
# consecutive repetitions. If there are multiple elements that
# have the same number of longest repetitions, the result should
# be the one that appears first. If the input list is empty,
# it should return None.

def longest_repetition():




#For example,

print longest_repetition()
# 3

print longest_repetition()
# b

print longest_repetition()
# 1

print longest_repetition()
# None



# Question 4: Deep Reverse
# Define a procedure, deep_reverse, that takes as input a list,
# and returns a new list that is the deep reverse of the input list.
# This means it reverses all the elements in the list, and if any
# of those elements are lists themselves, reverses all the elements
# in the inner list, all the way down.

# Note: The procedure must not change the input list.

# The procedure is_list below is from Homework 6. It returns True if
# p is a list and False if it is not.

def is_list(p):
return isinstance(p, list)

def deep_reverse():



#For example,

p = [1, [2, 3, [4, ]]]
print deep_reverse(p)
#>>> [[[, 4], 3, 2], 1]
print p
#>>> [1, [2, 3, [4, ]]]

q = [1, , 4, ]
print deep_reverse(q)
#>>> [ , 4, , 1]
print q
#>>> [1, , 4, ]


Вся помощь будет оценена

Офлайн

#2 Июнь 1, 2012 23:37:32

asilyator
От:
Зарегистрирован: 2010-10-24
Сообщения: 276
Репутация: +  -2  -
Профиль   Отправить e-mail  

Python Помощь!!

[code][/code]
Используй их.



Отредактировано asilyator (Июнь 2, 2012 02:43:22)

Офлайн

#3 Июнь 1, 2012 23:57:17

fata1ex
От:
Зарегистрирован: 2009-07-11
Сообщения: 732
Репутация: +  52  -
Профиль   Отправить e-mail  

Python Помощь!!

Странный подход к делу. Вы начните самостоятельно делать задания, а мы подскажем, если будут какие-то проблемы. Не думаю, что кому-то интересно делать всю работу за вас .



Офлайн

#4 Июнь 2, 2012 19:13:55

Unril
От: Москва
Зарегистрирован: 2012-05-27
Сообщения: 3
Репутация: +  1  -
Профиль   Отправить e-mail  

Python Помощь!!

Как-то так:

def remove_tags(str):
    is_tag = False
    result = ""
    for char in str:
        if char == "<":
            is_tag = True
        elif char == ">":
            is_tag = False
            char = ' '
        if not is_tag:
            result += char
    return result.split()
def make_converter(match, replace):
    return lambda str: str.replace(match, replace)
def apply_converter(converter, str):
    while True:
        result = converter(str)
        if result == str:
            break
        str = result
    return str
def longest_repetition(list):
    if not list:
        return
    count = [1, list[0]]
    max = count
    for item in list[1:]:
        if item == count[1]:
            count[0] += 1
        else:
            count = [1, item]
        if count[0] > max[0]:
            max = count
    return max[0], max[1]
def is_list(p):
    return isinstance(p, list)
def deep_reverse(input):
    if not is_list(input):
        return input
    result = input[::-1]
    for i, item in enumerate(result):
        result[i] = deep_reverse(item)
    return result
Было довольно интересно попрактиковаться в подобных задачках.

Отредактировано Unril (Июнь 2, 2012 19:17:42)

Офлайн

#5 Июнь 2, 2012 20:40:12

frenchsasha
Зарегистрирован: 2012-06-01
Сообщения: 4
Репутация: +  0  -
Профиль   Отправить e-mail  

Python Помощь!!

привет
У меня есть несколько вопросов по поводу некоторых кодирования питона. Я пытался решить эти три проблемы, но безрезультатно. я понятия не имею, как начать их решения. Это дополнительный курс, который я беру. У меня 2 выпускных экзаменов в школе послезавтра, и вся помощь будет высоко оценен.

Question 1

The number of ways of splitting n items in k non-empty sets is called
the Stirling number, S(n,k), of the second kind. For example, the group
of people Dave, Sarah, Peter and Andy could be split into two groups in
the following ways.

1. Dave, Sarah, Peter Andy
2. Dave, Sarah, Andy Peter
3. Dave, Andy, Peter Sarah
4. Sarah, Andy, Peter Dave
5. Dave, Sarah Andy, Peter
6. Dave, Andy Sarah, Peter
7. Dave, Peter Andy, Sarah

so S(4,2) = 7

If instead we split the group into one group, we have just one way to do it.

1. Dave, Sarah, Peter, Andy

so S(4,1) = 1

or into four groups, there is just one way to do it as well

1. Dave Sarah Peter Andy

so S(4,4) = 1

If we try to split into more groups than we have people, there are no ways to do it.

The formula for calculating the Stirling numbers is

S(n, k) = k*S(n-1, k) + S(n-1, k-1)

Furthermore, the Bell number B(n) is the number of ways of splitting n into any number of parts, that is,

B(n) is the sum of S(n,k) for k =1,2, … , n.

Write two procedures, stirling and bell. The first procedure, stirling takes as its inputs two positive integers of which the first is the number of items and the second is the number of sets into which those items will be split. The second procedure, bell, takes as input a positive integer n and returns the Bell number B(n).

def stirling():
    
def bell():
    
Here are some example cases:
#print stirling(1,1)
#>>> 1
#print stirling(2,1)
#>>> 1
#print stirling(2,2)
#>>> 1
#print stirling(2,3)
#>>>0
#print stirling(3,1)
#>>> 1
#print stirling(3,2)
#>>> 3
#print stirling(3,3)
#>>> 1
#print stirling(4,1)
#>>> 1
#print stirling(4,2)
#>>> 7
#print stirling(4,3)
#>>> 6
#print stirling(4,4)
#>>> 1
#print stirling(5,1)
#>>> 1
#print stirling(5,2)
#>>> 15
#print stirling(5,3)
#>>> 25
#print stirling(5,4)
#>>> 10
#print stirling(5,5)
#>>> 1
#print stirling(20,15)
#>>> 452329200
#print bell(1)
#>>> 1
#print bell(2)
#>>> 2
#print bell(3)
#>>> 5
#print bell(4)
#>>> 15
#print bell(5)
#>>> 52
#print bell(15)
#>>> 1382958545

Question 2:
One of the problems with our page ranking system is pages can collude with each other to improve their page ranks. We consider A->B a reciprocal link if there is a link path from B to A of length equal to or below the collusion level, k. The length of a link path is the number of links which are taken to travel from one page to the other.

If k = 0, then a link from A to A is a reciprocal link for node A, since no links needs to be taken to get from A to A.

If k=1, B->A would count as a reciprocal link if there is a link A->B, which includes one link and so is of length 1. (it requires two parties, A and B, to collude to increase each others page rank).

If k=2, B->A would count as a reciprocal link for node A if there is a path A->C->B, for some page C, (link path of length 2), or a direct link A-> B (link path of length 1).

The compute_ranks code must:
- take an extra input k, which is a non-negative integer, and
- exclude reciprocal links of length up to and including k from helping the page rank.


def compute_ranks(graph):
    d = 0.8 # damping factor
    numloops = 10
    ranks = {}
    npages = len(graph)
    for page in graph:
        ranks[page] = 1.0 / npages
    for i in range(0, numloops):
        newranks = {}
        for page in graph:
            newrank = (1 - d) / npages
            for node in graph:
                if page in graph[node]:
                    newrank = newrank + d * (ranks[node]/len(graph[node]))
            newranks[page] = newrank
        ranks = newranks
    return ranks

Here are some example cases:
g = {'a': ['a', 'b', 'c'], 'b':['a'], 'c':['d'], 'd':['a']}
#print compute_ranks(g, 0) # the a->a link is reciprocal
#>>> {'a': 0.26676872354238684, 'c': 0.1216391112164609,
#     'b': 0.1216391112164609, 'd': 0.1476647842238683}
#print compute_ranks(g, 1) # a->a, a->b, b->a links are reciprocal
#>>> {'a': 0.14761759762962962, 'c': 0.08936469270123457,
#     'b': 0.04999999999999999, 'd': 0.12202199703703702}
#print compute_ranks(g, 2)
# a->a, a->b, b->a, a->c, c->d, d->a links are reciprocal
# (so all pages end up with the same rank)
#>>> {'a': 0.04999999999999999, 'c': 0.04999999999999999,
#     'b': 0.04999999999999999, 'd': 0.04999999999999999}


Question 3:

A one-dimensional cellular automata takes in a string, which in our case, consists of the characters ‘.’ and ‘x’, and changes it according to some predetermined rules. The rules consider three characters, which are a character at position k and its two neighbours, and determine what the character at the corresponding position k will be in the new string.

For example, if the character at position k in the string is ‘.’ and its neighbours are ‘.’ and ‘x’, then the pattern is ‘..x’. We look up ‘..x’ in the table below. In the table, ‘..x’ corresponds to ‘x’ which means that in the new string, ‘x’ will be at position k.

Rules:
pattern in position k in contribution to
Value current string new string pattern number
is 0 if replaced by ‘.’ and value if replaced by ‘x’
# 1 ‘…’ ‘.’ 1 * 0
# 2 ‘..x’ ‘x’ 2 * 1
# 4 ‘.x.’ ‘x’ 4 * 1
# 8 ‘.xx’ ‘x’ 8 * 1
# 16 ‘x..’ ‘.’ 16 * 0
# 32 ‘x.x’ ‘.’ 32 * 0
# 64 ‘xx.’ ‘.’ 64 * 0
# 128 ‘xxx’ ‘x’ 128 * 1
# ———-
# 142

To calculate the patterns which will have the central character x, work out the values required to sum to the pattern number. For example, 32 = 32 so only pattern 32 which is x.x changes the central position to
an x. All the others have a . in the next line.

23 = 16 + 4 + 2 + 1 which means that ‘x..’, ‘.x.’, ‘..x’ and ‘…’ all
lead to an ‘x’ in the next line and the rest have a ‘.’

For pattern 142, and starting string
………..x………..
the new strings created will be
……….xx……….. (generations = 1)
………xx………… (generations = 2)
……..xx…………. (generations = 3)
…….xx………….. (generations = 4)
……xx…………… (generations = 5)
…..xx……………. (generations = 6)
….xx…………….. (generations = 7)
…xx……………… (generations = 8)
..xx………………. (generations = 9)
.xx……………….. (generations = 10)

Note that the first position of the string is next to the last position in the string.

Define a procedure, cellular_automaton, that takes three inputs:
a non-empty string,
a pattern number which is an integer between 0 and 255 that represents a set of rules, and
a positive integer, n, which is the number of generations.
The procedure should return a string which is the result of
applying the rules generated by the pattern to the string n times.

def cellular_automaton():


Here are some examples:
print cellular_automaton('.x.x.x.x.', 17, 2)
#>>> xxxxxxx..
print cellular_automaton('.x.x.x.x.', 249, 3)
#>>> .x..x.x.x
print cellular_automaton('...x....', 125, 1)
#>>> xx.xxxxx
print cellular_automaton('...x....', 125, 2)
#>>> .xxx....
print cellular_automaton('...x....', 125, 3)
#>>> .x.xxxxx
print cellular_automaton('...x....', 125, 4)
#>>> xxxx...x
print cellular_automaton('...x....', 125, 5)
#>>> ...xxx.x
print cellular_automaton('...x....', 125, 6)
#>>> xx.x.xxx
print cellular_automaton('...x....', 125, 7)
#>>> .xxxxx..
print cellular_automaton('...x....', 125, 8)
#>>> .x...xxx
print cellular_automaton('...x....', 125, 9)
#>>> xxxx.x.x
print cellular_automaton('...x....', 125, 10)
#>>> ...xxxxx

Отредактировано frenchsasha (Июнь 2, 2012 20:44:41)

Офлайн

#6 Июнь 3, 2012 03:06:01

Unril
От: Москва
Зарегистрирован: 2012-05-27
Сообщения: 3
Репутация: +  1  -
Профиль   Отправить e-mail  

Python Помощь!!

def stirling(n, k):
    if k == 0 and n == 0:
        return 1
    if k == 0 or n == 0:
        return 0
    return k * stirling(n - 1, k) + stirling(n - 1, k - 1)
def bell(n):
    return sum(stirling(n, k) for k in range(n + 1))

Офлайн

#7 Июнь 4, 2012 00:37:48

s0rg
От:
Зарегистрирован: 2011-06-05
Сообщения: 777
Репутация: +  25  -
Профиль   Отправить e-mail  

Python Помощь!!

Unril
У вас ошибочка - для stirling(1, 1) правильный результат - 1, у вас - 2

Мой не-рекурсивный вариант:

def stirling(n, k):
# S(n, k) = k*S(n-1, k) + S(n-1, k-1)
_calc = {}

for i in xrange(n + 1):
for j in xrange(k + 1):
key = (i, j)
if (i == j) or (j == 1):
_calc[key] = 1
elif 0 < j < i:
_calc[key] = j * _calc[(i - 1, j)] + _calc[(i - 1, j - 1)]
else:
_calc[key] = 0

return _calc[(n, k)]

Офлайн

#8 Июнь 4, 2012 17:57:16

Artemsky
Зарегистрирован: 2012-06-04
Сообщения: 2
Репутация: +  0  -
Профиль   Отправить e-mail  

Python Помощь!!

Пол дня просидел пытаясь решить эту задачку, оказывается все так просто…

def is_list(p):
    return isinstance(p, list)
def deep_reverse(input):
    if not is_list(input):
        return input
    result = input[::-1]
    for i, item in enumerate(result):
        result[i] = deep_reverse(item)
    return result 
но так и не получилось сделать так чтобы исходный лист остался без изменения - пока мало знаний… Расшифруйте пожалуйста, что означает запись
input [::-1] 
и что это за процедура enumerate? и что означает такая запись цикла
for i, item in enumerate(result):
или дайте ссылку почитать…

Офлайн

#9 Июнь 4, 2012 18:18:33

reclosedev
От: Н.Новгород
Зарегистрирован: 2012-03-29
Сообщения: 870
Репутация: +  173  -
Профиль   Отправить e-mail  

Python Помощь!!

google: python enumerate
http://docs.python.org/library/functions.html#enumerate

input [::-1]
http://docs.python.org/release/2.3.5/whatsnew/section-slices.html
http://stackoverflow.com/a/509295/1052325

Отредактировано reclosedev (Июнь 4, 2012 18:19:24)

Офлайн

#10 Июнь 9, 2012 08:26:54

redstars1979
Зарегистрирован: 2012-06-07
Сообщения: 15
Репутация: +  0  -
Профиль   Отправить e-mail  

Python Помощь!!

Здравствуйте! Я совсем еще новичок в Python , и в своем новом уроке я должен перейти в Numerical, но когда я набираю такую строчку : from Numeric import *, то программа выдает синтаксис инвалид. И это при том что в linuxe стоит python 2.6.5 a в Windows7 Python 3.2 но ошибки при наборе все той же строки одинаковы может не правильная команда. книга которая я читаю С. Сюзи Python 2002

Отредактировано redstars1979 (Июнь 9, 2012 13:05:00)

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version