Sorting Random Numbers in my array - python

I have made an array in python that generates 20 random numbers 50-100. I want to know how to sort the numbers in my array. I am in 8th grade and this is for my computing class. Can this even be done? My teacher mentioned some kind of sorting algorithm, but told me not to use sort(). I am using python. Thanks
this is what i have so far
from random import*
array = range(20)
for i in range(20):
array[i] = randint(50, 100)
print array

Since it's an homework I won't give you the solution, but a starting point http://en.wikipedia.org/wiki/Sorting_algorithm where you can find an introduction to sorting algorithms!
Just choose one and try to implement it! Then if you do something wrong you can ask for help ;)

Everyone has posted excellent answers. I want to point you to this page, because it has a set of good animations for various different sorting algorithms.
Good luck!

For educational purposes, this should be a good place to start: http://en.wikipedia.org/wiki/Bubble_sort It's not a very good sorting algorithm, but once you understand the principles you can move on to more advanced sorting algorithms (which you will probably learn in class eventually).
Essentially, you compare every element to the next one, and swap them if they are out of order. Continue doing this until your array is sorted. Good luck!

This can be done and there are a number of ways to do it, you need to implement your own sorting algorithm, examples of which are very easy to come accross.
I will point you towards a python implementation of one of these algorithms with excellent explanation but i strongly suggest you read up on this sort of stuff as it is the foundation of computer science imho.
go here for a python quicksort program.. but please do the work around it.
Also i have to reccommend Introduction to Algorithms by thomas h cormen which is an awesome book and took me through a lot of stuff, and I still look at it to this day. A word of warning on this book.. it is not a light read.
If you find all this a bit heavy I found a youtube clip which goes through bubble sort.

Related

Python Procedural 2d map generator explanation

So i found a certain procedural map generator in Python and I understand parts of it but i'm having a very hard time piecing it together to be able to modify it to suite my needs so I was wondering if it is possible for someone to explain step by step what exactly the generator does. Overall I understand the concept but the way it is written makes it very hard for me to follow the math involved.
The generator is here and some explanations would be welcomed and probably help anyone else trying to learn procedural generation as this example honestly yields beautiful results.
First you must understand how Perlin Noise works.
I recommend you write your own Perlin Noise code, something minimal, then play a bit with it and see the results.
Then move on to more advanced techniques and variants.
Here for example the user has some settings which more or less control the output:
basePerlinValue = (snoise2(float(x)*perlinScale, float(y)*perlinScale, octaves=8, persistence=0.5, lacunarity=2.0, repeatx=2048, repeaty=2048, base=perlinOffset) + 1)/2.0;
Play with them and see how they affect the result.
Octaves is standard Perlin Noise stuff.

Find unknown exponent in Python with very large numbers

I am attempting to find d in Python, such that
(2 ** d) mod n = s2
Where n =
132177882185373774813945506243321607011510930684897434818595314234725602493934515403833460241072842788085178405842019124354553719616350676051289956113618487539608319422698056216887276531560386229271076862408823338669795520077783060068491144890490733649000321192437210365603856143989888494731654785043992278251
and s2 =
18269259493999292542402899855086766469838750310113238685472900147571691729574239379292239589580462883199555239659513821547589498977376834615709314449943085101697266417531578751311966354219681199183298006299399765358783274424349074040973733214578342738572625956971005052398172213596798751992841512724116639637
I am not looking for the solution, but for a reasonably fast way to do this. I've tried using pow and plugging in different values, but this is slow and never gets the solution. How can I find d?
There is no known algorithm that can solve your problem. It's called discrete logarithm problem, and some cryptosystems depend on its complexity (You can't find its solution fast unless you know factorization of n)
Look at the second answer to Is it possible to get RSA private key knowing public key and set of "original data=>encrypted data" entries?. A known-plaintext attack is no easier than known-ciphertext.
The only known discrete logarithm solvers are built around knowing the factors. If you don't have the factors, you need to generate them.
The best reasonable-time algorithm for this is Shor's algorithm. The problem is that you need a quantum computer with enough qubits, and nobody's built one large enough for your sample data yet. And it looks like it'll be quite a few years before anyone does; currently people are still excited about factoring numbers like 15 and 21.
If you want to use classical computing, the best known algorithms are nowhere near "reasonably fast". I believe someone recently showed that the Bonn results on 2^1039-1 should be reproducible in under 4 months with modern PCs. Another 5 years, and maybe it'll be down to a month.
It shouldn't surprise you that there are no known reasonable fast algorithms, because if there were, most private key encryption would be crackable and therefore worthless. It would be major news if someone gave you the answer you're looking for. (Is there an SO question for "Is P=NP?")

I need to make something like OkCupids' was of calculating the match percentage in python/web2py

I want to make something like that, but much more simple. I am using web2py and python.
For example:
I make two profiles for two individuals. For each one I want them to be able to choose 10 movies they like. After that, it compares the movies and output the percentage of similarity.
Again, something like how OkCupid makes you answer questions, and then compares you answers to someone else and give you how much your answers matches theirs.
I am a beginner and need help. If not at least what to look into and study to learn. But a bast generic example would be great.
The best introduction to this area that I have seen is Programming Collective Intelligence by Toby Segaran. There is a section in the introductory chapter on 'Finding similar users' that does exactly what you are intending, and it is even in Python.
If you want to play with a recommendation system (a user likes these ten movies, which other movies might she also like?), then you may want to try the python-recsys library which has an example using the movielens dataset.
Finally, welcome to SO and a recommendation for best participation in this community: try to come back with specific code-related questions, something along the lines of: "I have such-and-such a coding problem. This is what I have tried, can you help me move it further?"

Python usage of breadth-first search on social graph

