小编Bel*_*gor的帖子

如何在Python中打破while循环?

我必须为我的comp课程制作这个游戏,我无法弄清楚如何突破这个循环.看,我必须通过滚动更大的数字来对抗"计算机",看看谁有更高的分数.但我无法弄清楚如何从轮到我"打破",并转向计算机转向.我需要"Q"(退出)来表示计算机开始转动,但我不知道该怎么做.

ans=(R)
while True:
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore
    if ans=='Q':
        print("Now I'll see if I can break your score...")
        break
Run Code Online (Sandbox Code Playgroud)

python break while-loop

23
推荐指数
4
解决办法
13万
查看次数

计算RDD中的行数

我正在使用带有java的spark,我有一个500万行的RDD.是否有一个sollution,允许我计算我的RDD的行数.我试过RDD.count()但是需要很多时间.我见过我可以使用这个功能fold.但我没有找到这个函数的java文档.你能告诉我如何使用它或给我看另一个解决方案来获取我的RDD的行数.

这是我的代码:

JavaPairRDD<String, String> lines = getAllCustomers(sc).cache();
JavaPairRDD<String,String> CFIDNotNull = lines.filter(notNull()).cache();
JavaPairRDD<String, Tuple2<String, String>> join =lines.join(CFIDNotNull).cache();

double count_ctid = (double)join.count(); // i want to get the count of these three RDD
double all = (double)lines.count();
double count_cfid = all - CFIDNotNull.count();
System.out.println("********** :"+count_cfid*100/all +"% and now : "+ count_ctid*100/all+"%");
Run Code Online (Sandbox Code Playgroud)

谢谢.

java apache-spark

19
推荐指数
2
解决办法
4万
查看次数

生成给定模式的随机文本字符串

我需要生成特定格式的随机文本字符串.想要一些想法,以便我可以用Python编写代码.格式为<8位数> <15个字符串>.

python string random

17
推荐指数
3
解决办法
4万
查看次数

(Python)ValueError:路径中找不到程序点

我有以下问题:我在xUbuntu操作系统上,我试图在Flask应用程序中使用networkx,我有以下代码:

.....
import networkx as nx
......
# Creating and initializing graph object which is networkx object
hosts_graph = get_networkx_graph_object()

# Variable 'coord' where the coordinates for each node will be stored
coord = nx.pygraphviz_layout(hosts_graph, prog = 'dot')
Run Code Online (Sandbox Code Playgroud)

最后一行是411行.我收到以下错误:

File "/home/kiril/Documents/workfolder/omeganoc-sprint/onoc/omeganoc/grapher.py", line 411, in grouping_method
    coord = nx.pygraphviz_layout(hosts_graph, prog = 'dot')
  File "/usr/local/lib/python2.7/dist-packages/networkx-1.7-py2.7.egg/networkx/drawing/nx_agraph.py", line 264, in pygraphviz_layout
    A.layout(prog=prog,args=args)
  File "/usr/local/lib/python2.7/dist-packages/pygraphviz-1.1-py2.7-linux-x86_64.egg/pygraphviz/agraph.py", line 1301, in layout
    data=self._run_prog(prog,' '.join([args,"-T",fmt]))
  File "/usr/local/lib/python2.7/dist-packages/pygraphviz-1.1-py2.7-linux-x86_64.egg/pygraphviz/agraph.py", line 1248, in _run_prog
    runprog=self._get_prog(prog)
  File "/usr/local/lib/python2.7/dist-packages/pygraphviz-1.1-py2.7-linux-x86_64.egg/pygraphviz/agraph.py", line 1236, in _get_prog
    raise …
Run Code Online (Sandbox Code Playgroud)

python graphviz networkx pygraphviz xubuntu

15
推荐指数
3
解决办法
2万
查看次数

查找范围内的最接近数字

我想到了一个问题如下:

我们有一个大小为n的整数数组A,我们有测试用例t,在每个测试用例中我们给出一个数字m和一个范围[s,e],即我们给出s和e,我们必须找到最接近的该数组范围内的m数(A [s] -A [e]).

您可以假设索引的数组从1到n.

例如:

  A = {5, 12, 9, 18, 19}
  m = 13
  s = 4 and e = 5
Run Code Online (Sandbox Code Playgroud)

所以答案应该是18.

约束:

n<=10^5
t<=n
Run Code Online (Sandbox Code Playgroud)

我能想到的只是针对每个测试用例的O(n)解决方案,我认为存在更好的解决方案.

algorithm complexity-theory

13
推荐指数
1
解决办法
1259
查看次数

此语言级别不支持多次捕获

所以我想输入一个数字,然后输入一个人或其他人的名字.这没有问题,但为什么我不能在1个块中放置2个错误异常?

