[英]Django returns algorithm result different to python interpreter
I have some Algorithms Bubble, insertion, sort, merge etc. 我有一些算法冒泡,插入,排序,合并等。
I have coded them into a Django website so you can input an array of numbers and it will sort them into order. 我已经将它们编码到Django网站中,因此您可以输入数字数组,它将按顺序对它们进行排序。
To test i passed in this list of numbers: 为了测试我通过了这个数字列表:
[3, 12, 5, 4, 8, 5, 1]
When I run the function in a shell the algorithm returns what I want: 当我在外壳中运行该函数时,算法将返回我想要的内容:
[1, 3, 4, 5, 5, 8, 12]
When I run it through Django the output is not what I want: 当我通过Django运行它时,输出不是我想要的:
[1, 12, 3, 4, 5, 5, 8]
I have tried both POST and GET methods. 我已经尝试了POST和GET方法。
I have tried with and without for loops. 我已经尝试过和没有for循环。
I have tried with and without CSRF_TOKENS. 我尝试过使用CSRF_TOKENS和不使用CSRF_TOKENS。
views.py views.py
from django.shortcuts import render
from django.conf import settings
from custom.bubble import maf_bubble
def algo(request):
if request.GET:
nums_list = maf_bubble(list(request.GET['numbers'].split(',')))
rtn_res = render(request, 'algorithms/sort.html', {'results' : nums_list})
return rtn_res
else:
return render(request, 'algorithms/sort.html', {})
sort.html sort.html
<div class="wrapper">
<div class="search">
<form class="navbar-form navbar-left" method="GET" action=" " style="margin:2%" >
<select name="algo_type" style="padding:5%; border-radius:5px; border: 2px solid #ccc;" placeholder="Type" >
<option value="bubble">Bubble Sort</option>
<option value="insertion"> Insertion Sort</option>
<option value="merge" selected>Merge Sort</option>
<option value="quick">Quick Sort</option>
<option value="selection">Selection Sort</option>
<option value="shell">Shell Sort</option>
</select>
<br><br>
<form class="navbar-form navbar-left" method="GET">{% csrf_token %}
<div>
<input type="text" name="numbers" autocomplete="on" placeholder="Input numbers" />
</div>
<br>
<br>
<button type="submit">Sort!</button>
</form>
</div>
<div class="results">
{{results}}
{% for res in results %}
<b>{{ res }}</b>
{% endfor %}
</div>
</div>
{% endblock %}
You're sending a list of strings, and they are being sorted as strings. 您正在发送字符串列表,并且它们被按字符串排序。 You need to convert them to ints. 您需要将它们转换为整数。
nums_list = maf_bubble(list(map(int, request.GET['numbers'].split(','))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.