Pseudocode with calling function for multiple test scores letter grade? - pseudocode

how do I call this function for multiple test scores in pseudocode? So far I have:
Function String determineGrade(Real number)
if score >= 90
return "A"
else if score >= 80
return "B"
else if score >= 70
return "C"
else if score >= 60
return "D"
else
return "F"
end if
End function
How will I call this function so it will display 10 different test letter grade with 10 different inputs i recieved from user in pseudocode? Thanks

It depends if you are getting grades from array or randomly creating them. For array for example you can do this.
Function String name() // type can be void if you are printing
for i=0, i<10, i++
determineGrade(number[i])

Related

How to create a function with zipWithIndex that returns an Int from a List[Int] in scala

I'm trying to use zipWithIndex to index of the first negative value in my List by creating a method function that takes a List[Int] and will return an Int or an option[Int] for me to use. First, I created the list and the function with zipWithIndex but I keep getting type mismatch error:
val list = List(-2,-1,2,3,4)
def getNegativeIndex(xs: List[Int]): Int = {
for ((x, count) <- xs.zipWithIndex if x < 0) yield(count)
}
and this is the error I keep getting:
type mismatch;
found : List[Int] => Int
required: Int
My aim is to index off the first negative value of the List "list"
i.e my result should be getNegativeIndex(list) == 0 using the list I provided since the 1st element -2 is at index 0
pls, what do I need to add to the above function or remove to achieve my goal
In order for getNegativeIndex(list) to return a single integer and your desired value you need to only return the headOption of the list that your for-comprehension generates.
The current for-comprehension is equivalent to
xs.zipWithIndex.filter(_._1 < 0).map(_._2). So you can either do this
xs.zipWithIndex.filter(_._1 < 0).map(_._2).headOption
Or add the headOption to your comprehension like this
(
for ((x, count) <- xs.zipWithIndex if x < 0) yield(count)
).headOption
The result will be the same, i.e. the function returns the first index of a negative number in the list or None if all are non-negative. You could instead use .head to get an integer directly but be aware that it will throw an exception if the list doesn't contain any negative number or is empty.

Trouble with Return Values

I am taking a lesson on codecademy in which I am currently stuck do not know how to proceed - it is regarding return values.
The instructions are:
Write a method that takes an integer as an argument, and returns that integer times ten. Call times_ten in your code after you define it and print out its return value.
What is given in the script is:
def times_ten(integer)
# your code here
end
# call times_ten here
This is the example it gives but I am having a hard time understanding:
def first_squares(number_of_squares)
squares = []
idx = 0
while idx < number_of_squares
squares.push(idx * idx)
idx = idx + 1
end
return squares
end
puts("How many square numbers do you want?")
number_of_squares = gets.to_i
squares = first_squares(number_of_squares)
idx = 0
while idx < squares.length
puts(squares[idx])
idx = idx + 1
end
Thanks for your help
It should be:
def ten_times(n)
n*10 # you don't have to use 'return' explicitly
end
ten_times(n) -- but put in an actual integer instead of n (or maybe you have to puts or print it, depending on what they want)
Your example is not really related to your outcome.
The example script should be like this:
def ten_times(integer)
# integer * 10 #for implicit return
return integer * 10 #for explicit return
end
print ten_times(any number you want goes in here)
You can run the following code at www.rubyplus.biz:
Implicit return:
def times_ten(integer)
integer * 10
end
p times_ten(1)
Explicit return:
def times_ten(integer)
return integer * 10
end
p times_ten(2)

Recursive solution to finding patterns