while (true) {
    try {
        int id = Integer.parseInt( reader.readLine() );
        String name = reader.readLine();

        if (name.equals("")) {
            break;
        }

        map.put(name, id);
    } catch (NumberFormatException | IOException e) {
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我试图打印我的价值时,我明白了 NumberFormatException

for (Map.Entry<Integer, String> pair: map.entrySet()) {
    int id = pair.getKey();
    String name = pair.getValue();
    System.out.println(id + " " + name);
}
Run Code Online (Sandbox Code Playgroud)

java exception-handling hashmap

12
推荐指数
3
解决办法
9377
查看次数

json.dump - UnicodeDecodeError:'utf8'编解码器无法解码位置0的字节0xbf:无效的起始字节

我有一个data我存储的字典:

  • key - 活动的ID

  • value- 此事件的名称,其中value是UTF-8字符串

现在,我想将此地图写入json文件.我试过这个:

with open('events_map.json', 'w') as out_file:
    json.dump(data, out_file, indent = 4)
Run Code Online (Sandbox Code Playgroud)

但这给了我错误:

UnicodeDecodeError:'utf8'编解码器无法解码位置0的字节0xbf:无效的起始字节

现在,我也尝试过:

with io.open('events_map.json', 'w', encoding='utf-8') as out_file:
   out_file.write(unicode(json.dumps(data, encoding="utf-8")))
Run Code Online (Sandbox Code Playgroud)

但这会引发同样的错误:

UnicodeDecodeError:'utf8'编解码器无法解码位置0的字节0xbf:无效的起始字节

我也尝试过:

with io.open('events_map.json', 'w', encoding='utf-8') as out_file:
    out_file.write(unicode(json.dumps(data, encoding="utf-8", ensure_ascii=False)))
Run Code Online (Sandbox Code Playgroud)

但这会引发错误:

UnicodeDecodeError:'ascii'编解码器无法解码位置3114中的字节0xbf:序数不在范围内(128)

关于如何解决这个问题的任何建议?

编辑: 我相信这是导致我这个问题的路线:

> data['142']
'\xbf/ANCT25'
Run Code Online (Sandbox Code Playgroud)

编辑2:data变量被从文件中读取.所以,从文件中读取后:

data_file_lines = io.open(file_name, 'r', encoding='utf8').readlines()
Run Code Online (Sandbox Code Playgroud)

然后我做:

with io.open('data/events_map.json', 'w', encoding='utf8') as json_file:
        json.dump(data, json_file, ensure_ascii=False)
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

TypeError:必须是unicode,而不是str

然后,我尝试使用数据字典执行此操作:

for tuple in sorted_tuples (the …
Run Code Online (Sandbox Code Playgroud)

python unicode encoding json utf-8

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

AttributeError:解析JSON字典值时,'unicode'对象没有属性'values'

我有以下JSON字典:

{
 u'period': 16, u'formationName': u'442', u'formationId': 2, 
 u'formationSlots': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0, 0, 0], 
 u'jerseyNumbers': [1, 20, 3, 15, 17, 5, 19, 6, 18, 25, 10, 2, 4, 12, 16, 22, 24, 
                    34], 
 u'playerIds': [23122, 38772, 24148, 39935, 29798, 75177, 3860, 8505, 
               26013, 3807, 34693, 18181, 4145, 23446, 8327, 107395, 29762, 254558], 
 u'captainPlayerId': 29798, 
 u'startMinuteExpanded': 0, 
 u'endMinuteExpanded': 82, 
 u'formationPositions': [{u'horizontal': 5.0, u'vertical': 0.0}, 
     {u'horizontal': 1.0, u'vertical': 2.5}, …
Run Code Online (Sandbox Code Playgroud)

python json dictionary

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

关于使用NSOpenPanel的详细说明

我希望能够在Swift中打开图像.这是我的第一个Swift项目.

@IBAction func SelectFileToOpen(sender: NSMenuItem) {
    var openPanel = NSOpenPanel();
    openPanel.allowsMultipleSelection = false;
    openPanel.canChooseDirectories = false;
    openPanel.canCreateDirectories = false;
    openPanel.canChooseFiles = true;
    let i = openPanel.runModal();
    if(i == NSOKButton){
        print(openPanel.URL);
        var lettersPic = NSImage(contentsOfURL: openPanel.URL!);
        imageView.image = lettersPic;

    }
}
Run Code Online (Sandbox Code Playgroud)

NSLog使用打开面板时的输出

Optional(file:///Users/ethansanford/Desktop/BigWriting.png)
fatal error: unexpectedly found nil while unwrapping an Optional value
Run Code Online (Sandbox Code Playgroud)

如何允许用户打开感兴趣的png文件.当我在代码中指定相同的文件时一切正常.我的一个示例,指示在不使用打开文件面板并充当用户的情况下在代码中打开哪个文件:

let pictureURl = NSURL(fileURLWithPath: "///Users/ethansanford/Desktop/BigWriting.png");
var lettersPic = NSImage(contentsOfURL: pictureURl!);
imageView.image = lettersPic; 
Run Code Online (Sandbox Code Playgroud)

我的网址格式有问题吗?任何帮助,将不胜感激.

swift

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

从Spark中的压缩中读取整个文本文件

我有以下问题:假设我有一个包含压缩目录的目录,其中包含存储在HDFS上的多个文件.我想创建一个包含T类型对象的RDD,即:

context = new JavaSparkContext(conf);
JavaPairRDD<String, String> filesRDD = context.wholeTextFiles(inputDataPath);

JavaPairRDD<String, String> filesRDD = context.wholeTextFiles(inputDataPath);
JavaRDD<T> processingFiles = filesRDD.map(fileNameContent -> {
    // The name of the file
    String fileName = fileNameContent._1();
    // The content of the file
    String content = fileNameContent._2();

    // Class T has a constructor of taking the filename and the content of each
    // processed file (as two strings)
    T t = new T(content, fileName);

    return t;
});
Run Code Online (Sandbox Code Playgroud)

现在什么时候inputDataPath是一个包含文件的目录,这完全正常,即它是这样的:

String inputDataPath =  "hdfs://some_path/*/*/"; // because …
Run Code Online (Sandbox Code Playgroud)

java compression hadoop hdfs apache-spark

10
推荐指数
1
解决办法
9486
查看次数