I am trying to write a program where you can enter a number and then what number you want it multiplied by and also how many times. After this, you can choose which # step you want and what number it was at that step:
numbr= int(raw_input("pick a number: "))
mult= int(raw_input("keep multiplying by what: "))
listy= []
ff= 1
while x < 999999999999999999999999999:
numbr *= mult
listy.append(x)
ff += 1
cc = int(raw_input("what number do you want: "))
print listy[cc-2]
Currently it only goes up to that big number. How can I make it output whatever # step the user wants? If I do while x > 1, then it just loads and doesn't even allow the user to enter what they want. What can I do?
First off, computer memory is limited, and you typically should avoid using more of it than you absolutely need. With the problem in question particularly, you do not need the intermediate values at all - why make a list if you only need a single number?
Also, some random comments on style: Try to make variables self-explanatory, and avoid skipping letters or shortening things when necessary. Anyway, an example of how this could be done:
number= int(raw_input("pick a number: "))
multiplier = int(raw_input("keep multiplying by what: "))
times = int(raw_input("multiply how many times: "))
x = 0
while x < times:
number *= multiplier
x += 1
print(number)
One thing though, you don't have to use a while loop for this, since for _ in range(times) does the job just as well, and is additionally more readable. The _ here is a variable name usually used for values we don't need, e.g. a "discard" variable, and thus the code becomes:
number= int(raw_input("pick a number: "))
multiplier = int(raw_input("keep multiplying by what: "))
times = int(raw_input("multiply how many times: "))
for _ in range(times):
number *= multiplier
print(number)
Additionally, if you observe what kind of math you are doing, it is possible to further reduce the code's complexity, since you are effectively multiplying a number by the power of another number, e.g. numbr * mult^cc in your original code. Since the operator for power is ** in Python, the final code is:
number= int(raw_input("pick a number: "))
multiplier = int(raw_input("keep multiplying by what: "))
times = int(raw_input("multiply how many times: "))
print(number * multiplier ** times)
The code I posted differs from yours a bit, since it doesn't count the original number as a part of our sequence, but well, I'll leave that as an exercise to you, as it is not a very hard one ;)
Each time you multiply a number you are appending it to the list. Your list is keeping track of all 999999999999999999999999999 entries. As the entries get bigger which they do very quickly each one will take up more space in memory. A regular int will start at 8 bits.
You should have the program take whatever step the user wants and calculate it using a formula instead of generating all values up to that point. I think the formula would be: number * mult^cc.
Related
I am trying to solve the below question.
You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.
First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers denoting array elements.
Next Q lines contain two integers L and R(indices of the array).
Print a single integer denoting the answer.*
I have replaced print() with stdout.write() and input() with stdin.readline().
from sys import stdin, stdout
x,y=map(int,stdin.readline().split())
array=[int(x) for x in stdin.readline().split()]
result=[]
sum=0
for i in range(y):
l,r=map(int,stdin.readline().split())
for i in range(l-1,r):
sum = sum + array[i]
result.append(sum//(r-l+1))
sum=0
for i in result:
stdout.write(str(i)+"\n")
The time taken by my code is about 8 secs, to solve the challenge time limit is 1.5 secs
This type of problem is usually pretty simple if you store the sums from 1-i in the ith value of the array, like so:
from sys import stdin, stdout
x,y=map(int,stdin.readline().split())
array=[int(x) for x in stdin.readline().split()]
sums[0] = array[0]
sums = [sum[i-1]+array[i] for i in range(1,len(array))]
result=[]
for i in range(y):
l,r=map(int,stdin.readline().split())
result.append((sums[r-1]-sums[l-1])//(r-l+1))
for i in result:
stdout.write(str(i)+"\n")
By doing presummation it changes the speed of the program from O(N^2) to O(N) which should be much faster.
Remove the append operation. It is a costly operation and is unecessary since you don't reuse the results. Instead, do directily:
for i in range(l-1,r):
sum = sum + array[i]
stdout.write(str(sum//(r-l+1))+"\n")
By doing like this you avoid go through the second loop too.
If you try, please report here the time taken.
I'm taking the CS50 course on edx.org; it's called Introduction to Computer Science.
I'm trying to solve 1st week problem set. So user inputs credit card number and I have to develop some sort of algorithm to check if it's number is valid. To do so I need to separate whole 16-digit number to digits. And I'm stuck here. I guess I need to do this in loop, at getting at each step digit by digit and to do so I wanted to divide user's input by 10 each step and somehow get the residue.
I can't convert to type int because of int's restrictions on number of digits it can hold. How can I implement this kind of function? I tried this, but then realized it leads to nothing... At first glance at least. cre_num stays for credit number.
long long check(long long cre_num)
{
double part, i;
for (i = 0.1; i <= 1; i = i+0.1)
{
if (cre_num/10 == i)
{
part = i;
}
}
return part;
}
You need to put in a vector, or kind of it, 16 digits of a number (long int)?
When you % a number by 10, you get the last digit of it, like this:
13%10 = 3
3%10 = 3 (03 = 3)
523%10 = 3
So, if you %10 you get the last digit and put in your vector, and than you /10, because /10 will remove the last digit, the one that you have already saved.
If you want, I can try to code it, but I think that you've already that kind of done.
What I want to achieve:
I have a function where I want to loop through all possible combinations of printable ascii-characters, starting with a single character, then two characters, then three etc.
The part that makes this difficult for me is that I want this to work for as many characters as I can (leave it overnight).
For the record: I know that abc really is 97 98 99, so a numeric representation is fine if that's easier.
This works for few characters:
I could create a list of all possible combinations for n characters, and just loop through it, but that would require a huge amount of memory already when n = 4. This approach is literally impossible for n > 5 (at least on a normal desktop computer).
In the script below, all I do is increment a counter for each combination. My real function does more advanced stuff.
If I had unlimited memory I could do (thanks to Luis Mendo):
counter = 0;
some_function = #(x) 1;
number_of_characters = 1;
max_time = 60;
max_number_of_characters = 8;
tic;
while toc < max_time && number_of_characters < max_number_of_characters
number_of_characters = number_of_characters + 1;
vectors = [repmat({' ':'~'}, 1, number_of_characters)];
n = numel(vectors);
combs = cell(1,n);
[combs{end:-1:1}] = ndgrid(vectors{end:-1:1});
combs = cat(n+1, combs{:});
combs = reshape(combs, [], n);
for ii = 1:size(combs, 1)
counter = counter + some_function(combs(ii, :));
end
end
Now, I want to loop through as many combinations as possible in a certain amount of time, 5 seconds, 10 seconds, 2 minutes, 30 minutes, so I'm hoping to create a function that's only limited by the available time, and uses only some reasonable amount of memory.
Attempts I've made (and failed at) for more characters:
I've considered pre-computing the combinations for two or three letters using one of the approaches above, and use a loop only for the last characters. This would not require much memory, since it's only one (relatively small) array, plus one or more additional characters that gets looped through.
I manage to scale this up to 4 characters, but beyond that I start getting into trouble.
I've tried to use an iterator that just counts upwards. Every time I hit any(mod(number_of_ascii .^ 1:n, iterator) == 0) I increment the m'th character by one. So, the last character just repeats the cycle !"# ... ~, and every time it hits tilde, the second character increments. Every time the second character hits tilde, the third character increments etc.
Do you have any suggestions for how I can solve this?
It looks like you're basically trying to count in base-26 (or base 52 if you need CAPS). Each number in that base will account for a specific string of character. For example,
0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,10,11,12,...
Here, cap A through P are just symbols that are used to represent number symbols for base-26 system. The above simply represent this string of characters.
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,ba,bb,bc,...
Then, you can simply do this:
symbols = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E',...
'F','G','H','I','J','K','L','M','N','O','P']
characters = ['a','b','c','d','e','f','g','h','i','j','k','l',...
'm','n','o','p','q','r','s','t','u','v','w','x','y','z']
count=0;
while(true)
str_base26 = dec2base(count,26)
actual_str = % char-by-char-lookup-of-str26 to chracter string
count=count+1;
end
Of course, it does not represent characters that begin with trailing 0's. But that should be pretty simple.
You were not far with your idea of just getting an iterator that just counts upward.
What you need with this idea is a map from the integers to ASCII characters. As StewieGriffin suggested, you'd just need to work in base 95 (94 characters plus whitespace).
Why whitespace : You need something that will be mapped to 0 and be equivalent to it. Whitespace is the perfect candidate. You'd then just skip the strings containing any whitespace. If you don't do that and start directly at !, you'll not be able to represent strings like !! or !ab.
First let's define a function that will map (1:1) integers to string :
function [outstring,toskip]=dec2ASCII(m)
out=[];
while m~=0
out=[mod(m,95) out];
m=(m-out(1))/95;
end
if any(out==0)
toskip=1;
else
toskip=0;
end
outstring=char(out+32);
end
And then in your main script :
counter=1;
some_function = #(x) 1;
max_time = 60;
max_number_of_characters = 8;
currString='';
tic;
while numel(currString)<=max_number_of_characters&&toc<max_time
[currString,toskip]=dec2ASCII(counter);
if ~toskip
some_function(currString);
end
counter=counter+1;
end
Some random outputs of the dec2ASCII function :
dec2ASCII(47)
ans =
O
dec2ASCII(145273)
ans =
0)2
In terms of performance I can't really elaborate as I don't know what you want to do with your some_function. The only thing I can say is that the running time of dec2ASCII is around 2*10^(-5) s
Side note : iterating like this will be very limited in terms of speed. With the function some_function doing nothing, you'd just be able to cycle through 4 characters in around 40 minutes, and 5 characters would already take up to 64 hours. Maybe you'd want to reduce the amount of stuff you want to pass through the function you iterate on.
This code, though, is easily parallelizable, so if you want to check more combinations, I'd suggest trying to do it in a parallel manner.
I am looking for an algorithm to solve the following problem: We are given an integer array of size n which contains k (0 < k < n) many elements exactly once. Every other integer occurs an even number of times in the array. The output should be any of the k unique numbers. k is a fixed number and not part of the input.
An example would be the input [1, 2, 2, 4, 4, 2, 2, 3] with both 1 and 3 being a correct output.
Most importantly, the algorithm should run in O(n) time and require only O(1) additional space.
edit: There has been some confusion regarding whether there is only one unique integer or multiple. I apologize for this. The correct problem is that there is an arbitrary but fixed amount. I have updated the original question above.
"Dante." gave a good answer for the case that there are at most two such numbers. This link also provides a solution for three. "David Eisenstat" commented that it is also possible to do for any fixed k. I would be grateful for a solution.
There is a standard algorithm to solve such problems using XOR operator:
Time Complexity = O(n)
Space Complexity = O(1)
Suppose your input array contains only one element that occurs odd no of times and rest occur even number of times,we take advantage of the following fact:
Any expression having even number of 0's and 1's in any order will always be = 0 when xor is applied.
That is
0^1^....... = 0 as long as number of 0 is even and number of 1 is even
and 0 and 1 can occur in any order.
Because all numbers that occur even number of times will have their corresponding bits form even number of 1's and 0's and only the number which occurs only once will have its bit left out when we take xor of all elements of array because
0(from no's occuring even times)^1(from no occuring once) = 1
0(from no's occuring even times)^0(from no occuring once) = 0
as you can see the bit of only the number occuring once is preserved.
This means when given such an array and you take xor of all the elements,the result is the number which occurs only once.
So the algorithm for array of length n is:
result = array[0]^array[1]^.....array[n-1]
Different Scenario
As the OP mentioned that input can also be an array which has two numbers occuring only once and rest occur even number of times.
This is solved using the same logic as above but with little difference.
Idea of algorithm:
If you take xor of all the elements then definitely all the bits of elements occuring even number of times will result in 0,which means:
The result will have its bit 1 only at that bit position where the bits of the two numbers occuring only once differ.
We will use the above idea.
Now we focus on the resultant xor bit which is 1(any bit which is 1) and make rest 0.The result is a number which will allow us to differentiate between the two numbers(the required ones).
Because the bit is 1,it means they differ at this position,it means one will have 0 at this position and one will have 1.This means one number when taken AND results in 0 and one does not.
Since it is very easy to set the right most bit,we set it of the result xor as
A = result & ~(result-1)
Now traverse through the array once and if array[i]&A is 0 store the number in variable number_1 as
number_1 = number_1^array[i]
otherwise
number_2 = number_2^array[i]
Because the remaining numbers occur even number of times,their bit will automatically disappear.
So the algorithm is
1.Take xor of all elements,call it xor.
2.Set the rightmost bit of xor and store it in B.
3.Do the following:
number_1=0,number_2=0;
for(i = 0 to n-1)
{
if(array[i] & B)
number_1 = number_1^array[i];
else
number_2 = number_2^array[i];
}
The number_1 and number_2 are the required numbers.
Here's a Las Vegas algorithm that, given k, the exact number of elements that occur an odd number of times, reports all of them in expected time O(n k) (read: linear-time when k is O(1)) and space O(1) words, assuming that "give me a uniform random word" and "give me the number of 1 bits set in this word (popcount)" are constant-time operations. I'm pretty sure that I'm not the first person to come up with this algorithm (and I'm not even sure that I'm remembering all of the refinements), but I've reached the limits of my patience trying to find it.
The central technique is called random restrictions. Essentially what we do is to filter the input randomly by value, in the hope that we retain exactly one odd-count element. We apply the classic XOR algorithm to the filtered array and check the result; if it succeeded, then we pretend to add it to the array, to make it even-count. Repeat until all k elements are found.
The filtration process goes like this. Treat each input word x as a binary vector of length w (doesn't matter what w is). Compute a random binary matrix A of size w by ceil(1 + lg k) and a random binary vector b of length ceil(1 + lg k). We filter the input by retaining those x such that Ax = b, where the left-hand side is a matrix multiplication mod 2. In implementation, A is represented as ceil(1 + lg k) vectors a1, a2, .... We compute the bits of Ax as popcount(a1 ^ x), popcount(a2 ^ x), .... (This is convenient because we can short-circuit the comparison with b, which shaves a factor lg k from the running time.)
The analysis is to show that, in a given pass, we manage with constant probability to single out one of the odd-count elements. First note that, for some fixed x, the probability that Ax = b is 2-ceil(1 + lg k) = Θ(1/k). Given that Ax = b, for all y ≠ x, the probability that Ay = b is less than 2-ceil(1 + lg k). Thus, the expected number of elements that accompany x is less than 1/2, so with probability more than 1/2, x is unique in the filtered input. Sum over all k odd-count elements (these events are disjoint), and the probability is Θ(1).
Here's a deterministic linear-time algorithm for k = 3. Let the odd-count elements be a, b, c. Accumulate the XOR of the array, which is s = a ^ b ^ c. For each bit i, observe that, if a[i] == b[i] == c[i], then s[i] == a[i] == b[i] == c[i]. Make another pass through the array, accumulate the XOR of the lowest bit set in s ^ x. The even-count elements contribute nothing again. Two of the odd-count elements contribute the same bit and cancel each other out. Thus, the lowest bit set in the XOR is where exactly one of the odd-count elements differs from s. We can use the restriction method above to find it, then the k = 2 method to find the others.
The question title says "the unique integer", but the question body says there can be more than one unique element.
If there is in fact only one non-duplicate: XOR all the elements together. The duplicates all cancel, because they come in pairs (or higher multiples of 2), so the result is the unique integer.
See Dante's answer for an extension of this idea that can handle two unique elements. It can't be generalized to more than that.
Perhaps for k unique elements, we could use k accumulators to track sum(a[i]**k). i.e. a[i], a[i]2, etc. This probably only works for Faster algorithm to find unique element between two arrays?, not this case where the duplicates are all in one array. IDK if an xor of squares, cubes, etc. would be any use for resolving things.
Track the counts for each element and only return the elements with a count of 1. This can be done with a hash map. The below example tracks the result using a hash set while it's still building the counts map. Still O(n) but less efficient, but I think it's slightly more instructive.
Javascript with jsfiddle http://jsfiddle.net/nmckchsa/
function findUnique(arr) {
var uniq = new Map();
var result = new Set();
// iterate through array
for(var i=0; i<arr.length; i++) {
var v = arr[i];
// add value to map that contains counts
if(uniq.has(v)) {
uniq.set(v, uniq.get(v) + 1);
// count is greater than 1 remove from set
result.delete(v);
} else {
uniq.set(v, 1);
// add a possibly uniq value to the set
result.add(v);
}
}
// set to array O(n)
var a = [], x = 0;
result.forEach(function(v) { a[x++] = v; });
return a;
}
alert(findUnique([1,2,3,0,1,2,3,1,2,3,5,4,4]));
EDIT Since the non-uniq numbers appear an even number of times #PeterCordes suggested a more elegant set toggle.
Here's how that would look.
function findUnique(arr) {
var result = new Set();
// iterate through array
for(var i=0; i<arr.length; i++) {
var v = arr[i];
if(result.has(v)) { // even occurances
result.delete(v);
} else { // odd occurances
result.add(v);
}
}
// set to array O(n)
var a = [], x = 0;
result.forEach(function(v) { a[x++] = v; });
return a;
}
JSFiddle http://jsfiddle.net/hepsyqyw/
Assuming you have an input array: [2,3,4,2,4]
Output: 3
In Ruby, you can do something as simple as this:
[2,3,4,2,4].inject(0) {|xor, v| xor ^ v}
Create an array counts that has INT_MAX slots, with each element initialized to zero.
For each element in the input list, increment counts[element] by one. (edit: actually, you will need to do counts[element] = (counts_element+1)%2, or else you might overflow the value for really ridiculously large values of N. It's acceptable to do this kind of modulus counting because all duplicate items appear an even number of times)
Iterate through counts until you find a slot that contains "1". Return the index of that slot.
Step 2 is O(N) time. Steps 1 and 3 take up a lot of memory and a lot of time, but neither one is proportional to the size of the input list, so they're still technically O(1).
(note: this assumes that integers have a minimum and maximum value, as is the case for many programming languages.)
So I have this problem.
Input # of rooms: 4
room1:6
room2:4
room3:7
room4:3
(if I type 5 in "Input # of rooms" there would also be room5)
Odd: 7 3
Even: 6 4
I have to display the odd and even numbers, so I came up with this code:
System.out.print("Input # of rooms: ");
int rms=Integer.parseInt(io.readLine());
int[] array=new int[rms];
int a=0;
int b=1;
do {
System.out.print("room "+b+":");
array[a] = Integer.parseInt(io.readLine());
a++;
b++;
} while (a<rms);
I don't know how to display which are Odd numbers and which are Even numbers?
you want to find the remainder or modulus when the param is divided by 2.
3 % 2 = 1 so odd
4 % 2 = 2 so even
if(param % 2 == 1){
Print odd number
}else{
Print even number
}
Should get you started
The use of the modulo operator (%) will be invaluable here - it performs integer division and returns the remainder of the quotient - kind of like short division.
The rules for determining the type of number are simple:
If the number is even, it is divisible by 2.
Otherwise, it is odd.
As for the printing part: I would recommend accumulating the values in two separate StringBuffers or Strings if you prefer, adding a space between when we get another of the type of value we want. Then, we can print it out pretty after we're done iterating through the array.
One last thing - you should only need one loop - preferably a for loop, since you know exactly how many elements you're going to iterate over. You can use the above rules for modulus to determine which number gets appended to which variable.