小编Blc*_*ght的帖子

如何像计算机科学家一样思考

因此,正如标题所希望的那样,这是在所述书中的一个例子.我还是编程新手,调试困难.对此表示欢迎任何批评,特别是如果它显示更有效的编码方式; 请记住,我仍然是新手,所以如果你给我一个新的内置功能或某些东西,我很可能不知道你指的是什么.

因此,本练习的目的是编写一个函数,给它三个参数,以确定这三个参数是否形成一个三角形.这是我的代码:

def is_triangle(a,b,c):
    num_list = [a,b,c]
    biggest = max(num_list)
    other_two = num_list.remove(biggest)
    sum_of_two = sum(other_two)

    if sum_of_two > biggest:
        print 'Congrats, %d, %d, and %d form a triangle!' % (a,b,c)
    elif sum_of_two == biggest:
        print 'That forms a degenerate triangle!'
    else:
        print 'That does\'t make any sort triangle... >:['


def sides():
    side1 = raw_input('Please input side numero Juan: ')
    side2 = raw_input('Now side two: ')
    side3 = raw_input('...aaaannnd three: ')
    import time
    time.sleep(1)
    print 'Thanks >:]'
    side1 = …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 nonetype

7
推荐指数
1
解决办法
939
查看次数

在Python中使用带有多处理的click.progressbar

我有一个庞大的列表,我需要处理,这需要一些时间,所以我把它分成4件,并用一些功能多处理每件.使用4个内核运行仍然需要一些时间,所以我想我会在函数中添加一些进度条,以便它可以告诉我处理列表时每个处理器的位置.

我的梦想是拥有这样的东西:

