Writing pseudocode with dummy value [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
An pseudocode is required to input a series of numbers from the keyboard and to ensure that they are in ascending order even though they need not be consecutive.The number may be positive or negative and will end with a dummy value of 9999.
This is a python code I wrote and it works ok,
li=[]
num=int(raw_input("Enter number"))
while num!=9999:
li.append(num)
num=int(raw_input("Enter number"))
new=0
print "Entered sequence is "
print li
j=0
while j<len(li):
for i in range(len(li)-1):
value1=li[i]
value2=li[i+1]
if (value1>value2):
new=li[i]
li[i]=li[i+1]
li[i+1]=new
j+=1
print "ordered list is "
print li
But I have problem in writing this as an algorithm.
This is my tried algorithm:
Main
li list
num integer
new=0,j=0 integer
Begin
num=INPUT num.
while num<>9999.
append num to li.
num=INPUT num.
ENDWHILE.
DISSPLAY "Entered Sequence is".
OUTPUT li.
while j<(length of li).
FOR i=0 to (length of li-2).
value1=i th element of li
value2=(i+1) th element of li
if (value1>value2):
new=value1
value1=value2
value2=new
ENDIF
END FOR
j=j+1
ENDWHILE
DISPLAY "ORDERED LIST IS"
DISPLAY li
END
END
Can I use "list" in an algorithm because I think objects as "list" do not appear in every programming language.And shouldn't algorithm be a general code.Same way is it allowed to use arrays in writing an algorithm
And Is it okay to say "value1=ith element in li"?
And how to show that I am assigning the value entered from keyboard to the variable "num"

(This was originally a comment)
You seem to miss what the point of pseudo code is. Pseudo code is neither standardized nor somewhat defined. In general it is just a code-like representation of an algorithm, while maintaining a high level and readability. You can write pseudo code in whatever form you like. Even real Python code could be considered pseudo code. That being said, there are no thing disallowed in pseudo code; you can even write prose to explain something that happens. For example in the inner-most loop, you could just write “swap value1 and value2”.
This is approximately how I would transform your Python code into pseudo-code. I tend to leave out all language specific stuff and focus just on the actual algorithmic parts.
Input:
list: Array of input numbers
FOR j = 0 to length(list):
FOR i = 0 to length(list)-1:
if list[i] > list[i+1]:
Swap list[i] and list[i+1]
OUTPUT ordered list
So is it okay to use lists, tuples, dictionaries in a pseudocode, even if they are not common to all programming languages?
Absolutely! In more complex algorithms you will even find things like “Get minimum spanning tree for XY” which would be a whole different problem for which again multiple different solutions exist. Instead of specifying a specific solution you are keeping it open to the actual implementation which algorithm is to be used for that. It usually does not matter for the algorithm you are currently describing. Maybe later when you analyze your algorithm, you might mention things like “There are algorithms known for this who can do this in O(log n)” or something, so you just use that to continue.

Related

What is the Big O efficiency of this code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
The question I was given requires me to get an output within 3 secs
The constraint given is 2<= len(a) <= 5000000 and 1 <= a[i] <= 10**9
Below is the code I have written. I belive that the Big O efficiency of this code is linear or O(n) as I am only using one for loop. Is that the case? If can it run the max input size within 3 secs?
line = input()
m = line.split()
m.sort()
smallest_diff = 10 ** 9
for i in range(len(m)-1):
diff = abs(int(m[i]) - int(m[i+1]))
if diff < smallest_diff:
smallest_diff = diff
else:
smallest_diff = smallest_diff
if i+1 > len(m):
break
print(smallest_diff)
Your runtime complexity is currently O(N log(N)), dominated by the sort call. You're correct that the main work loop takes only O(N) time. However, the input size of 5*10^6 will be close to the borderline for what Python can get done in 3 seconds; you
I actually suspect your input loading may be eating up a lot of time. That's not an asymptotics issue; input is just often pretty slow. Here are things I'd try:
Check whether the website you're submitting to allows you to use PyPy instead of regular Python. You could still submit the same code either way, but it'll probably run a lot faster in PyPy.
Replace your first 2 lines with m = map(int, input().split()). This stores a list of int instead of string. ints make your code less memory-intensive and ints are what you want to use anyway. There are some more advanced tricks you could try to make the input loading steps even faster, like using BytesIO, but I'm just mentioning for fun; you probably don't want to get into that right now.
You currently have a few other unnecessary lines of code that slow your program down slightly, but they won't affect the runtime much.
Bonus note: I don't know the exact problem you're trying to solve, but your code probably has a bug where you sort the data. Your m is a list of strings, not ints, so for example your code would consider this array to be already sorted: ['10', '3'] (because the string '10' comes before the string '3'). This bug would be fixed as a side effect of my suggestion (2) above, since if you store the data as ints then you'd instead get [3, 10] which I'm pretty sure is what you're intending.

I need help figuring what wrong with my code! ('int' issue) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
i am having an issue figuring out why my code is wrong.
def draw_poly(t, n, size):
for s in (n):
t.forward(sz)
t.left(45)
draw_poly (liz, 8, 50)
I am trying to make a octogon but it keeps on giving me an "'int' object is not iterable" error.
If you could help i would be forever grateful, Thanks.
The for-loop:
for s in (n):
Expects n to be some sort of iterable: a list, tuple, dictionary, etc, but you are passing an integer (int) - hence the error.
If you want s to take the values 0, 1, 2, ..., n then you should use the range() function to produce an iterable sequence of the numbers up to the number passed into it.
Therefore, what your probably want is:
for s in range(n):
which will allow you to work with an integer variable s in that code block.
If you want to debug your code, it often helps to print out the values of variables to check they are evaluating to what you think they should be.
For instance,
for i in range(4):
print(i)
gives:
0
1
2
3
which is to be expected.
The correct int iterable would be range(int), so, use this: for s in range(n):
For the future using of range(): this function creates a list of iterable int objects. In some cases using of xrange() is better, especially for large loops.
I.e. range(1000000000) creates a huge object in memory while xrange(1000000000) does not, though it works in a similar way giving you int numbers one by one.

To better understand recursion [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am making an attempt to learn recursion better so I have been practicing some problems.
A common problem is flatten an list of lists to a single list. For example
[3,4,[1,2]] so the desired result will be [3,4,1,2].
The way I am approaching the problem is:
is 0 element a list - no
is 1 element a list - no
is 2 element a
list - yes
call the function again and do tests again
My base case will be to return if element is not a list.
Is there a better approach to understand recursion better?
Your approach is in the right direction, but you should not check more than the first element. In general - a "pure" recursive solution will only have to look at the "head" of the list (first element), and the "tail" (list[1:]).
something like (python like pseudo code):
def flatten(l):
if len(l) == 0:
return []
if isinstance(l[0], list):
left = flatten(l[0])
else:
left = [l[0]]
return left + flatten(l[1:])
You example is certainly one that works however it may be slightly too simple for you to get a full understanding. I found that maze problems were the most helpful in me understanding recursive problems. The main preface is there is a 2x2 array consisting of two different values. One value denotes a wall within the maze and the other value denotes empty space. Your job would be to traverse through the maze using recursion. Here is an example problem and solution:
https://www.cs.bu.edu/teaching/alg/maze/
Hope this helps!!
You should.
Create a new list (passed) before calling function. Call function.
Loop through the old one and check if the type of list if so, then call function recursive.
else add element to passed list.
aList = [3,4,[1,2]]
def flatten(inList,outList):
for elem in inList:
if isinstance(elem,list):
flatten(elem,outList)
else:
outList.append(elem)
bList = list()
flatten(aList,bList)
print bList

Python - "slashList = [i for i, ind in enumerate(start) if ind == '/']" [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I just started to learn programming 4 weeks ago. I read the book "Learn Python the hard way" and I am currently working through "Learn Raspberry Pi programming with Python". The code that I wrote above completely confuses me and I can't seem to wrap my head around it. The book states it lists the indices of slashes (I am working on a web bot). I just have never seen a format like this in a for loop. Why is there a variable in front of the for? Please explain (in english please:D).
Thanks,
Michael
That is a list comprehension, a more compact way of running a loop to build up a list in Python.
The long way of writing this would be:
SlashList = []
for i, ind in enumerate(start):
If ind == '/':
SlashList.append(i)
Where ind is the name for the value of the field in list 'start' and i is ind's index (or position in the list)
And 'ind' and 'start' being particularly unhelpful variable names likely adds to the confusion in understanding the line :-)
A "for loop" inside brackets is called "list comprehension".
Here it iterates over enumerate(start) which is an iterator yielding a tuple of (index, item) for each item of the iterable given.
This iterator is iterated over, putting index into i and the character into ind (which is confusing, variable-wise). For each item, if it is a /, the index is taken over into the final list so that, at the end, the list consists of all indexes of the slashes in the string(?) start.
It does the same thing as the following code:
slashList = []
i = 0
for ind in start:
if ind == '/':
slashList.append(i)
i += 1
It uses a few tricks to squeeze that all on to one line. The first is called a list comprehension. It lets you make a list without breaking out a for loop and if statement onto different lines. The second is the enumerate built-in function. It lets you get the index i of every item in an iterable like start at the same time as the item (here, assigned to ind) itself.

Python -- Morse Code Translation through a binary tree [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm writing a program that will create a binary tree of the Morse Code alphabet (as well as a period and an apostrophe), and which will then read a line of Morse Code and translate it into English. (Yes, I know that a look-up table would be easier, but I need to sort out my binary trees). I think a good bit of my problem is that I want to put the values into the tree in alphabetical order, rather than by symbol order. But surely there must be a way to do that? Because if I had a million such values that weren't numeric, I wouldn't need to sort them into the simplest order for insertion...right?
It's reading from a text file where each line has one sentence in Morse Code.
- .... .. ... .. ... ..-. ..- -. .-.-.- for example, which is "This is fun."
1 space between symbols means it's a new letter, 2 spaces means it's a new word.
As it stands, I'm getting the output ".$$$" for that line given above, which means it's reading a period and then getting an error which is symbolized by ('$$$'), which is obviously wrong...
Like I said before, I know I'm being complicated, but surely there's a way to do this without sorting the values in my tree first, and I'd like to figure this out now, rather than when I'm in a time crunch.
Does anyone have any insight? Is this something so horribly obvious that I should be embarrassed for asking about it?
Welcome to SO and thanks for an interesting question. Yes, it looks to me like you're overcomplicating things a bit. For example, there's absolutely no need to use classes here. You can reuse existing python data structures to represent a tree:
def add(node, value, code):
if code:
add(node.setdefault(code[0], {}), value, code[1:])
else:
node['value'] = value
tree = {}
for value, code in alphabet:
add(tree, value, code)
import pprint; pprint.pprint(tree)
This gives you a nested dict with keys ., -, and value which will be easier to work with.

Categories

Resources