I've been reading a lot of stackoverflow questions about how to use the breadth-first search, dfs, A*, etc, the question is what is the optimal usage and how to implement it in reality verse simulated graphs. E.g.
Consider you have a social graph of Twitter/Facebook/Some social networking site, to me it seems a search algorithm would work as follows:
If user A had 10 friends, then one of those had 2 friends and another 3. The search would first figure out who user A's friends were, then it would have to look up who the friends where to each of the ten users. To me this seems like bfs?
However, I'm not sure if that's the way to go about implementing the algorithm.
Thanks,
For my two cents, if you're just trying to traverse the whole graph it doesn't matter a whole lot what algorithm you use so long as it only hits each node once. This seems to be what you're saying when you note:
I'm just trying to traverse the whole graph
This means your terminology is technically flawed- you're talking about walking a graph, not searching a graph. Unless you're actually trying to search for something in particular, which you don't seem to mention in the question at all.
With that said, Facebook and Twitter are very different graph structures that do have an impact on how you walk them:
Facebook is fundamentally an undirected graph. If X is friends with Y, Y MUST be friends with X. (Or in a relationship with, or related to, etc).
Twitter is fundamentally a directed graph. If you X follows Y, Y does not have to follow X.
These issues will significantly impact the graph walking algorithm. To be quite honest, if you just want to visit all the nodes, do you even need a graph? Why not just iterate over all of them? If you have all the nodes in some data structure MY_DATA that is iterable, you could just have a generator expression like this:
def nodeGenerator(MY_DATA)
for node in MY_DATA:
yield node
Clearly, you'd need to adjust the nodeGenerator internals to handle how you're actually accessing the nodes. With that said, most graph structures implement a node iterator. Then you can just create an iterator anytime you want to do things via:
for node in nodeGenerator(MY_DATA):
(Do something here)
Maybe I'm just missing the point of the question here, but at present you've posed a question about search algorithms without a search problem. Due to the No Free Lunch nature of optimization and search, the worth of any search algorithm will be entirely dependent on the search problem you're trying to examine.
This is true even among the same data set. After all, if you were searching for everybody whose name starts with the letter D, a great approach would be to just sort everyone alphabetically and do a binary search. If instead you're trying to find everyone's degree of separation from Kevin Bacon, you're going to want and algorithm that starts with Mr. Bacon and recursively iterates over everyone who knows him and everyone who they know. These are both things you COULD do on Facebook or Twitter, but without any specifics there's really no way to recommend an algorithm. Hence, if you know nothing, just iterate over everyone as a list. It's just as good as anything else. If you then want to optimize, cache any calculations.
I have around 300 friends in facebook and some of my friends also have 300 friends on an average. If you gonna build a graph out of it , it's gonna be huge . Correct me , if I am wrong ? . A BFS will be quit lot demanding in this scenario ?
Thanks
J

How to synthesize sounds?

I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that.
What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds?
This far I've gotten to do this, it produces quite plain sound from which I'm not sure it's even using the alsa correctly.
import numpy
from numpy.fft import fft, ifft
from numpy.random import random_sample
from alsaaudio import PCM, PCM_NONBLOCK, PCM_FORMAT_FLOAT_LE
pcm = PCM()#mode=PCM_NONBLOCK)
pcm.setrate(44100)
pcm.setformat(PCM_FORMAT_FLOAT_LE)
pcm.setchannels(1)
pcm.setperiodsize(4096)
def sine_wave(x, freq=100):
sample = numpy.arange(x*4096, (x+1)*4096, dtype=numpy.float32)
sample *= numpy.pi * 2 / 44100
sample *= freq
return numpy.sin(sample)
for x in xrange(1000):
sample = sine_wave(x, 100)
pcm.write(sample.tostring())
Sound synthesis is a complex topic which requires many years of study to master.
It is also not an entirely solved problem, although relatively recent developments (such as physical modelling synthesis) have made progress in imitating real-world instruments.
There are a number of options open to you. If you are sure that you want to explore synthesis further, then I suggest you start by learning about FM synthesis. It is relatively easy to learn and implement in software, at least in basic forms, and produces a wide range of interesting sounds. Also, check out the book "The Computer Music Tutorial" by Curtis Roads. It's a bible for all things computer music, and although it's a few years old it is the book of choice for learning the fundamentals.
If you want a quicker way to produce life-like sound, consider using sampling techniques: that is, record the instruments you want to reproduce (or use a pre-existing sample bank), and just play back the samples. It's a much more straightforward (and often more effective) approach.
Cheery, if you want to generate (from scratch) something that really sounds "organic", i.e. like a physical object, you're probably best off to learn a bit about how these sounds are generated. For a solid introduction, you could have a look at a book such as Fletcher and Rossings The Physics of Musical Instruments. There's lots of stuff on the web too, you might want to have a look at a the primer James Clark has here
Having at least a skim over this sort of stuff will give you an idea of what you are up against. Modeling physical instruments accurately is very difficult!
If what you want to do is have something that sounds physical, rather something that sounds like instrument X, your job is a bit easier. You can build up frequencies quite easily and stack them together, add a little noise, and you'll get something that at least doesn't sound anything like a pure tone.
Reading a bit about Fourier analysis in general will help, as will Frequency Modulation (FM) techniques.
Have fun!
I agree that this is very non-trivial and there's no set "right way", but you should consider starting with a (or making your own) MIDI SoundFont.
As other people said, not a trivial topic at all. There are challenges both at the programming side of things (especially if you care about low-latency) and the synthesis part. A goldmine for sound synthesis is the page by Julius O. Smith. There is a lot of techniques for synthesis http://ccrma-www.stanford.edu/~jos/.

Categories