erasing close atoms, cpu0  [######..............................]  13%
erasing close atoms, cpu1  [#######.............................]  15%
erasing close atoms, cpu2  [######..............................]  13%
erasing close atoms, cpu3  [######..............................]  14%
Run Code Online (Sandbox Code Playgroud)

每个条随着函数循环的移动而移动.但相反,我得到一个持续的流程:

在此输入图像描述

等等,填满我的终端窗口.

这是调用函数的主要python脚本:

from eraseCloseAtoms import *
from readPDB import *
import multiprocessing as mp
from vectorCalc import *

prot, cell = readPDB('file')
atoms = vectorCalc(cell)

output = mp.Queue()

# setup mp to erase grid atoms that are too close to the protein (dmin = 2.5A)
cpuNum = 4
tasks = len(atoms)
rangeSet = …
Run Code Online (Sandbox Code Playgroud)

python numpy multiprocessing python-2.7 python-click

7
推荐指数
2
解决办法
3913
查看次数

如何在Python中使用复选框

我试图在我的HTML中使用复选框,将这些复选框返回到我的python后端,然后如果单击该框,则递增三个计数器.

现在我的HTML如下,工作正常:

<form method="post">
    <input type="checkbox inline" name="adjective" value="entertaining">Entertaining
    <input type="checkbox inline" name="adjective" value="informative">Informative
    <input type="checkbox inline" name="adjective" value="exceptional">Exceptional
</form>
Run Code Online (Sandbox Code Playgroud)

然后在我的python后端我有以下内容:

def post(self):
    adjective = self.request.get('adjective ')

    if adjective :
        #somehow tell if the entertaining box was checked
        #increment entertaining counter
        #do the same for the others
Run Code Online (Sandbox Code Playgroud)

html python checkbox google-app-engine webapp2

6
推荐指数
1
解决办法
1万
查看次数

Python中的类常量字典

我正在构建一个具有类变量字典的模块:

class CodonUsageTable:
        CODON_DICT={'TTT': 0, 'TTC': 0, 'TTA': 0, 'TTG': 0, 'CTT': 0,
        'CTC': 0, 'CTA': 0, 'CTG': 0, 'ATT': 0, 'ATC': 0,
        'ATA': 0, 'ATG': 0, 'GTT': 0, 'GTC': 0, 'GTA': 0,
        'GTG': 0, 'TAT': 0, 'TAC': 0, 'TAA': 0, 'TAG': 0,
        'CAT': 0, 'CAC': 0, 'CAA': 0, 'CAG': 0, 'AAT': 0,
        'AAC': 0, 'AAA': 0, 'AAG': 0, 'GAT': 0, 'GAC': 0,
        'GAA': 0, 'GAG': 0, 'TCT': 0, 'TCC': 0, 'TCA': 0,
        'TCG': 0, 'CCT': 0, 'CCC': 0, 'CCA': …
Run Code Online (Sandbox Code Playgroud)

python dictionary class

6
推荐指数
1
解决办法
8887
查看次数

在多处理池中使用时,不会正确引发自定义异常

我正在观察Python 3.3.4中我希望帮助理解的行为:为什么在正常执行函数时正确引发异常,而不是在函数池中执行函数时?

import multiprocessing

class AllModuleExceptions(Exception):
    """Base class for library exceptions"""
    pass

class ModuleException_1(AllModuleExceptions):
    def __init__(self, message1):
        super(ModuleException_1, self).__init__()
        self.e_string = "Message: {}".format(message1)
        return

class ModuleException_2(AllModuleExceptions):
    def __init__(self, message2):
        super(ModuleException_2, self).__init__()
        self.e_string = "Message: {}".format(message2)
        return

def func_that_raises_exception(arg1, arg2):
    result = arg1 + arg2
    raise ModuleException_1("Something bad happened")

def func(arg1, arg2):

    try:
        result = func_that_raises_exception(arg1, arg2)

    except ModuleException_1:
        raise ModuleException_2("We need to halt main") from None

    return result

pool = multiprocessing.Pool(2)
results = pool.starmap(func, [(1,2), (3,4)])

pool.close()
pool.join() …
Run Code Online (Sandbox Code Playgroud)

python exception python-3.x

6
推荐指数
1
解决办法
1673
查看次数

启动活动的快捷方式

我有一个应用程序,以下列方式创建一个快捷方式:

Intent shortcutIntent = new Intent(this, MYWEBVIEW.class);
String fileHtml = trovaHtml(path);
shortcutIntent.putExtra("appToLaunch", appId);
shortcutIntent.putExtra("fileHtml", fileHtml);
shortcutIntent.setAction(Intent.ACTION_VIEW);

Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, dirAppName);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
    Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
this.sendBroadcast(addIntent);
Run Code Online (Sandbox Code Playgroud)

我知道这段代码已被弃用但让我们忘了它.......

MYWEBVIEW不是我的应用程序的主要活动,是打开离线html页面的webview,并且此html文件的路径在额外值"fileHtml"内.

当我点击快捷方式时,我收到此错误:

08-08 14:15:37.907:ERROR/Launcher(165):启动器没有启动Intent的权限{act = android.intent.action.VIEW flg = 0x10000000 cmp = market.finestraprincipale/.MyAppActivity bnds = [3,217] ] [77,296](有额外的)}.确保为相应的活动创建MAIN intent-filter或使用此活动的导出属性.tag = ShortcutInfo(title = myFile)intent = Intent {act = android.intent.action.VIEW flg = 0x10000000 cmp = market.finestraprincipale/.MYWEBVIEW bnds = [3,217] [77,296](有额外内容)}

08-08 14:15:37.907:ERROR/Launcher(165):java.lang.SecurityException:Permission Denial:start Intent {act = android.intent.action.VIEW flg = 0x10000000 cmp = …

permissions android android-intent

5
推荐指数
1
解决办法
3992
查看次数

在python v.2中交换两个不同长度的列表?

我正在尝试编写一个Python函数,它将两个列表作为参数并对它们进行交错.应保留组件列表的顺序.如果列表的长度不同,则较长列表的元素应最终位于结果列表的末尾.例如,我想把它放在Shell中:

interleave(["a", "b"], [1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)

得到这个:

["a", 1, "b", 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

如果你能帮助我,我会很感激.

python python-2.7

5
推荐指数
1
解决办法
1619
查看次数

python线程应用程序错误到许多参数

这个python源代码有什么问题?

import threading
import subprocess as sub

def ben(fil):
    pr = sub.Popen(fil,stdout=sub.PIPE,stderr=sub.PIPE)
    output, errors = pr.communicate()
    print output

theapp = '''blender
            blender-softwaregl'''.split()
print theapp

for u in theapp:
    print u
    tr = threading.Thread(target=ben, args=(u))
    tr.daemon = True
    tr.start()
Run Code Online (Sandbox Code Playgroud)

错误是:

['blender', 'blender-softwaregl']
blender
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "/usr/local/lib/python2.7/threading.py", line 504, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: ben() takes exactly 1 argument (7 given)

blender-softwaregl
Exception in thread Thread-2:
Traceback …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-2.7

5
推荐指数
1
解决办法
5878
查看次数

双向链接列表迭代器python

我正在构建一个双向链表,我正在努力在PYTHON中构造一个双向链表迭代器方法.

到目前为止这是我的代码

class DoubleListNode:
    def __init__(self,data):
        self.data=data
        self.prev = None
        self.next= None

class ListIterator:
    def __init__(self):
        self._current = self.head

    def __iter__(self):
        return self

    def next(self):
        if self.size == 0 :
            raise StopIteration
        else:
            item = self._current.data
            self._current=self._current.next
            return item

class DoublyLinkedList:
    def __init__(self):
        self.head= None
        self.tail= None
        self.size = 0

    def add(self,data):
        newnode= DoubleListNode(data)
        self.size+=1
        if self.head is None:
            self.head = newnode
            self.tail = self.head
        elif data < self.head.data: # before head
            newnode.next = self.head
            self.head.prev= newnode
            self.head= …
Run Code Online (Sandbox Code Playgroud)

python

5
推荐指数
1
解决办法
1万
查看次数

Python 2.7 - 使用字典从文本文件中查找并替换为新的文本文件

我是编程的新手,过去几个月我一直在闲暇时间学习python.我决定尝试创建一个小脚本,在文本文件中将美国拼写转换为英语拼写.

在过去的5个小时里,我一直在尝试各种各样的事情,但最终想出的东西让我更接近我的目标,但并不完全在那里!

#imported dictionary contains 1800 english:american spelling key:value pairs. 
from english_american_dictionary import dict


def replace_all(text, dict):
    for english, american in dict.iteritems():
        text = text.replace(american, english)
    return text


my_text = open('test_file.txt', 'r')

for line in my_text:
    new_line = replace_all(line, dict)
    output = open('output_test_file.txt', 'a')
    print >> output, new_line

output.close()
Run Code Online (Sandbox Code Playgroud)

我确信有一个更好的方法可以解决问题,但对于这个脚本,这里是我遇到的问题:

  • 在输出文件中,每行都写入行,并在它们之间有换行符,但原始的test_file.txt没有.本页底部显示的test_file.txt的内容
  • 只有一行中美国拼写的第一个实例转换为英语.
  • 我真的不想在追加模式下打开输出文件,但在这段代码结构中无法弄清楚'r'.

任何帮助赞赏这个渴望新手!

test_file.txt的内容是:

I am sample file.
I contain an english spelling: colour.
3 american spellings on 1 line: color, analyze, utilize.
1 american spelling on 1 line: …
Run Code Online (Sandbox Code Playgroud)

python python-2.7

5
推荐指数
1
解决办法
9025
查看次数