I was solving a problem on recursion which is to count the total number of consecutive 8's in a number. For example:
input: 8801 output: 2
input: 801 output: 0
input: 888 output: 3
input: 88088018 output:4
I am unable to figure out the logic of passing the information to the next recursive call about whether the previous digit was an 8.
I do not want the code but I need help with the logic. For an iterative solution, I could have used a flag variable, but in recursion how do I do the work which flag variable does in an iterative solution. Also, it is not a part of any assignment. This just came to my mind because I am trying to practice coding using recursion.
A typical solution to this would be to add a new parameter to your function to pass along the "flag" state. This parameter is usually called an accumulator. If you're using a language that allows for nested functions, you often want to define an outer function that takes the actual parameters, then an inner, recursive function with an accumulator as a parameter. There's an example in Scheme here.
you can scan through your number digit by digit with this function
int totalConsecutive8(int digit, boolean last)
while boolean last indicate whether the last digit (which mean digit - 1) is 8 or not.
For example, in the last example 88088018, starting at digit 0, boolean last is false -> digit 1, as the last digit is 8, so last is true ...
Code in Java
public int numberOfConsecutive8(int val){
String number = "" + val;
return totalConsecutive8(number, 0, false, false);
}
public int totalConsecutive8(String number, int digit, boolean last, boolean first){
if(digit == number.length()){
return 0;
}
int result = 0;
if(number.charAt(digit) == '8'){
if(last){
if(first){
result += 2 + totalConsecutive8(number, digit + 1, true, false);
}else{
result += 1 + totalConsecutive8(number, digit + 1, true, false);
}
}else{
result += totalConsecutive8(number, digit + 1, true, true);
}
}else{
result += totalConsecutive8(number, digit + 1, false, false);
}
return result;
}
Barmar suggested approach:
int totalConsecutive8(int number, boolean last , boolean first){
if(number == 0){
return 0;
}
int result = 0;
if(number % 10 == 8){
if(last){
if(first){
result += 2 + totalConsecutive8(number/10, true , false){
}else{
result += 1 + totalConsecutive8(number/10, true , false){
}
} else{
result += totalConsecutive8(number/10, true , true){
}
}else{
result += totalConsecutive8(number/10, false , false){
}
return result;
}
here pseudo code for the above problem :-
int max = 0;
void cal_eight(char ch[],int i,int count) {
if(ch[i]=='\0') {
max = maximum(max,count);
}
else if(ch[i]=='8') {
cal_eight(ch,i+1,count+1);
}
else {
max = maximum(max,count);
cal_eight(ch,i+1,0);
}
}
call :- cal_eight(ch,0,0)
As you are focusing on recursion I'd mention that one of its specifics and benefits that there is no need at all to pass any additional parameter or count calls.
You perform call of your function from inside of its own with modified argument - say the string minus one digit which you check in your function - and then call it again until the string becomes empty.
May be multiple times - nested calls.
[UPDATE]
Below is the example in Python, verbose fore more readability.
We call our function with string, current chain of consecutive 8s which is flushed if the 1st char of current string is not '8' (which, and already known total cosecutive 8s
def f8_trace(s, chainlen=0, total=0, indent=0):
print ' '*indent, "invoked with s='%s', chainlen=%d, total=%d" % (s,chainlen, total)
if len(s) == 0:
if chainlen>1:
total += chainlen
retval = total
else:
if s[0] == '8':
chainlen += 1
else:
if chainlen>1:
total += chainlen
chainlen = 0
retval = f8_trace(s[1:],chainlen,total,indent+1)
print ' '*indent, 'returns %d' % (retval)
return retval
s = 'abc888d88e8f888'
print f8_trace( s )
Output:
invoked with s='abc888d88e8f888', chainlen=0, total=0
invoked with s='bc888d88e8f888', chainlen=0, total=0
invoked with s='c888d88e8f888', chainlen=0, total=0
invoked with s='888d88e8f888', chainlen=0, total=0
invoked with s='88d88e8f888', chainlen=1, total=0
invoked with s='8d88e8f888', chainlen=2, total=0
invoked with s='d88e8f888', chainlen=3, total=0
invoked with s='88e8f888', chainlen=0, total=3
invoked with s='8e8f888', chainlen=1, total=3
invoked with s='e8f888', chainlen=2, total=3
invoked with s='8f888', chainlen=0, total=5
invoked with s='f888', chainlen=1, total=5
invoked with s='888', chainlen=0, total=5
invoked with s='88', chainlen=1, total=5
invoked with s='8', chainlen=2, total=5
invoked with s='', chainlen=3, total=5
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
returns 8
8
Here's an example in Haskell, a language often associated with recursive approaches.
xxs stands for the string, x and xs loosely mean, "first item" and "the rest" (so after we check x, we pass xs, the rest of the string, to the next function call).
previous set as True means the previous digit was an 8. I hope the rest of the code may seem more straight forward and self-explanatory. The guards, |, are like imperative "if" clauses (e.g., if previous then ...).
f xxs first8 previous count
| null xxs = count
| previous = if x == 8
then f xs 0 True (count + first8 + 1)
else g
| otherwise = if x == 8
then f xs 1 True count
else g
where x:xs = xxs
g = f xs 0 False count
Output:
*Main> f [8,0,1] 0 False 0
0
*Main> f [8,8,8] 0 False 0
3
*Main> f [8,8,0,8,8,0,1,8] 0 False 0
4

pseudocode function to return two results for processing a tree

I'm trying to write a pseudocode for a recursive function that should process a binary tree. But the problem is that the function should return two variables. I know that functions are supposed to return on variable, and for more return values they should use list, array or vector, but I don't know how to present it as a pseudocode.
Does it look correct for a pseudocode?
function get_min(node *p)
begin
if (p==NULL) then
return list(0,0);
else
(vl,wl) = get_min(p->left)
(vr,wr) = get_min(p->right)
if (vl > vr) then
return list(vr + p->cost, 1)
else
return list(vl + p->cost, 0)
end if
end if
end function
Since it's pseudo-code, just about anything goes.
However, I'd rather go for omitting "list":
return (0, 0)
return (vr + p->cost, 1)
return (vl + p->cost, 0)
There doesn't seem to be any real benefit to putting "list" there - the (..., ...) format pretty clearly indicates returning two values already - there's no need to explicitly say you're returning them in a list.
Side note: You mention list, array or vector, but pair is another option in some languages, or wrapping the two in an object (typically giving the advantage of compile-time type checking - not really applicable in pseudo-code, obviously).
You could consider replacing "list" with "pair" instead of removing it if you wish to make it clear that the function only ever returns exactly 2 values.
If you pass parameters as reference , then there is no need to use lists as #Dukeling suggested .
void function get_min(node *p , int *cost , int * a)
begin
if (p==NULL) then
*cost =0 ; *a =0 ; return ;
else
get_min(p->left ,vl ,vw)
get_min(p->right , vr , wr)
if (vl > vr) then
*cost = vl + p->cost , *a =0 ; return;
else
*cost = vl + p->cost , *a =0 ; return ;
end if
end if
end function

What is the best algorithm to find whether an anagram is of a palindrome?

In this problem we consider only strings of lower-case English letters (a-z).
A string is a palindrome if it has exactly the same sequence of characters when traversed left-to-right as right-to-left. For example, the following strings are palindromes:
"kayak"
"codilitytilidoc"
"neveroddoreven"
A string A is an anagram of a string B if it consists of exactly the same characters, but possibly in another order. For example, the following strings are each other's anagrams:
A="mary" B="army" A="rocketboys" B="octobersky" A="codility" B="codility"
Write a function
int isAnagramOfPalindrome(String S);
which returns 1 if the string s is a anagram of some palindrome, or returns 0 otherwise.
For example your function should return 1 for the argument "dooernedeevrvn", because it is an anagram of a palindrome "neveroddoreven". For argument "aabcba", your function should return 0.
'Algorithm' would be too big word for it.
You can construct a palindrome from the given character set if each character occurs in that set even number of times (with possible exception of one character).
For any other set, you can easily show that no palindrome exists.
Proof is simple in both cases, but let me know if that wasn't clear.
In a palindrome, every character must have a copy of itself, a "twin", on the other side of the string, except in the case of the middle letter, which can act as its own twin.
The algorithm you seek would create a length-26 array, one for each lowercase letter, and start counting the characters in the string, placing the quantity of character n at index n of the array. Then, it would pass through the array and count the number of characters with an odd quantity (because one letter there does not have a twin). If this number is 0 or 1, place that single odd letter in the center, and a palindrome is easily generated. Else, it's impossible to generate one, because two or more letters with no twins exist, and they can't both be in the center.
I came up with this solution for Javascript.
This solution is based on the premise that a string is an anagram of a palindrome if and only if at most one character appears an odd number of times in it.
function solution(S) {
var retval = 0;
var sorted = S.split('').sort(); // sort the input characters and store in
// a char array
var array = new Array();
for (var i = 0; i < sorted.length; i++) {
// check if the 2 chars are the same, if so copy the 2 chars to the new
// array
// and additionally increment the counter to account for the second char
// position in the loop.
if ((sorted[i] === sorted[i + 1]) && (sorted[i + 1] != undefined)) {
array.push.apply(array, sorted.slice(i, i + 2));
i = i + 1;
}
}
// if the original string array's length is 1 or more than the length of the
// new array's length
if (sorted.length <= array.length + 1) {
retval = 1;
}
//console.log("new array-> " + array);
//console.log("sorted array-> " + sorted);
return retval;
}
i wrote this code in java. i don't think if its gonna be a good one ^^,
public static int isAnagramOfPalindrome(String str){
ArrayList<Character> a = new ArrayList<Character>();
for(int i = 0; i < str.length(); i++){
if(a.contains(str.charAt(i))){
a.remove((Object)str.charAt(i));
}
else{
a.add(str.charAt(i));
}
}
if(a.size() > 1)
return 0;
return 1;
}
Algorithm:
Count the number of occurrence of each character.
Only one character with odd occurrence is allowed since in a palindrome the maximum number of character with odd occurrence can be '1'.
All other characters should occur in an even number of times.
If (2) and (3) fail, then the given string is not a palindrome.
This adds to the other answers given. We want to keep track of the count of each letter seen. If we have more than one odd count for a letter then we will not be able to form a palindrome. The odd count would go in the middle, but only one odd count can do so.
We can use a hashmap to keep track of the counts. The lookup for a hashmap is O(1) so it is fast. We are able to run the whole algorithm in O(n). Here's it is in code:
if __name__ == '__main__':
line = input()
dic = {}
for i in range(len(line)):
ch = line[i]
if ch in dic:
dic[ch] += 1
else:
dic[ch] = 1
chars_whose_count_is_odd = 0
for key, value in dic.items():
if value % 2 == 1:
chars_whose_count_is_odd += 1
if chars_whose_count_is_odd > 1:
print ("NO")
else:
print ("YES")
I have a neat solution in PHP posted in this question about complexities.
class Solution {
// Function to determine if the input string can make a palindrome by rearranging it
static public function isAnagramOfPalindrome($S) {
// here I am counting how many characters have odd number of occurrences
$odds = count(array_filter(count_chars($S, 1), function($var) {
return($var & 1);
}));
// If the string length is odd, then a palindrome would have 1 character with odd number occurrences
// If the string length is even, all characters should have even number of occurrences
return (int)($odds == (strlen($S) & 1));
}
}
echo Solution :: isAnagramOfPalindrome($_POST['input']);
It uses built-in PHP functions (why not), but you can make it yourself, as those functions are quite simple. First, the count_chars function generates a named array (dictionary in python) with all characters that appear in the string, and their number of occurrences. It can be substituted with a custom function like this:
$count_chars = array();
foreach($S as $char) {
if array_key_exists($char, $count_chars) {
$count_chars[$char]++;
else {
$count_chars[$char] = 1;
}
}
Then, an array_filter with a count function is applied to count how many chars have odd number of occurrences:
$odds = 0;
foreach($count_chars as $char) {
$odds += $char % 2;
}
And then you just apply the comparison in return (explained in the comments of the original function).
return ($odds == strlen($char) % 2)
This runs in O(n). For all chars but one, must be even. the optional odd character can be any odd number.
e.g.
abababa
def anagram_of_pali(str):
char_list = list(str)
map = {}
nb_of_odds = 0
for char in char_list:
if char in map:
map[char] += 1
else:
map[char] = 1
for char in map:
if map[char] % 2 != 0:
nb_of_odds += 1
return True if nb_of_odds <= 1 else False
You just have to count all the letters and check if there are letters with odd counts. If there are more than one letter with odd counts the string does not satisfy the above palindrome condition.
Furthermore, since a string with an even number letters must not have a letter with an odd count it is not necessary to check whether string length is even or not. It will take O(n) time complexity:
Here's the implementation in javascript:
function canRearrangeToPalindrome(str)
{
var letterCounts = {};
var letter;
var palindromeSum = 0;
for (var i = 0; i < str.length; i++) {
letter = str[i];
letterCounts[letter] = letterCounts[letter] || 0;
letterCounts[letter]++;
}
for (var letterCount in letterCounts) {
palindromeSum += letterCounts[letterCount] % 2;
}
return palindromeSum < 2;
}
All right - it's been a while, but as I was asked such a question in a job interview I needed to give it a try in a few lines of Python. The basic idea is that if there is an anagram that is a palindrome for even number of letters each character occurs twice (or something like 2n times, i.e. count%2==0). In addition, for an odd number of characters one character (the one in the middle) may occur only once (or an uneven number - count%2==1).
I used a set in python to get the unique characters and then simply count and break the loop once the condition cannot be fulfilled. Example code (Python3):
def is_palindrome(s):
letters = set(s)
oddc=0
fail=False
for c in letters:
if s.count(c)%2==1:
oddc = oddc+1
if oddc>0 and len(s)%2==0:
fail=True
break
elif oddc>1:
fail=True
break
return(not fail)
def is_anagram_of_palindrome(S):
L = [ 0 for _ in range(26) ]
a = ord('a')
length = 0
for s in S:
length += 1
i = ord(s) - a
L[i] = abs(L[i] - 1)
return length > 0 and sum(L) < 2 and 1 or 0
While you can detect that the given string "S" is a candidate palindrome using the given techniques, it is still not very useful. According to the implementations given,
isAnagramOfPalindrome("rrss") would return true but there is no actual palindrome because:
A palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction. (Wikipedia)
And Rssr or Srrs is not an actual word or phrase that is interpretable. Same with it's anagram. Aarrdd is not an anagram of radar because it is not interpretable.
So, the solutions given must be augmented with a heuristic check against the input to see if it's even a word, and then a verification (via the implementations given), that it is palindrome-able at all. Then there is a heuristic search through the collected buckets with n/2! permutations to search if those are ACTUALLY palindromes and not garbage. The search is only n/2! and not n! because you calculate all permutations of each repeated letter, and then you mirror those over (in addition to possibly adding the singular pivot letter) to create all possible palindromes.
I disagree that algorithm is too big of a word, because this search can be done pure recursively, or using dynamic programming (in the case of words with letters with occurrences greater than 2) and is non trivial.
Here's some code: This is same as the top answer that describes algorithm.
1 #include<iostream>
2 #include<string>
3 #include<vector>
4 #include<stack>
5
6 using namespace std;
7
8 bool fun(string in)
9 {
10 int len=in.size();
11 int myints[len ];
12
13 for(int i=0; i<len; i++)
14 {
15 myints[i]= in.at(i);
16 }
17 vector<char> input(myints, myints+len);
18 sort(input.begin(), input.end());
19
20 stack<int> ret;
21
22 for(int i=0; i<len; i++)
23 {
24 if(!ret.empty() && ret.top()==input.at(i))
25 {
26 ret.pop();
27 }
28 else{
29 ret.push(input.at(i));
30 }
31 }
32
33 return ret.size()<=1;
34
35 }
36
37 int main()
38 {
39 string input;
40 cout<<"Enter word/number"<<endl;
41 cin>>input;
42 cout<<fun(input)<<endl;
43
44 return 0;
45 }

Resources