Page 3 of 13 FirstFirst 12345 ... LastLast
Results 21 to 30 of 128

Thread: [Beginner] Programming Challenge: 3

  1. #21
    Join Date
    Dec 2006
    Location
    Birmingham, England
    Beans
    83
    Distro
    Ubuntu 6.06 Dapper

    Re: [Beginner] Programming Challenge: 3

    Here's my entry.

    Python:
    Code:
    import re
    
    f = open('bhaarat.text').read()
    
    #  Search for sequences containing one or more numbers,
    #  then a full stop, then white-space, then words beginning
    #  with H and S.
    sh = re.compile(r'\d+.\s(H\D+|S\D+)')
    list = sh.findall(f)
    
    out = open('out.text', 'w')
    
    a = len(list)
    while a > 0:
      list.insert(a-1,'. ')
      list.insert(a-1,str(a),)
      a = a - 1
    
    b = "".join(list)
    out.write(b)
    out.close
    
    bh = open('bhaarat.text', 'a')
    bh.write('23. English\n')
    bh.close()

  2. #22
    Join Date
    Jul 2008
    Beans
    11

    Re: [Beginner] Programming Challenge: 3

    Quote Originally Posted by ghostdog74 View Post
    then you are deleting off the numbers.
    Code:
    awk '$2 ~ /^(H|S)/{print d++". "$2 }END{ print "23. English" >> "bhaarat.text"}' bhaarat.text > out.text
    That was the point.

    "Output can be flexible, however, it cannot include the original numbers and some sort of whitespace should separate the words (newlines if you are going for extra credit). Extra credit for correctly numbered lines."

    I am, admittedly, new to linux/unix command line though, so I'm sure there is a better way to do it.

    edit: In fact, I'm gonna have to learn about awk now. That was cool.
    Last edited by iofthemourning; August 9th, 2008 at 08:17 PM.

  3. #23
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Beginner] Programming Challenge: 3

    Quote Originally Posted by jimi_hendrix View Post
    do we have to create a new text file for the output in the program or is that done manually

    also do you mean save it as bhaarat.text or bhaarat.txt?
    bhaarat.text is the input file, and I don't understand the first question. You don't have a choice in the matter I think, you will have to create it.

  4. #24
    Join Date
    Sep 2007
    Location
    Over there --->
    Beans
    157
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [Beginner] Programming Challenge: 3

    Well, my awk is not THAT ubber, so I used a simpler method:

    Code:
    cat bhaarat.text | awk '{print $2}' | egrep "^H|^S" | while read line; do echo $count $line; ((count++)); done | sed 's/Hindi/0 Hindi/' > out.text
    echo "23. English" >> bhaarat.txt
    Going to read those python examples now ...

    Thd.
    Woof !

  5. #25
    Join Date
    May 2008
    Beans
    2

    Re: [Beginner] Programming Challenge: 3

    In Java:

    PHP Code:
    // Beginner Challenge 3 in Java
    // by greps5 8/9/08

    import java.io.*;

    public class 
    Challenge3 {

        public static 
    void main(String[] args) {

            
    BufferedReader fileIn;
            
    BufferedWriter fileOut;
            
    int count 1;
            
    String txtRecord;
            
            
    // initialize the file input and output streams
            
    try {
                
    fileIn = new BufferedReader(new FileReader("bhaarat.text"));
                
    fileOut = new BufferedWriter(new FileWriter("out.text"));
            }
            catch (
    FileNotFoundException ex) {
                
    System.out.println("Error: file 'bhaarat.text' not found.");
                
    System.out.println("Please make sure that the filename is " +
                        
    "spelled correctly and that the file resides in the " +
                        
    "same location as the Challenge3.class file.");
                return;
            }
            catch (
    IOException ex) {
                
    System.out.println("Error: unable to initialize file I/O");
                return;
            } 
    // end try-catch
            
            
    try {
                
    txtRecord fileIn.readLine();
                
                
    System.out.println("File I/O in progress...");
                
                while (
    txtRecord != null) {
                    
    // trim record number from txtRecord
                    
    if (txtRecord.charAt(1) == '.') {
                        
    txtRecord txtRecord.substring(1);
                    }
                    else {
                        
    txtRecord txtRecord.substring(2);
                    } 
    // end if
                    
                    // check first letter of the language and write to file
                    
    if (txtRecord.charAt(2) == 'H' || txtRecord.charAt(2) == 'S') {
                        
    txtRecord "" count txtRecord;
                        
    fileOut.write(txtRecord);
                        
    fileOut.newLine();
                        
    count++;
                    } 
    // end if
                    
                    
    txtRecord fileIn.readLine();
                } 
    // end while
                
                // close file I/O streams
                
    fileIn.close();
                
    fileOut.close();
                
                
    // append new record to bhaarat.text
                
    fileOut = new BufferedWriter(new FileWriter("bhaarat.text"true));
                
    fileOut.write("23. English");
                
    fileOut.newLine();
                
    fileOut.close();
            }
            catch (
    IOException ex){
                
    System.out.println("Error during file I/O");
                return;
            } 
    // end try-catch
            
            
    System.out.println("File I/O finished sucessfully.");
        } 
    // end main



  6. #26
    Join Date
    May 2005
    Beans
    14

    Re: [Beginner] Programming Challenge: 3

    I tried to do this in C++ which is a new language for me.

    So this program checks for two unicode characters I chose randomly in my native tongue. The test data is the same list in tamil, which I have attached. Change line 39 if you want to use different criteria.

    EDIT 1: Bug fixed in the next post (#27)

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    // removes the serial numbers from the beginning of the line
    wstring getlanguage(wstring line) {
      // find the space in the string
      wchar_t delim = ' ';
      wstring::size_type delim_loc = line.find(delim, 0);
    
      // get substring from the first character after space till the end
      if (delim_loc != wstring::npos) 
        return line.substr(delim_loc + 1);
      else
        return line;
    }
    
    int main() {
      wifstream infile;      //input file
      wofstream outfile;     //output file
      wstring line;        //line of data
      int index = 1;        //serial number for output file
      locale loc("");       //unicode
    
      // open file and proceed if file exists
      infile.open("bhaarat.txt");
      infile.imbue(loc);
    
      if (infile.is_open()) {
        outfile.open("out.txt");
        outfile.imbue(loc);
    
        // read a line
        while (getline(infile, line)) {
          wstring lang = getlanguage(line);
          //if first character is one of two unicode chars write to file 
          if (lang.at(0) == L'க' or lang.at(0) == L'த')
            outfile << index++ << ". " << lang << endl;
        }
    
        // free resources
        infile.close();
        outfile.close();
      }
    
      // write a line to the original file
      outfile.open("bhaarat.txt", ios::app);
      if (outfile.is_open())
        outfile << "23. ஆங்கிலம்" << endl;
      outfile.close();
    
      return 0;
    }
    Attached Files Attached Files
    Last edited by chandru; August 9th, 2008 at 08:51 PM.

  7. #27
    Join Date
    May 2005
    Beans
    14

    Re: [Beginner] Programming Challenge: 3

    Bug in the last program (post #26), where the original file was not modified.

    Corrected version

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    // removes the serial numbers from the beginning of the line
    wstring getlanguage(wstring line) {
      // find the space in the string
      wchar_t delim = ' ';
      wstring::size_type delim_loc = line.find(delim, 0);
    
      // get substring from the first character after space till the end
      if (delim_loc != wstring::npos) 
        return line.substr(delim_loc + 1);
      else
        return line;
    }
    
    int main() {
      wifstream infile;      //input file
      wofstream outfile;     //output file
      wstring line;        //line of data
      int index = 1;        //serial number for output file
      locale loc("");       //unicode
    
      // open file and proceed if file exists
      infile.open("bhaarat.txt");
      infile.imbue(loc);
    
      if (infile.is_open()) {
        outfile.open("out.txt");
        outfile.imbue(loc);
    
        // read a line
        while (getline(infile, line)) {
          wstring lang = getlanguage(line);
          //if first character is one of two unicode chars write to file 
          if (lang.at(0) == L'க' or lang.at(0) == L'த')
            outfile << index++ << ". " << lang << endl;
        }
    
        // free resources
        infile.close();
        outfile.close();
      }
    
      // write a line to the original file
      outfile.open("bhaarat.txt", ios::app);
      outfile.imbue(loc);
      if (outfile.is_open()) 
        outfile << L"23. ஆங்கிலம்" << endl;
      outfile.close();
    
      return 0;
    }

  8. #28
    Join Date
    Jun 2008
    Location
    California, USA
    Beans
    1,030
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [Beginner] Programming Challenge: 3

    Here is mine, I might add that unicode thing after I do some reading, so expect some changes, Again suggestions would be appreciated.

    PHP Code:
    import os

    def main
    ():
        if 
    not os.path.exists("bhaarat.text"):
            print 
    "Error: 'bhaarat.text' does not exist! The program cannot continue!"
            
    exit(1)
        
    elif os.path.exists("bhaarat.text"):
            
    inFile open("bhaarat.text")
            
    outFile open("out.text""w" )
            
    lineNumber 0
            
    for line in inFile:
                
    line line.split()[1]
                if 
    line.startswith("H") | line.startswith("S"):
                    
    result "%i. %s\n" % (lineNumberline)
                    
    outFile.write(result)
                    
    lineNumber += 1
            outFile
    .close()
            
    inFile open("bhaarat.text""a")
            
    inFile.write("23. English\n")
                
                
    if 
    __name__ == "__main__":
        
    main() 
    Last edited by OutOfReach; August 9th, 2008 at 10:01 PM.

    Blog | I'm available for programming contributions. C & Python.
    Intel Core i7 920 | EVGA x58 SLI | NVidia GeForce 8600 GT | WD 500GB HDD | Corsair XMS3 3GB | Ubuntu 9.04

  9. #29
    Join Date
    Apr 2006
    Beans
    569
    Distro
    Xubuntu 12.04 Precise Pangolin

    Re: [Beginner] Programming Challenge: 3

    I had no idea that there was any effort behind unicode strings in python. I thought all I'd have to do was put a 'u' before the strings when I first declared them. Good fun. Hopefully I haven't missplaced an error like last time. I'm fairly sure this is good to go though.

    Code could be a little more compact, a few lines could be combined into something smaller, but I think this is easier on the eyes.

    PHP Code:
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # coding=UTF-8

    Hindi=u"हिन्दी"
    Sanskrit=u"संस्कृता वाक"
    langs=[]
    inputText=""    # incase of IOError
    try:    inputText=open('bhaarat.text','r').readlines()
    except IOError:    print "Whoa whoa, where's your bhaarat.text?"
    for items in inputText:
        
    langs.append(items.split('. ')[1].split('\n')[0])

    outputText=u""
    att=0        # Generic counter
    for items in langs:
        if 
    items[0].lower() == 's' or items[0].lower() == 'h':
            if 
    items.lower() == 'hindi'outputText += "%i. %s (%s)\n" %(att,items,Hindi)    
            
    elif items.lower() == 'sanskrit'outputText += "%i. %s (%s)\n" %(att,items,Sanskrit)    
            else:    
    outputText+="%i. %s\n" %(att,items)
            
    att+=1

    open
    ('out.text','w').write(outputText.encode("UTF-8"))
    if 
    inputText[-1].startswith('23'): None    # Don't want to do this more then once
    else:    open('bhaarat.text','a').write("23. English"

  10. #30
    Join Date
    Oct 2007
    Beans
    410

    Re: [Beginner] Programming Challenge: 3

    here's mine:
    I realized I blew it on the last one...d'oh...so stupid, but I think this one works correctly.

    Code:
    /**
    
    Ubuntu forum challenge #2
    File i/o
    
    
    */
    
    import java.util.*;
    import java.io.*;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    
    public class UbuntuFileReaderChallenge{
    
    	ArrayList<String> newFileList;
    	ArrayList<String> revisedOldFileList;
    	BufferedReader br;
    	BufferedWriter newFileBR;
    
    
    	public void readInputFile(File file){
    
    		System.out.println("reading file input...");
    		try{
    			newFileList = new ArrayList<String>();
    			revisedOldFileList = new ArrayList<String>();
    			br = new BufferedReader(new FileReader(file));
    		
    			String line = "";
    			// read input from text file
    		while((line=br.readLine()) != null){
    		// pick out number, figure out what letter each word begins with  and add text to arrayLists
    		populateAndAnalyzeList(line);
    		}
    		System.out.println("writing new file...\n");		
    		writeNewFile();
    
    		// now overwrite old file and add English at the end
    		System.out.println("re-writing original file...");
    		BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    		
    		bw.write("List of Languages\nFile modified by " + this.getClass() + "\nfor Ubuntu Forum Challenge #3\nWritten by Badperson\n\n");
    		int counter = 1;
    		for(Iterator i = revisedOldFileList.iterator(); i.hasNext();){
    		String language = (String)i.next();
    		bw.write(counter + ". " + language + "\n");
    		counter++;
    
    		}
    
    		bw.write(counter + ". " + "English");
    		bw.close();	
    		System.out.println("done.");
    		} catch(IOException e){
    		System.err.println("problem reading input file...make sure bhaarat.text is in the same directory in which the app is run...");
    		e.printStackTrace();
    		}
    
    
    	} // end read input file method
    
    	public void populateAndAnalyzeList(String text){
    	
    
    
    
    	// regex to pick out number
    	Pattern lineFormat = Pattern.compile("\\d+\\.");
    	Matcher lineFormatMatcher = lineFormat.matcher(text);
    		while(lineFormatMatcher.find()){
    
    		// take number out of line
    		text = lineFormatMatcher.replaceAll("");
    		// eliminate leading space
    		text = text.replace(" ", "");
    		revisedOldFileList.add(text);
    			// pick out words that start with h or s and add them to their own list
    			if(text.startsWith("S") || text.startsWith("s") || text.startsWith("H") || text.startsWith("h")){
    			newFileList.add(text);
    			}
    
    		
    		}
    
    
    
    
    	} // end populateAndAnalyzeList method
    
    	public void writeNewFile(){
    
    		try{
    
    		
    		BufferedWriter newFileBR = new BufferedWriter(new FileWriter(new File("out.txt")));
    		newFileBR.write("Output File for Ubuntu Forum Programming Challenge #3\nWritten by Badperson\n\n");
    		// write out new file:
    		int counter = 1;
    
    		for(Iterator i = newFileList.iterator(); i.hasNext();){
    		String language = (String)i.next();
    		newFileBR.write(counter + ". " + language + "\n");
    		counter++;
    		}
    		newFileBR.close();
    
    
    		} catch(IOException e){
    		System.err.println("problem writing new files...");
    		e.printStackTrace();
    		}
    		
    
    
    		
    
    
    	
    
    	}
    
    	
    
    
    //main
    	public static void main(String[] args){
    	new UbuntuFileReaderChallenge().readInputFile(new File("bhaarat.text"));
    	}
    
    
    
    } // end class
    bp

Page 3 of 13 FirstFirst 12345 ... LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •