asong -4

i have to have a main function but dont know how to call it in the functions in it.

asong -4

[CODE]import operator, random, sys, time, math
from math import*

square = []

def userinput(): #demands input from the user
return input('enter a value for n: ')

def isvalid(n): #checks whether n is valid
if n == 0 :
print 'invalid arguments for magic square'
return 0
elif n==2:
print 'invalid arguments for magic square'
return 0
elif n>3:
print 'warning: n is greater than 3 so it will take a long time to compute'
return 1
else:
return 1

def thesquare(n): #creates a NxN matrix
for i in range(n):
square.append([])
for j in range(n):
square[i].append(0)
return square

def thesum(n): #computes the required sum
s = (n(nn + 1))/2
return s

def allpossiblevals(n): #lists all possible values
vals = range(1, (n*n)+1, 1)
return vals

def allpermutations(vals): #lists all possible arrangements of all possible values
length = len(vals)
if length <= 1:
yield vals
else:
for permut in allpermutations(vals[1:]):
for i in range(len(permut)+1):
yield permut[:i]+vals[0:1]+permut[i:]

def perm(): #evaluates which permutations are valid magic squares
n = userinput()
v = isvalid(n)
if v == 1:
squares = thesquare(n)
[/CODE]
but program wont run

asong -4

never mind, i figure this out on my own

asong -4

1,2,3,4,5,6,7,8,9

can form this magic square:

123
456
789

and will be represented as

[[1,2,3],[2,1,2],[3,2,1]]

[CODE]def read_file(file_name):
f = open(file_name, "r")

## creating the new file name
new_file_name = "new_" + file_name

## creating the new file with writing permissions
n = open(new_file_name, "w")

for line in f:
    line = line.replace("\n","")
    num = line.split(",")

    ## appending the information to the end of each line
    if fill_array(num) is True:
        ## formatting
        entry = line + " (is a magic number)\n"
        n.write(entry)
    else:
        ## formatting
        entry = line + " (is not a magic nummber)\n"
        n.write(entry)

n.close()
f.close()

"""

import sys

def is_identical(list):
return max(list) == min(list)

def check_array(A, length):
h_sum_list = []
v_sum_list = []

h_sum = 0
v_sum = 0
for i in range(length):
    for j in range(length):
        h_sum += int(A[i][j])
        v_sum += int(A[j][i])
    h_sum_list.append(h_sum)
    v_sum_list.append(v_sum)
    h_sum = 0
    v_sum = 0

left_to_right_diagonal = 0
right_to_left_diagonal = 0
for i in range(length):
    left_to_right_diagonal += int(A[i][i])
    right_to_left_diagonal += int(A[i][length-i-1])

is_horizontal = is_identical(h_sum_list)
is_vertical = is_identical(v_sum_list)
if is_horizontal and is_vertical:
    if left_to_right_diagonal == right_to_left_diagonal:
        if left_to_right_diagonal == h_sum_list[0]:

            return True
return False

def fill_array(num):

A = [[None,None,None],
     [None,None,None],
     [None,None,None]]

length = 3

iteration = 0
for i in range(length):
    for j in range(length):
        A[i][j] = num[iteration]
        iteration += 1

if check_array(A, length):
    return True

return False

def read_file(file_name):
f = open(file_name, "r")
new_filename = "new" + file_name
n = open(new_file_name, "w")
for line in f:
line = line.replace("\n","")
num = line.split(",")
if fill_array(num) is True:
entry = line + " (is a ...

asong -4

i actually have to use a list, i dont know how to use it in this case

TrustyTony commented: Use proper sentences! -3

asong -4

i dont get it

asong -4

This what i have but wont work
[CODE]def makeSquare(n):
mSquare = [ [ 0 for c in xrange(n) ] for r in xrange(n) ]
row = n-1
col = (n-1)/2
M = n*n #
v = 1
r = 0
c = 0
mSquare[row][col] = v
while v != M:
v =v + 1
if (row+1) >= n:
r = 0
else:
r = row + 1
if (col+1) < n:
c = col+1
else: c = 0
if mSquare[r][c]:
if (row+1) < n:
r = row+1
c = col
grid[r][c] = v
row = r
col = c

print Magic Square

for r in xrange(n):
for c in xrange(n):
print mSquare[r][c],
print

def checkSquare(mSquare):

Calculates if square is valid

d = 0
for i in range(len(b)):
r = c = 0
d += b[i][i]
for j in range(len(b)):
r += b[i][j]
c += b[j][i]

if (r != c):
return False

if (d != r):
return False
else:
return True

def main():

Prompt the user to enter an odd number 3 or greater and check the input

while True:
n = int(raw_input("Please enter an odd number: "))
if n > 2 and n % 2:
break

Create the magic square

makeSquare(n)

Verify that it is a magic square

if checkSquare(mSquare) == True:
print "This is a magic Square"
else:
print "Not a magic Square"

main()[/CODE]

asong -4

this is my permutation
[CODE]from itertools import permutations
x=[1,2,3,4,5,6,7,8,9]
for a in permutations(x,9):
if a[0]+a[1]+a[2]==15 and a[3]+a[4]+a[5]==15:
if a[6]+a[7]+a[8]==15 and a[0]+a[3]+a[6]==15:
if a[1]+a[4]+a[7]==15 and a[2]+a[5]+a[8]==15:
if a[0]+a[4]+a[8]==15 and a[2]+a[4]+a[6]==15:
print(a[0:3])
print(a[3:6])
print(a[6:])
print()[/CODE]
but ma problem is to Use a recursive permute to give all of the permutations of the square.

asong -4

i actualy dont know how to do it, i had something like this but not sure.
[CODE]def magic(n):
if n > 2 and n % 2 == 0:
print "You need an odd number."
elif n <=2:
print "You need a number greater or equal to 3."
else:
print "Magic Square: ", n, 'x', n
grid = [ [ 0 for c in xrange(n) ] for r in xrange(n) ]
row, col = 0, n/2
n2, v = n*n, 1;
r, c = 0, 0
grid[row][col] = v
while v != n2:
v += 1
if (row-1) >= 0:
r = row-1
else:
r = n-1
if (col+1) < n:
c = col+1
else: c = 0
if grid[r][c]:
if (row+1) < n:
r = row+1
if grid[r][col]:
break
c = col
grid[r][c] = v
row = r
col = c
for r in xrange(n):
for c in xrange(n):
print "%2d" % grid[r][c],
print[/CODE]

asong -4 Light Poster

This should be written in Python. The program will determine all of the magic squares when given an n, display permutations that match the magic squares to the screen AND write it to a file.

It will only test when n == 3!!! But code it for n of ANY number!! It must come up with every possible arrangement (permutation) of numbers within the square. These are known as the permutations of that list of numbers. Each permutation needs to be checked to see if it has formed a magic square.

The program must:
Use command line arguments. At the command line the user must enter (in this order):

  1. The name of the executable file,
  2. n (which will ALWAYS be 3, but again could be run with other numbers)
    and the name of the output file in which to write the squares.

Use a recursive permute to give all of the permutations of the square.

In other words, your function called "permute", must be a recursive function. So for each permutation, you should check to see if it is a magic square, display it and write it to the file. Write only the unique magic squares to the SCREEN and FILE. No duplicates allowed. Close any files that you have opened as soon as you have finished using them. Time how long your program takes to find the magic square and print that time at the end of the SAME file.

SAMPLE OUTPUT:

2 7 6
9 5 ...

asong -4

i just have to work on the stack and queue modules to import, i believe i can handle that.Thank you all once again

asong -4

first of all i just want to say thank you guys, you guys have given me the best explanantion to this problem, i really appreciated.My prof is not that good, i am a python beginner and he just comes and assigns labs and projects and i have put a lot of hours on my own understanding it myself and you guys have been amazing and patient with and i want to say thank you

asong -4

no thats not what am saying, am talking abt understanding what the question want , not solving it

asong -4

but pytony,they want us to have a stack.py and queue.py, and then import it,so the class queue and class stack, is that what am going to import?cause it is similar to what i have

asong -4

thanks alot guys, i pray it works, going to run it now.

asong -4

they want the program must use command line arguments. At the command line the user must enter
(in this order):
the name of the executable file,
the name of the html file to be checked.
ma little bit confuse now,i have attach the web page(url), so maybe somneone can explain it to me better.
[url]http://www.csee.umbc.edu/courses/201/fall11/assignments/proj_adts.shtml#(1[/url])

asong -4

i think the problem is maybe the stack.py and the queue.py, because we had to import them inside the main.We had to make a stack.py and queue.py.I did what you said but its not giving me different

asong -4

thats the sample output above , this is it again











Phase 1: End of file was reached for xhtml.dat with no errors

matches matches
matches
matches

matches

matches


is self-closing

is self-closing

is self-closing

matches

is self-closing

matches

matches


is self-closing

is self-closing

is self-closing

is self-closing

matches


is self-closing

matches


is self-closing

matches


is self-closing

matches

matches

matches matches

Phase 2: The tags match in this document.
iwas suppose to have a stack.py and a queue.py and import it on my def main.Maybe thats where my problem is.I can give you them and check if you want

asong -4

its still gibing me the same thing, it still doesnt ouput after phase1, thats is no phase 2 is running

asong -4

this supposed to be the output
[code]











[/code] Phase 1: End of file was reached for xhtml.dat with no errors [code] matches matches
matches
matches matches

matches


is self-closing
is self-closing
is self-closing

matches

is self-closing matches

matches


is self-closing
is self-closing
is self-closing
is self-closing matches
is self-closing matches
is self-closing matches
is self-closing

matches

matches

matches matches [/code] Phase 2: The tags match in this document. linuxserver1.cs.umbc.edu[117] but i ma not having nothing after phase

asong -4 Light Poster

Your task is to write a program that checks html files, (web pages) to determine whether the embedded XHTML tags are balanced. Balanced tags are necessary for the file to be a valid XHTML file as explained above.
The first phase takes care of reading the file and finding all of the tags from the file. The first phase will print out the tags as it finds them and also save them into a queue of tags. If the input file ends in the middle of a tag, the program will report the error and end.
The second phase of the program takes the queue of tags generated in phase one and analyzes the sequence of tags to make sure that they are properly balanced. This phase will make use of the queue and a stack, as described on the previous slide. As the tags are matched, you should print the matching tags. If the tag is self-closing, you should print it and also that it is self-closing.
This is what i have so far.My phase 2 is not running, can someone please help me
[code]
def printGreeting():
print 'Welcome bla bla bla bla\n\n'

def phase1(file, queue):
line_num = 0
start = 0
end = 0
ok_tag = False
for line in file:
line_num += 1
if line.count('>') != line.count('<'):
print 'You have an error in line ', line_num
return False
for i in range (len(line)):
if line[i] == '<':
start = i
ok_tag = True
if line[i] == '>': ...

asong -4

i dont know what u mean by that

asong -4

but holdup i have my lab3.py as this

[CODE]import string

def main():

#read input <string> from user

#convert <string> to all uppercase

#for each <char>acter in <string>

    #if <char> is not a space

        #convert <char> to its ASCII <value>

        #rotate <value> by a given amount

        #convert <value> back to a character, <char>

        #print out <char>[/CODE]

but they want us to decode the alphabetical letters to look like the alphabets above.i am confuse a bit.do i have to use if and for statements.i know i have to use chr and ord to convert.please i need help

asong -4

Thank you guys i got it, sorry for the incovenience am used to java

asong -4

Sir,i know one way of doing the actual cipher bit would be to have 2 strings to encode/decode:

1
decoded = "abcdefghijklmnopqrstuvwxyz"
2
encoded = "tuvwxyzabcdefghijklmnopqrs"

In this case decoded[0] = a, encoded[0] = t. You can use the same indexes to translate your input.

But as the rotation length needs to be calculated, it might be better to use modular arithmetic (MOD 26) to calculate the values after the alphabet has been shifted but i am having problem putting it on python.

asong -4 Light Poster

I am writing a program that contains python code that will decode an English
message that was encoded using a Caesar cypher with a fixed
rotation length. It makes use of letter frequencies in
the English language to determine the rotation length.The program should also have some comments within your code to explain what confusing-looking code is doing. These comments should be directly above and indented evenly with the code it is explaining.
The output should look like this
linuxserver1.cs.umbc.edu[101] more code.txt
BJ YMJ UJTUQJ TK YMJ ZSNYJI XYFYJX, NS TWIJW YT KTWR F RTWJ UJWKJHY ZSNTS, JXYFGQNXM OZXYNHJ, NSXZWJ ITRJXYNH YWFSVZNQNYD, UWTANIJ KTW YMJ HTRRTS IJKJSXJ, UWTRTYJ YMJ LJSJWFQ BJQKFWJ, FSI XJHZWJ YMJ GQJXXNSLX TK QNGJWYD YT TZWXJQAJX FSI TZW UTXYJWNYD, IT TWIFNS FSI JXYFGQNXM YMNX HTSXYNYZYNTS KTW YMJ ZSNYJI XYFYJX TK FRJWNHF.
linuxserver1.cs.umbc.edu[102] python hw4.py < code.txt
WE THE PEOPLE OF THE UNITED STATES, IN ORDER TO FORM A MORE PERFECT UNION, ESTABLISH JUSTICE, INSURE DOMESTIC TRANQUILITY, PROVIDE FOR THE COMMON DEFENSE, PROMOTE THE GENERAL WELFARE, AND SECURE THE BLESSINGS OF LIBERTY TO OURSELVES AND OUR POSTERITY, DO ORDAIN AND ESTABLISH THIS CONSTITUTION FOR THE UNITED STATES OF AMERICA.
linuxserver1.cs.umbc.edu[103]

Iam just little bit confuse on how to start and i need some help.

Here are the English frequencies for each letter :

a 8.167%
b 1.492%
c 2.782%
d 4.253%
e 12.702%
f 2.228%
g 2.015%
h 6.094%
i 6.966%
j 0.153%
k 0.772%
l 4.025%
m 2.406%
n 6.749%
o 7.507%
p 1.929%
q 0.095%
r ...

JoshuaBurleson commented: Show effort -1

asong -4 Light Poster

i have a question but am confuse
the question is create and array of random double floating point numbers,calculate and print the sum off all the numbers in the array.truncates all of the numbers in the array up to 7 decimal places and then calculate and print the sum of the truncated numbers.calculate and print the difference between the actual sum of the numbersand the sum of the truncated numbers.the part i understand was how to
then you can use the java.text.NumberFormat class.

double value = 5.9999999999999;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(7);
String displayValue = nf.format(value);
System.out.println(displayValue);

//should print >5.9999999
but i dont kbnow haw to create a random double floating point numbers it just confuse me ,can someon help me out?please

asong -4 Light Poster

have a java program that have evaluate thefunction,calculate the derivative and roots haw can i demonstrate numerical methods to solve the runge kutta method.
This ma functiuon
package Iterative.Newton;
import java.io.*;
import java.text.DecimalFormat;
public class Newtonlastest {
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Format to display with six decimal places
DecimalFormat root = new DecimalFormat("####0.000000");
//Format to display with seven decimal places
DecimalFormat rootseven = new DecimalFormat("####0.0000000");
//This is the const to select delta
final double select_delta = 0.5;
double xnew;
double fxold;
double fdashxold;
double absfxnew;
int iteration;
System.out.print("Enter the initial approximation for the root: ");
double xold = Double.parseDouble(in.readLine());
iteration =0;
System.out.print("step x fx\n");
System.out.print("--------------------…
do
{
// determine f(xold) and f·xold)
fxold = func(xold);
// printf temp result
System.out.print( "\n");
System.out.print( iteration );
System.out.print( " " + root.format(xold) );
System.out.print( " " + rootseven.format(fxold) );
iteration = iteration + 1;
//fdashxold = derivative_func(xold);

//if calculate by approximate derivative then comment above line, and uncomment below line
fdashxold = appro_derivative(xold, select_delta);
xnew = xold - (fxold/fdashxold);
absfxnew = func(xnew);
if(absfxnew < 0)
{
absfxnew = -absfxnew;
}
xold = xnew;

// check for convergence using the criterion |f(x)| < 0.000001
}
while (absfxnew > 0.000001);
System.out.println("\n");
System.out.print( iteration );
System.out.print(" " + root.format(xold) );
System.out.print( " "+ rootseven.format(func(xold)) );
System.out.println();
System.out.print("\nroot to six decimal places is :");
System.out.print(root.format(xnew));

}
public static double func(double x)
{

return (0.66 pow_int(x, 5) - 8.7 pow_int(x, 4) + 42 pow_int(x, 3) - 90 x *x ...

asong -4 Light Poster

i have this code
[code=Java]//
//Angles.java
//
//
//
//

import java.util.Scanner;

public class Angles
{
public static void main (String[] args)
{
double degree=1/360;
double minutes=1/60;
double seconds=1/60;
double PI=3.14159;;
Scanner scan = new Scanner(System.in);

    // takes the first angles from the user

    System.out.print("Enter the Degrees of the first angle < 360: ");

    int Angle1 = scan.nextInt();

    // takes the first minutes from the user

    System.out.print("Enter the Minutes of the first angle < 60: ");

    int Minutes1 = scan.nextInt();

    // takes the first seconds from the user

    System.out.print("Enter the Seconds of the first angle < 60: ");

    int Seconds1 = scan.nextInt();

    // takes the second angles from the user

    System.out.print("Enter the Degrees of the second angle < 360: ");

    int Angle2 = scan.nextInt();

    // takes the second minutes from the user

    System.out.print("Enter the Minutes of the second angle < 60: ");

    int Minutes2 = scan.nextInt();

    // takes the second seconds from the user

    System.out.print("Enter the Seconds of the second angle < 60: ");

    int Seconds2 = scan.nextInt();

    // adds the seconds

    int SecondsTotal = (Seconds1 + Seconds2);

    SecondsTotal =  SecondsTotal % 60;

    // adds the minutes

    int MinutesTotal = (Minutes1 + Minutes2 + (SecondsTotal % 60));

    MinutesTotal = MinutesTotal % 60;

    // adds the angles

    int AngleTotal = (Angle1 + Angle2 + (MinutesTotal % 60));

    AngleTotal = AngleTotal % 360;

    // prints the angles, minutes, seconds to the user

    System.out.println(Angle1 + "deg" + Minutes1 + "'" + Seconds1 + "'' + " + Angle2 + "deg" + Minutes2 + ...

asong -4 Light Poster

Write a Java program that uses an algorithm implementing the Gauss-Jordan
method to solve the system of linear equations given in the introduction. Your
output must show the output of every calculation to no more than seven (7) decimal
places. You must create and use a function that cuts off the result of each
calculation at exactly seven decimal places and uses this cutoff value in any
subsequent calculation